diff --git a/CHANGELOG.md b/CHANGELOG.md index 99833e57ff8d3..8be325f6e9fc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,17 +1,78 @@ -## 1.12.0 (Unreleased) +## 1.14.0 (Unreleased) + +IMPROVEMENTS: + +* `azurerm_iothub` - exporting the `event_hub_events_endpoint`, `event_hub_events_path`, `event_hub_operations_endpoint` and `event_hub_operations_path` fields [GH-1789] +* `azurerm_iothub` - support for `endpoint` and `route` blocks [GH-1693] + +BUG FIXES: + +* `azurerm_eventhub` - updating the validation to support periods, hyphens and underscores [GH-1795] +* `azurerm_eventhub_authorization_rule` - updating the validation error [GH-1795] +* `azurerm_eventhub_consumer_group` - updating the validation to support periods, hyphens and underscores [GH-1795] +* `azurerm_eventhub_namespace` - updating the validation error [GH-1795] +* `azurerm_kubernetes_cluster` - removing validation for the `pod_cidr` field when `network_plugin` is set to `azure` [GH-1798] +* `azurerm_virtual_machine` - setting the `image_uri` property within the `storage_os_disk` block [GH-1799] + +## 1.13.0 (August 15, 2018) + +FEATURES: + +* **New Data Source:** `azurerm_log_analytics_workspace` ([#1755](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1755)) +* **New Resource:** `azurerm_monitor_action_group` ([#1725](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1725)) + +IMPROVEMENTS: + +* dependencies: upgrading to `2018-04-01` of the IoTHub SDK ([#1717](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1717)) +* Azure CLI Auth - using the `USERPROFILE` environment variable to locate the users home directory, if set ([#1718](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1718)) +* Data Source `azurerm_kubernetes_cluster` - exposing the `max_pods` field within the `agent_pool_profile` block ([#1753](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1753)) +* Data Source: `azurerm_kubernetes_cluster` - exposing the `add_on_profile` block ([#1751](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1751)) +* `azurerm_automation_schedule` - adding the `week_days`, `month_days` and `monthly_occurrence` properties ([#1626](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1626)) +* `azurerm_container_group` - adding a new `commands` field / deprecating the `command` field ([#1740](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1740)) +* `azurerm_iothub` - support for the `Basic` SKU ([#1717](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1717)) +* `azurerm_kubernetes_cluster` - support for `max_pods` within the `agent_pool_profile` block ([#1753](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1753)) +* `azurerm_kubernetes_cluster` - support for the `add_on_profile` block ([#1751](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1751)) +* `azurerm_kubernetes_cluster` - validation for when `pod_cidr` is set with a `network_plugin` set to `azure` ([#1763](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1763)) +* `azurerm_kubernetes_cluster` - `client_id` and `client_secret` in the `service_principal` block are now ForceNew ([#1737](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1737)) +* `azurerm_kubernetes_cluster` - `docker_bridge_cidr`, `dns_service_ip` and `service_cidr` are now conditionally set ([#1715](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1715)) +* `azurerm_lb_nat_rule` - `protocol` property now supports `All` ([#1736](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1736)) +* `azurerm_lb_nat_pool` - `protocol` property now supports `All` ([#1748](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1748)) +* `azurerm_lb_probe` - `protocol` property now supports `Https` ([#1742](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1742)) +* `azurerm_lb_rule` - support for the `All` protocol / adding validation ([#1754](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1754)) + +BUG FIXES: + +* `azurerm_application_insights` - handling a `HTTP 201` being returned from the Create API which working around a breaking change in the API ([#1769](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1769)) +* `azurerm_autoscale_setting` - filtering out the `$tags` tag ([#1770](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1770)) +* `azurerm_eventhub` - allowing underscores in the name field ([#1768](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1768)) +* `azurerm_eventhub_authorization_rule` - allowing underscores in the name field ([#1768](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1768)) +* `azurerm_eventhub_consumer_group` - allowing underscores in the name field ([#1768](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1768)) + +## 1.12.0 (August 03, 2018) + +UPGRADE NOTES: + +* **Please Note:** When upgrading to v1.12.0 of the Azure Provider, you may need to specify the `priority` of any VM Scale Sets created between v1.6 of the Provider and v1.12. ([#1586](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1586)) FEATURES: -* **New Data Source:** `azurerm_container_registry` [GH-1642] +* **New Data Source:** `azurerm_container_registry` ([#1642](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1642)) +* **New Resource:** `azurerm_service_fabric_cluster` ([#4](https://github.com/terraform-providers/terraform-provider-azurerm/issues/4)) IMPROVEMENTS: -* sdk: switching from `WaitForCompletion` -> `WaitForCompletionRef` when polling Future's [GH-1660] -* Data Source: `azurerm_kubernetes_cluster` - support for specifying the `network_profile` block [GH-1479] -* Data Source: `azurerm_kubernetes_cluster` - outputting the `node_resource_group` field [GH-1649] -* `azurerm_kubernetes_cluster` - support for specifying the `network_profile` block [GH-1479] -* `azurerm_kubernetes_cluster` - outputting the `node_resource_group` field [GH-1649] -* `azurerm_virtual_machine` - setting the connection information for Provisioners [GH-1646] +* sdk: switching from `WaitForCompletion` -> `WaitForCompletionRef` when polling Future's ([#1660](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1660)) +* Data Source: `azurerm_kubernetes_cluster` - support for specifying the `network_profile` block ([#1479](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1479)) +* Data Source: `azurerm_kubernetes_cluster` - outputting the `node_resource_group` field ([#1649](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1649)) +* `azurerm_kubernetes_cluster` - support for specifying the `network_profile` block ([#1479](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1479)) +* `azurerm_kubernetes_cluster` - outputting the `node_resource_group` field ([#1649](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1649)) +* `azurerm_role_assignment` - retrying resource creation to match the Azure CLI's behaviour ([#1647](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1647)) +* `azurerm_virtual_machine` - setting the connection information for Provisioners ([#1646](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1646)) + + +BUG FIXES: + +* `azurerm_virtual_machine_scale_set` - removing the default of `priority`, since this isn't set on older instances. ([#1586](https://github.com/terraform-providers/terraform-provider-azurerm/issues/1586)) ## 1.11.0 (July 25, 2018) diff --git a/azurerm/config.go b/azurerm/config.go index 781696b4c853a..023712ee14b9e 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -25,7 +25,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/eventgrid/mgmt/2018-01-01/eventgrid" "github.com/Azure/azure-sdk-for-go/services/eventhub/mgmt/2017-04-01/eventhub" "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" - "github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices" + "github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices" keyVault "github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault" "github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2016-10-01/keyvault" "github.com/Azure/azure-sdk-for-go/services/logic/mgmt/2016-06-01/logic" @@ -50,6 +50,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/scheduler/mgmt/2016-03-01/scheduler" "github.com/Azure/azure-sdk-for-go/services/search/mgmt/2015-08-19/search" "github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus" + "github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2017-10-01/storage" "github.com/Azure/azure-sdk-for-go/services/trafficmanager/mgmt/2017-05-01/trafficmanager" "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2018-02-01/web" @@ -169,6 +170,7 @@ type ArmClient struct { logicWorkflowsClient logic.WorkflowsClient // Monitor + actionGroupsClient insights.ActionGroupsClient monitorAlertRulesClient insights.AlertRulesClient // MSI @@ -215,7 +217,7 @@ type ArmClient struct { resourceGroupsClient resources.GroupsClient subscriptionsClient subscriptions.Client - //Scheduler + // Scheduler schedulerJobCollectionsClient scheduler.JobCollectionsClient schedulerJobsClient scheduler.JobsClient @@ -229,6 +231,9 @@ type ArmClient struct { serviceBusSubscriptionsClient servicebus.SubscriptionsClient serviceBusSubscriptionRulesClient servicebus.RulesClient + // Service Fabric + serviceFabricClustersClient servicefabric.ClustersClient + // Storage storageServiceClient storage.AccountsClient storageUsageClient storage.UsageClient @@ -433,6 +438,7 @@ func getArmClient(c *authentication.Config) (*ArmClient, error) { client.registerResourcesClients(endpoint, c.SubscriptionID, auth) client.registerSearchClients(endpoint, c.SubscriptionID, auth) client.registerServiceBusClients(endpoint, c.SubscriptionID, auth) + client.registerServiceFabricClients(endpoint, c.SubscriptionID, auth) client.registerSchedulerClients(endpoint, c.SubscriptionID, auth) client.registerStorageClients(endpoint, c.SubscriptionID, auth) client.registerTrafficManagerClients(endpoint, c.SubscriptionID, auth) @@ -787,6 +793,10 @@ func (c *ArmClient) registerLogicClients(endpoint, subscriptionId string, auth a } func (c *ArmClient) registerMonitorClients(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { + actionGroupsClient := insights.NewActionGroupsClientWithBaseURI(endpoint, subscriptionId) + c.configureClient(&actionGroupsClient.Client, auth) + c.actionGroupsClient = actionGroupsClient + arc := insights.NewAlertRulesClientWithBaseURI(endpoint, subscriptionId) setUserAgent(&arc.Client) arc.Authorizer = auth @@ -994,6 +1004,12 @@ func (c *ArmClient) registerServiceBusClients(endpoint, subscriptionId string, a c.serviceBusSubscriptionRulesClient = subscriptionRulesClient } +func (c *ArmClient) registerServiceFabricClients(endpoint, subscriptionId string, auth autorest.Authorizer) { + clustersClient := servicefabric.NewClustersClientWithBaseURI(endpoint, subscriptionId) + c.configureClient(&clustersClient.Client, auth) + c.serviceFabricClustersClient = clustersClient +} + func (c *ArmClient) registerStorageClients(endpoint, subscriptionId string, auth autorest.Authorizer) { accountsClient := storage.NewAccountsClientWithBaseURI(endpoint, subscriptionId) c.configureClient(&accountsClient.Client, auth) diff --git a/azurerm/data_source_app_service.go b/azurerm/data_source_app_service.go index 6cdc24e22116f..9bf8e9ab39afe 100644 --- a/azurerm/data_source_app_service.go +++ b/azurerm/data_source_app_service.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/hashicorp/terraform/helper/schema" - azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -28,7 +28,7 @@ func dataSourceArmAppService() *schema.Resource { Computed: true, }, - "site_config": azSchema.AppServiceSiteConfigSchema(), + "site_config": azure.SchemaAppServiceSiteConfig(), "client_affinity_enabled": { Type: schema.TypeBool, @@ -192,7 +192,7 @@ func dataSourceArmAppServiceRead(d *schema.ResourceData, meta interface{}) error return err } - siteConfig := azSchema.FlattenAppServiceSiteConfig(configResp.SiteConfig) + siteConfig := azure.FlattenAppServiceSiteConfig(configResp.SiteConfig) if err := d.Set("site_config", siteConfig); err != nil { return err } diff --git a/azurerm/data_source_key_vault.go b/azurerm/data_source_key_vault.go index b066ca762b4eb..41c1a8f141658 100644 --- a/azurerm/data_source_key_vault.go +++ b/azurerm/data_source_key_vault.go @@ -5,7 +5,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2016-10-01/keyvault" "github.com/hashicorp/terraform/helper/schema" - kvschema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -139,12 +139,12 @@ func dataSourceArmKeyVaultRead(d *schema.ResourceData, meta interface{}) error { d.Set("enabled_for_disk_encryption", props.EnabledForDiskEncryption) d.Set("enabled_for_template_deployment", props.EnabledForTemplateDeployment) if err := d.Set("sku", flattenKeyVaultDataSourceSku(props.Sku)); err != nil { - return fmt.Errorf("Error flattening `sku` for KeyVault %q: %+v", resp.Name, err) + return fmt.Errorf("Error flattening `sku` for KeyVault %q: %+v", *resp.Name, err) } - flattenedPolicies := kvschema.FlattenKeyVaultAccessPolicies(props.AccessPolicies) + flattenedPolicies := azure.FlattenKeyVaultAccessPolicies(props.AccessPolicies) if err := d.Set("access_policy", flattenedPolicies); err != nil { - return fmt.Errorf("Error flattening `access_policy` for KeyVault %q: %+v", resp.Name, err) + return fmt.Errorf("Error flattening `access_policy` for KeyVault %q: %+v", *resp.Name, err) } d.Set("vault_uri", props.VaultURI) } diff --git a/azurerm/data_source_kubernetes_cluster.go b/azurerm/data_source_kubernetes_cluster.go index ae3255e6c1bd0..cf9564ff81fab 100644 --- a/azurerm/data_source_kubernetes_cluster.go +++ b/azurerm/data_source_kubernetes_cluster.go @@ -149,6 +149,11 @@ func dataSourceArmKubernetesCluster() *schema.Resource { Type: schema.TypeString, Computed: true, }, + + "max_pods": { + Type: schema.TypeInt, + Computed: true, + }, }, }, }, @@ -199,6 +204,48 @@ func dataSourceArmKubernetesCluster() *schema.Resource { }, }, + "addon_profile": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "http_application_routing": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "http_application_routing_zone_name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + + "oms_agent": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "log_analytics_workspace_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + }, + }, + }, + "tags": tagsForDataSourceSchema(), }, } @@ -245,23 +292,27 @@ func dataSourceArmKubernetesClusterRead(d *schema.ResourceData, meta interface{} return fmt.Errorf("Error setting `linux_profile`: %+v", err) } + addonProfiles := flattenKubernetesClusterDataSourceAddonProfiles(props.AddonProfiles) + if err := d.Set("addon_profile", addonProfiles); err != nil { + return fmt.Errorf("Error setting `addon_profile`: %+v", err) + } + agentPoolProfiles := flattenKubernetesClusterDataSourceAgentPoolProfiles(props.AgentPoolProfiles) if err := d.Set("agent_pool_profile", agentPoolProfiles); err != nil { return fmt.Errorf("Error setting `agent_pool_profile`: %+v", err) } + networkProfile := flattenKubernetesClusterDataSourceNetworkProfile(props.NetworkProfile) + if err := d.Set("network_profile", networkProfile); err != nil { + return fmt.Errorf("Error setting `network_profile`: %+v", err) + } + servicePrincipal := flattenKubernetesClusterDataSourceServicePrincipalProfile(resp.ManagedClusterProperties.ServicePrincipalProfile) if err := d.Set("service_principal", servicePrincipal); err != nil { return fmt.Errorf("Error setting `service_principal`: %+v", err) } } - networkProfile := flattenKubernetesClusterDataSourceNetworkProfile(resp.NetworkProfile) - - if err := d.Set("network_profile", networkProfile); err != nil { - return fmt.Errorf("Error setting `network_profile`: %+v", err) - } - kubeConfigRaw, kubeConfig := flattenKubernetesClusterDataSourceAccessProfile(&profile) d.Set("kube_config_raw", kubeConfigRaw) @@ -339,6 +390,10 @@ func flattenKubernetesClusterDataSourceAgentPoolProfiles(input *[]containerservi agentPoolProfile["os_type"] = string(profile.OsType) } + if profile.MaxPods != nil { + agentPoolProfile["max_pods"] = int(*profile.MaxPods) + } + agentPoolProfiles = append(agentPoolProfiles, agentPoolProfile) } @@ -419,3 +474,49 @@ func flattenKubernetesClusterDataSourceNetworkProfile(profile *containerservice. return []interface{}{values} } + +func flattenKubernetesClusterDataSourceAddonProfiles(profile map[string]*containerservice.ManagedClusterAddonProfile) interface{} { + values := make(map[string]interface{}, 0) + + routes := make([]interface{}, 0) + if httpApplicationRouting := profile["httpApplicationRouting"]; httpApplicationRouting != nil { + enabled := false + if enabledVal := httpApplicationRouting.Enabled; enabledVal != nil { + enabled = *enabledVal + } + + zoneName := "" + if v := httpApplicationRouting.Config["HTTPApplicationRoutingZoneName"]; v != nil { + zoneName = *v + } + + output := map[string]interface{}{ + "enabled": enabled, + "http_application_routing_zone_name": zoneName, + } + routes = append(routes, output) + } + values["http_application_routing"] = routes + + agents := make([]interface{}, 0) + if omsAgent := profile["omsAgent"]; omsAgent != nil { + enabled := false + if enabledVal := omsAgent.Enabled; enabledVal != nil { + enabled = *enabledVal + } + + workspaceId := "" + if workspaceResourceID := omsAgent.Config["logAnalyticsWorkspaceResourceID"]; workspaceResourceID != nil { + workspaceId = *workspaceResourceID + } + + output := map[string]interface{}{ + "enabled": enabled, + "log_analytics_workspace_id": workspaceId, + } + agents = append(agents, output) + } + values["oms_agent"] = agents + + return []interface{}{values} +} diff --git a/azurerm/data_source_kubernetes_cluster_test.go b/azurerm/data_source_kubernetes_cluster_test.go index 530a35263fb1f..7380984a9d90f 100644 --- a/azurerm/data_source_kubernetes_cluster_test.go +++ b/azurerm/data_source_kubernetes_cluster_test.go @@ -91,6 +91,35 @@ func TestAccDataSourceAzureRMKubernetesCluster_advancedNetworkingAzure(t *testin }) } +func TestAccDataSourceAzureRMKubernetesCluster_advancedNetworkingAzureComplete(t *testing.T) { + dataSourceName := "data.azurerm_kubernetes_cluster.test" + ri := acctest.RandInt() + clientId := os.Getenv("ARM_CLIENT_ID") + clientSecret := os.Getenv("ARM_CLIENT_SECRET") + location := testLocation() + config := testAccDataSourceAzureRMKubernetesCluster_advancedNetworkingAzureComplete(ri, clientId, clientSecret, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMKubernetesClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMKubernetesClusterExists(dataSourceName), + resource.TestCheckResourceAttrSet(dataSourceName, "agent_pool_profile.0.vnet_subnet_id"), + resource.TestCheckResourceAttr(dataSourceName, "network_profile.0.network_plugin", "azure"), + resource.TestCheckResourceAttrSet(dataSourceName, "network_profile.0.network_plugin"), + resource.TestCheckResourceAttrSet(dataSourceName, "network_profile.0.dns_service_ip"), + resource.TestCheckResourceAttrSet(dataSourceName, "network_profile.0.docker_bridge_cidr"), + resource.TestCheckResourceAttrSet(dataSourceName, "network_profile.0.service_cidr"), + ), + }, + }, + }) +} + func TestAccDataSourceAzureRMKubernetesCluster_advancedNetworkingKubenet(t *testing.T) { dataSourceName := "data.azurerm_kubernetes_cluster.test" ri := acctest.RandInt() @@ -120,6 +149,89 @@ func TestAccDataSourceAzureRMKubernetesCluster_advancedNetworkingKubenet(t *test }) } +func TestAccDataSourceAzureRMKubernetesCluster_advancedNetworkingKubenetComplete(t *testing.T) { + dataSourceName := "data.azurerm_kubernetes_cluster.test" + ri := acctest.RandInt() + clientId := os.Getenv("ARM_CLIENT_ID") + clientSecret := os.Getenv("ARM_CLIENT_SECRET") + location := testLocation() + config := testAccDataSourceAzureRMKubernetesCluster_advancedNetworkingKubenetComplete(ri, clientId, clientSecret, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMKubernetesClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMKubernetesClusterExists(dataSourceName), + resource.TestCheckResourceAttrSet(dataSourceName, "agent_pool_profile.0.vnet_subnet_id"), + resource.TestCheckResourceAttr(dataSourceName, "network_profile.0.network_plugin", "kubenet"), + resource.TestCheckResourceAttrSet(dataSourceName, "network_profile.0.network_plugin"), + resource.TestCheckResourceAttrSet(dataSourceName, "network_profile.0.dns_service_ip"), + resource.TestCheckResourceAttrSet(dataSourceName, "network_profile.0.docker_bridge_cidr"), + resource.TestCheckResourceAttrSet(dataSourceName, "network_profile.0.service_cidr"), + ), + }, + }, + }) +} + +func TestAccDataSourceAzureRMKubernetesCluster_addOnProfileOMS(t *testing.T) { + dataSourceName := "data.azurerm_kubernetes_cluster.test" + ri := acctest.RandInt() + clientId := os.Getenv("ARM_CLIENT_ID") + clientSecret := os.Getenv("ARM_CLIENT_SECRET") + location := testLocation() + config := testAccDataSourceAzureRMKubernetesCluster_addOnProfileOMS(ri, clientId, clientSecret, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMKubernetesClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMKubernetesClusterExists(dataSourceName), + resource.TestCheckResourceAttr(dataSourceName, "addon_profile.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "addon_profile.0.oms_agent.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "addon_profile.0.oms_agent.0.enabled", "true"), + resource.TestCheckResourceAttrSet(dataSourceName, "addon_profile.0.oms_agent.0.log_analytics_workspace_id"), + ), + }, + }, + }) +} + +func TestAccDataSourceAzureRMKubernetesCluster_addOnProfileRouting(t *testing.T) { + dataSourceName := "data.azurerm_kubernetes_cluster.test" + ri := acctest.RandInt() + clientId := os.Getenv("ARM_CLIENT_ID") + clientSecret := os.Getenv("ARM_CLIENT_SECRET") + location := testLocation() + config := testAccDataSourceAzureRMKubernetesCluster_addOnProfileRouting(ri, clientId, clientSecret, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMKubernetesClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMKubernetesClusterExists(dataSourceName), + resource.TestCheckResourceAttr(dataSourceName, "addon_profile.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "addon_profile.0.http_application_routing.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "addon_profile.0.http_application_routing.0.enabled", "true"), + resource.TestCheckResourceAttrSet(dataSourceName, "addon_profile.0.http_application_routing.0.http_application_routing_zone_name"), + ), + }, + }, + }) +} + func testAccDataSourceAzureRMKubernetesCluster_basic(rInt int, clientId string, clientSecret string, location string) string { resource := testAccAzureRMKubernetesCluster_basic(rInt, clientId, clientSecret, location) return fmt.Sprintf(` @@ -145,7 +257,19 @@ data "azurerm_kubernetes_cluster" "test" { } func testAccDataSourceAzureRMKubernetesCluster_advancedNetworkingAzure(rInt int, clientId string, clientSecret string, location string) string { - resource := testAccAzureRMKubernetesCluster_advancedNetworkingAzure(rInt, clientId, clientSecret, location) + resource := testAccAzureRMKubernetesCluster_advancedNetworking(rInt, clientId, clientSecret, location, "azure") + return fmt.Sprintf(` +%s + +data "azurerm_kubernetes_cluster" "test" { + name = "${azurerm_kubernetes_cluster.test.name}" + resource_group_name = "${azurerm_kubernetes_cluster.test.resource_group_name}" +} +`, resource) +} + +func testAccDataSourceAzureRMKubernetesCluster_advancedNetworkingAzureComplete(rInt int, clientId string, clientSecret string, location string) string { + resource := testAccAzureRMKubernetesCluster_advancedNetworkingComplete(rInt, clientId, clientSecret, location, "azure") return fmt.Sprintf(` %s @@ -157,7 +281,43 @@ data "azurerm_kubernetes_cluster" "test" { } func testAccDataSourceAzureRMKubernetesCluster_advancedNetworkingKubenet(rInt int, clientId string, clientSecret string, location string) string { - resource := testAccAzureRMKubernetesCluster_advancedNetworkingKubenet(rInt, clientId, clientSecret, location) + resource := testAccAzureRMKubernetesCluster_advancedNetworking(rInt, clientId, clientSecret, location, "kubenet") + return fmt.Sprintf(` +%s + +data "azurerm_kubernetes_cluster" "test" { + name = "${azurerm_kubernetes_cluster.test.name}" + resource_group_name = "${azurerm_kubernetes_cluster.test.resource_group_name}" +} +`, resource) +} + +func testAccDataSourceAzureRMKubernetesCluster_advancedNetworkingKubenetComplete(rInt int, clientId string, clientSecret string, location string) string { + resource := testAccAzureRMKubernetesCluster_advancedNetworkingComplete(rInt, clientId, clientSecret, location, "kubenet") + return fmt.Sprintf(` +%s + +data "azurerm_kubernetes_cluster" "test" { + name = "${azurerm_kubernetes_cluster.test.name}" + resource_group_name = "${azurerm_kubernetes_cluster.test.resource_group_name}" +} +`, resource) +} + +func testAccDataSourceAzureRMKubernetesCluster_addOnProfileOMS(rInt int, clientId string, clientSecret string, location string) string { + resource := testAccAzureRMKubernetesCluster_addonProfileOMS(rInt, clientId, clientSecret, location) + return fmt.Sprintf(` +%s + +data "azurerm_kubernetes_cluster" "test" { + name = "${azurerm_kubernetes_cluster.test.name}" + resource_group_name = "${azurerm_kubernetes_cluster.test.resource_group_name}" +} +`, resource) +} + +func testAccDataSourceAzureRMKubernetesCluster_addOnProfileRouting(rInt int, clientId string, clientSecret string, location string) string { + resource := testAccAzureRMKubernetesCluster_addonProfileRouting(rInt, clientId, clientSecret, location) return fmt.Sprintf(` %s diff --git a/azurerm/data_source_log_analytics_workspace.go b/azurerm/data_source_log_analytics_workspace.go new file mode 100644 index 0000000000000..0604ac864fc04 --- /dev/null +++ b/azurerm/data_source_log_analytics_workspace.go @@ -0,0 +1,102 @@ +package azurerm + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func dataSourceLogAnalyticsWorkspace() *schema.Resource { + return &schema.Resource{ + Read: dataSourceLogAnalyticsWorkspaceRead, + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + + "location": locationForDataSourceSchema(), + + "resource_group_name": resourceGroupNameForDataSourceSchema(), + + "sku": { + Type: schema.TypeString, + Computed: true, + }, + + "retention_in_days": { + Type: schema.TypeInt, + Computed: true, + }, + + "workspace_id": { + Type: schema.TypeString, + Computed: true, + }, + + "portal_url": { + Type: schema.TypeString, + Computed: true, + }, + + "primary_shared_key": { + Type: schema.TypeString, + Computed: true, + Sensitive: true, + }, + + "secondary_shared_key": { + Type: schema.TypeString, + Computed: true, + Sensitive: true, + }, + + "tags": tagsForDataSourceSchema(), + }, + } + +} + +func dataSourceLogAnalyticsWorkspaceRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).workspacesClient + ctx := meta.(*ArmClient).StopContext + + name := d.Get("name").(string) + resGroup := d.Get("resource_group_name").(string) + + resp, err := client.Get(ctx, resGroup, name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Error: Log Analytics workspaces %q (Resource Group %q) was not found", name, resGroup) + } + return fmt.Errorf("Error making Read request on AzureRM Log Analytics workspaces '%s': %+v", name, err) + } + + d.SetId(*resp.ID) + + d.Set("name", resp.Name) + d.Set("resource_group_name", resGroup) + if location := resp.Location; location != nil { + d.Set("location", azureRMNormalizeLocation(*location)) + } + + d.Set("workspace_id", resp.CustomerID) + d.Set("portal_url", resp.PortalURL) + if sku := resp.Sku; sku != nil { + d.Set("sku", sku.Name) + } + d.Set("retention_in_days", resp.RetentionInDays) + + sharedKeys, err := client.GetSharedKeys(ctx, resGroup, name) + if err != nil { + log.Printf("[ERROR] Unable to List Shared keys for Log Analytics workspaces %s: %+v", name, err) + } else { + d.Set("primary_shared_key", sharedKeys.PrimarySharedKey) + d.Set("secondary_shared_key", sharedKeys.SecondarySharedKey) + } + + flattenAndSetTags(d, resp.Tags) + return nil +} diff --git a/azurerm/data_source_log_analytics_workspace_test.go b/azurerm/data_source_log_analytics_workspace_test.go new file mode 100644 index 0000000000000..34aad054c7f2a --- /dev/null +++ b/azurerm/data_source_log_analytics_workspace_test.go @@ -0,0 +1,42 @@ +package azurerm + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccDataSourceAzureRMLogAnalyticsWorkspace_basic(t *testing.T) { + dataSourceName := "data.azurerm_log_analytics_workspace.test" + ri := acctest.RandInt() + config := testAccDataSourceAzureRMLogAnalyticsWorkspace_basicWithDataSource(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMStorageAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(dataSourceName, "sku", "pergb2018"), + resource.TestCheckResourceAttr(dataSourceName, "retention_in_days", "30"), + ), + }, + }, + }) +} + +func testAccDataSourceAzureRMLogAnalyticsWorkspace_basicWithDataSource(rInt int, location string) string { + config := testAccAzureRMLogAnalyticsWorkspace_retentionInDaysComplete(rInt, location) + return fmt.Sprintf(` +%s + +data "azurerm_log_analytics_workspace" "test" { + name = "${azurerm_log_analytics_workspace.test.name}" + resource_group_name = "${azurerm_log_analytics_workspace.test.resource_group_name}" +} +`, config) +} diff --git a/azurerm/data_source_route_table.go b/azurerm/data_source_route_table.go index 08d6c18af18c9..3dc249079d515 100644 --- a/azurerm/data_source_route_table.go +++ b/azurerm/data_source_route_table.go @@ -5,6 +5,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network" "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -14,8 +15,9 @@ func dataSourceArmRouteTable() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.NoZeroValues, }, "resource_group_name": resourceGroupNameForDataSourceSchema(), @@ -124,10 +126,10 @@ func flattenRouteTableDataSourceRoutes(input *[]network.Route) []interface{} { return results } -func flattenRouteTableDataSourceSubnets(input *[]network.Subnet) []string { +func flattenRouteTableDataSourceSubnets(subnets *[]network.Subnet) []string { output := make([]string, 0) - if subnets := input; subnets != nil { + if subnets != nil { for _, subnet := range *subnets { output = append(output, *subnet.ID) } diff --git a/azurerm/data_source_scheduler_job_collection.go b/azurerm/data_source_scheduler_job_collection.go index 657da5b75b01c..cdfd0f2827040 100644 --- a/azurerm/data_source_scheduler_job_collection.go +++ b/azurerm/data_source_scheduler_job_collection.go @@ -105,7 +105,7 @@ func dataSourceArmSchedulerJobCollectionRead(d *schema.ResourceData, meta interf d.Set("state", string(properties.State)) if err := d.Set("quota", flattenAzureArmSchedulerJobCollectionQuota(properties.Quota)); err != nil { - return fmt.Errorf("Error flattening quota for Job Collection %q (Resource Group %q): %+v", collection.Name, resourceGroup, err) + return fmt.Errorf("Error flattening quota for Job Collection %q (Resource Group %q): %+v", *collection.Name, resourceGroup, err) } } diff --git a/azurerm/data_source_subscription.go b/azurerm/data_source_subscription.go index c872549c84007..5d0848467df86 100644 --- a/azurerm/data_source_subscription.go +++ b/azurerm/data_source_subscription.go @@ -4,14 +4,14 @@ import ( "fmt" "github.com/hashicorp/terraform/helper/schema" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/subscription" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) func dataSourceArmSubscription() *schema.Resource { return &schema.Resource{ Read: dataSourceArmSubscriptionRead, - Schema: subscription.SubscriptionSchema(true), + Schema: azure.SchemaSubscription(true), } } diff --git a/azurerm/data_source_subscriptions.go b/azurerm/data_source_subscriptions.go index de95b7035ba9a..87bb2106919f7 100644 --- a/azurerm/data_source_subscriptions.go +++ b/azurerm/data_source_subscriptions.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/hashicorp/terraform/helper/schema" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/subscription" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" ) func dataSourceArmSubscriptions() *schema.Resource { @@ -16,7 +16,7 @@ func dataSourceArmSubscriptions() *schema.Resource { Type: schema.TypeList, Computed: true, Elem: &schema.Resource{ - Schema: subscription.SubscriptionSchema(false), + Schema: azure.SchemaSubscription(false), }, }, }, diff --git a/azurerm/express_route_circuit.go b/azurerm/express_route_circuit.go index 67204e81c8299..1dcf263d45908 100644 --- a/azurerm/express_route_circuit.go +++ b/azurerm/express_route_circuit.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network" - "github.com/hashicorp/errwrap" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -26,7 +25,7 @@ func retrieveErcByResourceId(resourceId string, meta interface{}) (erc *network. resGroup, name, err := extractResourceGroupAndErcName(resourceId) if err != nil { - return nil, "", errwrap.Wrapf("Error Parsing Azure Resource ID - {{err}}", err) + return nil, "", fmt.Errorf("Error Parsing Azure Resource ID -: %+v", err) } resp, err := ercClient.Get(ctx, resGroup, name) @@ -34,7 +33,7 @@ func retrieveErcByResourceId(resourceId string, meta interface{}) (erc *network. if utils.ResponseWasNotFound(resp.Response) { return nil, "", nil } - return nil, "", errwrap.Wrapf(fmt.Sprintf("Error making Read request on Express Route Circuit %s: {{err}}", name), err) + return nil, "", fmt.Errorf("Error making Read request on Express Route Circuit %s: %+v", name, err) } return &resp, resGroup, nil diff --git a/azurerm/helpers/schema/app_service.go b/azurerm/helpers/azure/app_service.go similarity index 96% rename from azurerm/helpers/schema/app_service.go rename to azurerm/helpers/azure/app_service.go index 202777de2df9d..14cca09c524e5 100644 --- a/azurerm/helpers/schema/app_service.go +++ b/azurerm/helpers/azure/app_service.go @@ -1,4 +1,4 @@ -package schema +package azure import ( "log" @@ -8,10 +8,11 @@ import ( "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2018-02-01/web" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) -func AppServiceSiteConfigSchema() *schema.Schema { +func SchemaAppServiceSiteConfig() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, Optional: true, @@ -39,7 +40,7 @@ func AppServiceSiteConfigSchema() *schema.Schema { "v2.0", "v4.0", }, true), - DiffSuppressFunc: IgnoreCaseDiffSuppressFunc, + DiffSuppressFunc: suppress.CaseDifference, }, "http2_enabled": { @@ -83,7 +84,7 @@ func AppServiceSiteConfigSchema() *schema.Schema { "JETTY", "TOMCAT", }, true), - DiffSuppressFunc: IgnoreCaseDiffSuppressFunc, + DiffSuppressFunc: suppress.CaseDifference, }, "java_container_version": { @@ -105,7 +106,7 @@ func AppServiceSiteConfigSchema() *schema.Schema { string(web.Classic), string(web.Integrated), }, true), - DiffSuppressFunc: IgnoreCaseDiffSuppressFunc, + DiffSuppressFunc: suppress.CaseDifference, }, "php_version": { @@ -144,7 +145,7 @@ func AppServiceSiteConfigSchema() *schema.Schema { "VS2015", "VS2017", }, true), - DiffSuppressFunc: IgnoreCaseDiffSuppressFunc, + DiffSuppressFunc: suppress.CaseDifference, }, "scm_type": { diff --git a/azurerm/helpers/azure/eventhub.go b/azurerm/helpers/azure/eventhub.go index f346e9a3de663..1859cef0b47fc 100644 --- a/azurerm/helpers/azure/eventhub.go +++ b/azurerm/helpers/azure/eventhub.go @@ -15,28 +15,28 @@ import ( func ValidateEventHubNamespaceName() schema.SchemaValidateFunc { return validation.StringMatch( regexp.MustCompile("^[a-zA-Z][-a-zA-Z0-9]{4,48}[a-zA-Z0-9]$"), - "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 and be between 6 and 50 characters long.", + "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 and be between 6 and 50 characters long.", ) } func ValidateEventHubName() schema.SchemaValidateFunc { return validation.StringMatch( - regexp.MustCompile("^[a-zA-Z][-a-zA-Z0-9]{4,48}[a-zA-Z0-9]$"), - "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 and be between 6 and 50 characters long.", + regexp.MustCompile("^[a-zA-Z0-9]([-._a-zA-Z0-9]{0,48}[a-zA-Z0-9])?$"), + "The event hub name can contain only letters, numbers, periods (.), hyphens (-),and underscores (_), up to 50 characters, and it must begin and end with a letter or number.", ) } func ValidateEventHubConsumerName() schema.SchemaValidateFunc { return validation.StringMatch( - regexp.MustCompile("^[a-zA-Z][-a-zA-Z0-9]{4,48}[a-zA-Z0-9]$"), - "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 and be between 6 and 50 characters long.", + regexp.MustCompile("^[a-zA-Z0-9]([-._a-zA-Z0-9]{0,48}[a-zA-Z0-9])?$"), + "The consumer group name can contain only letters, numbers, periods (.), hyphens (-),and underscores (_), up to 50 characters, and it must begin and end with a letter or number.", ) } func ValidateEventHubAuthorizationRuleName() schema.SchemaValidateFunc { return validation.StringMatch( - regexp.MustCompile("^[a-zA-Z0-9][-._a-zA-Z0-9]{0,48}([a-zA-Z0-9])?$"), - "The name can contain only letters, numbers, periods, hyphens and underscores. The name must start and end with a letter or number and be less the 50 characters long.", + regexp.MustCompile("^[a-zA-Z0-9]([-._a-zA-Z0-9]{0,48}[a-zA-Z0-9])?$"), + "The authorization rule name can contain only letters, numbers, periods, hyphens and underscores. The name must start and end with a letter or number and be up to 50 characters long.", ) } diff --git a/azurerm/helpers/azure/eventhub_test.go b/azurerm/helpers/azure/eventhub_test.go new file mode 100644 index 0000000000000..11cbf19d7f4ed --- /dev/null +++ b/azurerm/helpers/azure/eventhub_test.go @@ -0,0 +1,65 @@ +package azure + +import ( + "strings" + "testing" +) + +func TestValidateEventHubName(t *testing.T) { + tests := []struct { + name string + input string + valid bool + }{ + { + name: "Valid short name", + input: "abc", + valid: true, + }, + { + name: "Valid short name", + input: "a", + valid: true, + }, + { + name: "Valid name with dot", + input: "a.b", + valid: true, + }, + { + name: "Just a digit", + input: "1", + valid: true, + }, + { + name: "Invalid long name", + input: strings.Repeat("a", 51), + valid: false, + }, + { + name: "Invalid short name", + input: ".", + valid: false, + }, + { + name: "Invalid name with period at end", + input: "a.", + valid: false, + }, + { + name: "empty name", + input: "", + valid: false, + }, + } + var validationFunction = ValidateEventHubName() + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := validationFunction(tt.input, "") + valid := err == nil + if valid != tt.valid { + t.Errorf("Expected valid status %t but got %t for input %s", tt.valid, valid, tt.input) + } + }) + } +} diff --git a/azurerm/helpers/schema/key_vault_access_policy.go b/azurerm/helpers/azure/key_vault_access_policy.go similarity index 97% rename from azurerm/helpers/schema/key_vault_access_policy.go rename to azurerm/helpers/azure/key_vault_access_policy.go index b73612f788ab1..fafcdec9a84d8 100644 --- a/azurerm/helpers/schema/key_vault_access_policy.go +++ b/azurerm/helpers/azure/key_vault_access_policy.go @@ -1,4 +1,4 @@ -package schema +package azure import ( "github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2016-10-01/keyvault" @@ -8,7 +8,7 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" ) -func KeyVaultCertificatePermissionsSchema() *schema.Schema { +func SchemaKeyVaultCertificatePermissions() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, Optional: true, @@ -35,7 +35,7 @@ func KeyVaultCertificatePermissionsSchema() *schema.Schema { } } -func KeyVaultKeyPermissionsSchema() *schema.Schema { +func SchemaKeyVaultKeyPermissions() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, Required: true, @@ -64,7 +64,7 @@ func KeyVaultKeyPermissionsSchema() *schema.Schema { } } -func KeyVaultSecretPermissionsSchema() *schema.Schema { +func SchemaKeyVaultSecretPermissions() *schema.Schema { return &schema.Schema{ Type: schema.TypeList, Required: true, diff --git a/azurerm/helpers/subscription/subscription.go b/azurerm/helpers/azure/subscription.go similarity index 88% rename from azurerm/helpers/subscription/subscription.go rename to azurerm/helpers/azure/subscription.go index 59f1331bd6625..38bf5c23a46d7 100644 --- a/azurerm/helpers/subscription/subscription.go +++ b/azurerm/helpers/azure/subscription.go @@ -1,10 +1,10 @@ -package subscription +package azure import ( "github.com/hashicorp/terraform/helper/schema" ) -func SubscriptionSchema(subscriptionIDOptional bool) map[string]*schema.Schema { +func SchemaSubscription(subscriptionIDOptional bool) map[string]*schema.Schema { s := map[string]*schema.Schema{ "subscription_id": { Type: schema.TypeString, diff --git a/azurerm/helpers/schema/diff_suppress_func.go b/azurerm/helpers/schema/diff_suppress_func.go deleted file mode 100644 index a622ff7f74c08..0000000000000 --- a/azurerm/helpers/schema/diff_suppress_func.go +++ /dev/null @@ -1,19 +0,0 @@ -package schema - -import ( - "strings" - - "github.com/hashicorp/terraform/helper/schema" -) - -// ignoreCaseDiffSuppressFunc is a DiffSuppressFunc from helper/schema that is -// used to ignore any case-changes in a return value. -func IgnoreCaseDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool { - return strings.ToLower(old) == strings.ToLower(new) -} - -// ignoreCaseStateFunc is a StateFunc from helper/schema that converts the -// supplied value to lower before saving to state for consistency. -func IgnoreCaseStateFunc(val interface{}) string { - return strings.ToLower(val.(string)) -} diff --git a/azurerm/helpers/validate/network.go b/azurerm/helpers/validate/network.go index 65d4fcec39bdf..390d5721f6791 100644 --- a/azurerm/helpers/validate/network.go +++ b/azurerm/helpers/validate/network.go @@ -45,3 +45,17 @@ func MACAddress(i interface{}, k string) (_ []string, errors []error) { return } + +func PortNumber(i interface{}, k string) (_ []string, errors []error) { + v, ok := i.(int) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %q to be int", k)) + return + } + + if v < 1 || 65535 < v { + errors = append(errors, fmt.Errorf("%q is not a valid port number: %q", k, i)) + } + + return +} diff --git a/azurerm/helpers/validate/network_test.go b/azurerm/helpers/validate/network_test.go index 2e6e8ac55d9c3..b2e91fdd7bb5f 100644 --- a/azurerm/helpers/validate/network_test.go +++ b/azurerm/helpers/validate/network_test.go @@ -1,6 +1,9 @@ package validate -import "testing" +import ( + "strconv" + "testing" +) func TestIPv4Address(t *testing.T) { cases := []struct { @@ -147,3 +150,49 @@ func TestMACAddress(t *testing.T) { }) } } + +func TestPortNumber(t *testing.T) { + cases := []struct { + Port int + Errors int + }{ + { + Port: -1, + Errors: 1, + }, + { + Port: 0, + Errors: 1, + }, + { + Port: 1, + Errors: 0, + }, + { + Port: 8477, + Errors: 0, + }, + { + Port: 65535, + Errors: 0, + }, + { + Port: 65536, + Errors: 1, + }, + { + Port: 7000000, + Errors: 1, + }, + } + + for _, tc := range cases { + t.Run(strconv.Itoa(tc.Port), func(t *testing.T) { + _, errors := PortNumber(tc.Port, "test") + + if len(errors) != tc.Errors { + t.Fatalf("Expected PortNumber to return %d error(s) not %d", len(errors), tc.Errors) + } + }) + } +} diff --git a/azurerm/import_arm_iothub_test.go b/azurerm/import_arm_iothub_test.go index 6e33e6a1a7b99..23f8ab35d8f1a 100644 --- a/azurerm/import_arm_iothub_test.go +++ b/azurerm/import_arm_iothub_test.go @@ -11,7 +11,30 @@ func TestAccAzureRMIotHub_importBasic(t *testing.T) { resourceName := "azurerm_iothub.test" ri := acctest.RandInt() - config := testAccAzureRMIotHub_basicStandard(ri, testLocation()) + config := testAccAzureRMIotHub_basic(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMIotHubDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMIotHub_importStandard(t *testing.T) { + resourceName := "azurerm_iothub.test" + + ri := acctest.RandInt() + config := testAccAzureRMIotHub_standard(ri, testLocation()) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, diff --git a/azurerm/loadbalancer.go b/azurerm/loadbalancer.go index 53f83da8abf26..4b37055080c79 100644 --- a/azurerm/loadbalancer.go +++ b/azurerm/loadbalancer.go @@ -8,7 +8,6 @@ import ( "strings" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network" - "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" ) @@ -30,7 +29,7 @@ func retrieveLoadBalancerById(loadBalancerId string, meta interface{}) (*network resGroup, name, err := resourceGroupAndLBNameFromId(loadBalancerId) if err != nil { - return nil, false, errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err) + return nil, false, fmt.Errorf("Error Getting Load Balancer Name and Group:: %+v", err) } resp, err := client.Get(ctx, resGroup, name, "") @@ -38,7 +37,7 @@ func retrieveLoadBalancerById(loadBalancerId string, meta interface{}) (*network if resp.StatusCode == http.StatusNotFound { return nil, false, nil } - return nil, false, fmt.Errorf("Error making Read request on Azure LoadBalancer %s: %s", name, err) + return nil, false, fmt.Errorf("Error making Read request on Azure Load Balancer %s: %s", name, err) } return &resp, true, nil @@ -132,7 +131,7 @@ func loadbalancerStateRefreshFunc(ctx context.Context, client network.LoadBalanc return func() (interface{}, string, error) { res, err := client.Get(ctx, resourceGroupName, loadbalancer, "") if err != nil { - return nil, "", fmt.Errorf("Error issuing read request in loadbalancerStateRefreshFunc to Azure ARM for LoadBalancer '%s' (RG: '%s'): %s", loadbalancer, resourceGroupName, err) + return nil, "", fmt.Errorf("Error issuing read request in loadbalancerStateRefreshFunc to Azure ARM for Load Balancer '%s' (RG: '%s'): %s", loadbalancer, resourceGroupName, err) } return res, *res.LoadBalancerPropertiesFormat.ProvisioningState, nil diff --git a/azurerm/provider.go b/azurerm/provider.go index 71c23b2d5ec23..a725a33fcfa8f 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -16,7 +16,7 @@ import ( "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/authentication" - azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" ) // Provider returns a terraform.ResourceProvider. @@ -97,6 +97,7 @@ func Provider() terraform.ResourceProvider { "azurerm_key_vault_access_policy": dataSourceArmKeyVaultAccessPolicy(), "azurerm_key_vault_secret": dataSourceArmKeyVaultSecret(), "azurerm_kubernetes_cluster": dataSourceArmKubernetesCluster(), + "azurerm_log_analytics_workspace": dataSourceLogAnalyticsWorkspace(), "azurerm_logic_app_workflow": dataSourceArmLogicAppWorkflow(), "azurerm_managed_disk": dataSourceArmManagedDisk(), "azurerm_network_interface": dataSourceArmNetworkInterface(), @@ -198,6 +199,7 @@ func Provider() terraform.ResourceProvider { "azurerm_managed_disk": resourceArmManagedDisk(), "azurerm_management_lock": resourceArmManagementLock(), "azurerm_metric_alertrule": resourceArmMetricAlertRule(), + "azurerm_monitor_action_group": resourceArmMonitorActionGroup(), "azurerm_mysql_configuration": resourceArmMySQLConfiguration(), "azurerm_mysql_database": resourceArmMySqlDatabase(), "azurerm_mysql_firewall_rule": resourceArmMySqlFirewallRule(), @@ -235,6 +237,7 @@ func Provider() terraform.ResourceProvider { "azurerm_servicebus_subscription_rule": resourceArmServiceBusSubscriptionRule(), "azurerm_servicebus_topic": resourceArmServiceBusTopic(), "azurerm_servicebus_topic_authorization_rule": resourceArmServiceBusTopicAuthorizationRule(), + "azurerm_service_fabric_cluster": resourceArmServiceFabricCluster(), "azurerm_snapshot": resourceArmSnapshot(), "azurerm_scheduler_job": resourceArmSchedulerJob(), "azurerm_scheduler_job_collection": resourceArmSchedulerJobCollection(), @@ -388,6 +391,7 @@ func determineAzureResourceProvidersToRegister(providerList []resources.Provider "Microsoft.Resources": {}, "Microsoft.Search": {}, "Microsoft.ServiceBus": {}, + "Microsoft.ServiceFabric": {}, "Microsoft.Sql": {}, "Microsoft.Storage": {}, } @@ -436,9 +440,9 @@ func registerAzureResourceProvidersWithSubscription(ctx context.Context, provide // armMutexKV is the instance of MutexKV for ARM resources var armMutexKV = mutexkv.NewMutexKV() -// Deprecated - use `azschema.IgnoreCaseDiffSuppressFunc` instead +// Deprecated: use `suppress.CaseDifference` instead func ignoreCaseDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool { - return azSchema.IgnoreCaseDiffSuppressFunc(k, old, new, d) + return suppress.CaseDifference(k, old, new, d) } // ignoreCaseStateFunc is a StateFunc from helper/schema that converts the @@ -448,8 +452,7 @@ func ignoreCaseStateFunc(val interface{}) string { } func userDataDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool { - oldValue := userDataStateFunc(old) - return oldValue == new + return userDataStateFunc(old) == new } func userDataStateFunc(v interface{}) string { diff --git a/azurerm/resource_arm_app_service.go b/azurerm/resource_arm_app_service.go index 0d0e7d2ec6854..c09f632ceb038 100644 --- a/azurerm/resource_arm_app_service.go +++ b/azurerm/resource_arm_app_service.go @@ -8,7 +8,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2018-02-01/web" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" - azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -67,7 +67,7 @@ func resourceArmAppService() *schema.Resource { ForceNew: true, }, - "site_config": azSchema.AppServiceSiteConfigSchema(), + "site_config": azure.SchemaAppServiceSiteConfig(), "client_affinity_enabled": { Type: schema.TypeBool, @@ -208,7 +208,7 @@ func resourceArmAppServiceCreate(d *schema.ResourceData, meta interface{}) error httpsOnly := d.Get("https_only").(bool) tags := d.Get("tags").(map[string]interface{}) - siteConfig := azSchema.ExpandAppServiceSiteConfig(d.Get("site_config")) + siteConfig := azure.ExpandAppServiceSiteConfig(d.Get("site_config")) siteEnvelope := web.Site{ Location: &location, @@ -272,7 +272,7 @@ func resourceArmAppServiceUpdate(d *schema.ResourceData, meta interface{}) error httpsOnly := d.Get("https_only").(bool) tags := d.Get("tags").(map[string]interface{}) - siteConfig := azSchema.ExpandAppServiceSiteConfig(d.Get("site_config")) + siteConfig := azure.ExpandAppServiceSiteConfig(d.Get("site_config")) siteEnvelope := web.Site{ Location: &location, Tags: expandTags(tags), @@ -296,7 +296,7 @@ func resourceArmAppServiceUpdate(d *schema.ResourceData, meta interface{}) error if d.HasChange("site_config") { // update the main configuration - siteConfig := azSchema.ExpandAppServiceSiteConfig(d.Get("site_config")) + siteConfig := azure.ExpandAppServiceSiteConfig(d.Get("site_config")) siteConfigResource := web.SiteConfigResource{ SiteConfig: &siteConfig, } @@ -451,7 +451,7 @@ func resourceArmAppServiceRead(d *schema.ResourceData, meta interface{}) error { return err } - siteConfig := azSchema.FlattenAppServiceSiteConfig(configResp.SiteConfig) + siteConfig := azure.FlattenAppServiceSiteConfig(configResp.SiteConfig) if err := d.Set("site_config", siteConfig); err != nil { return err } diff --git a/azurerm/resource_arm_app_service_slot.go b/azurerm/resource_arm_app_service_slot.go index 9dbf53ab8cd2c..294a6caae82cc 100644 --- a/azurerm/resource_arm_app_service_slot.go +++ b/azurerm/resource_arm_app_service_slot.go @@ -7,7 +7,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2018-02-01/web" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" - azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -72,7 +72,7 @@ func resourceArmAppServiceSlot() *schema.Resource { ForceNew: true, }, - "site_config": azSchema.AppServiceSiteConfigSchema(), + "site_config": azure.SchemaAppServiceSiteConfig(), "client_affinity_enabled": { Type: schema.TypeBool, @@ -159,7 +159,7 @@ func resourceArmAppServiceSlotCreate(d *schema.ResourceData, meta interface{}) e httpsOnly := d.Get("https_only").(bool) tags := d.Get("tags").(map[string]interface{}) - siteConfig := azSchema.ExpandAppServiceSiteConfig(d.Get("site_config")) + siteConfig := azure.ExpandAppServiceSiteConfig(d.Get("site_config")) siteEnvelope := web.Site{ Location: &location, Tags: expandTags(tags), @@ -230,7 +230,7 @@ func resourceArmAppServiceSlotUpdate(d *schema.ResourceData, meta interface{}) e location := azureRMNormalizeLocation(d.Get("location").(string)) appServicePlanId := d.Get("app_service_plan_id").(string) slot := id.Path["slots"] - siteConfig := azSchema.ExpandAppServiceSiteConfig(d.Get("site_config")) + siteConfig := azure.ExpandAppServiceSiteConfig(d.Get("site_config")) enabled := d.Get("enabled").(bool) httpsOnly := d.Get("https_only").(bool) tags := d.Get("tags").(map[string]interface{}) @@ -259,7 +259,7 @@ func resourceArmAppServiceSlotUpdate(d *schema.ResourceData, meta interface{}) e } if d.HasChange("site_config") { // update the main configuration - siteConfig := azSchema.ExpandAppServiceSiteConfig(d.Get("site_config")) + siteConfig := azure.ExpandAppServiceSiteConfig(d.Get("site_config")) siteConfigResource := web.SiteConfigResource{ SiteConfig: &siteConfig, } @@ -372,7 +372,7 @@ func resourceArmAppServiceSlotRead(d *schema.ResourceData, meta interface{}) err return err } - siteConfig := azSchema.FlattenAppServiceSiteConfig(configResp.SiteConfig) + siteConfig := azure.FlattenAppServiceSiteConfig(configResp.SiteConfig) if err := d.Set("site_config", siteConfig); err != nil { return err } diff --git a/azurerm/resource_arm_application_gateway.go b/azurerm/resource_arm_application_gateway.go index f2b059223afba..5a52c00f05a1e 100644 --- a/azurerm/resource_arm_application_gateway.go +++ b/azurerm/resource_arm_application_gateway.go @@ -7,7 +7,6 @@ import ( "strings" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network" - "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/helper/hashcode" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" @@ -776,12 +775,12 @@ func resourceArmApplicationGatewayCreateUpdate(d *schema.ResourceData, meta inte func resourceArmApplicationGatewayRead(d *schema.ResourceData, meta interface{}) error { id, err := parseAzureResourceID(d.Id()) if err != nil { - return errwrap.Wrapf("Error parsing ApplicationGateway ID {{err}}", err) + return fmt.Errorf("Error parsing ApplicationGateway ID: %+v", err) } applicationGateway, exists, err := retrieveApplicationGatewayById(d.Id(), meta) if err != nil { - return errwrap.Wrapf("Error Getting ApplicationGateway By ID {{err}}", err) + return fmt.Errorf("Error Getting ApplicationGateway By ID: %+v", err) } if !exists { d.SetId("") @@ -847,7 +846,7 @@ func resourceArmApplicationGatewayDelete(d *schema.ResourceData, meta interface{ id, err := parseAzureResourceID(d.Id()) if err != nil { - return errwrap.Wrapf("Error Parsing Azure Resource ID {{err}}", err) + return fmt.Errorf("Error Parsing Azure Resource ID: %+v", err) } resGroup := id.ResourceGroup name := id.Path["applicationGateways"] @@ -883,7 +882,7 @@ func retrieveApplicationGatewayById(applicationGatewayID string, meta interface{ resGroup, name, err := ApplicationGatewayResGroupAndNameFromID(applicationGatewayID) if err != nil { - return nil, false, errwrap.Wrapf("Error Getting ApplicationGateway Name and Group: {{err}}", err) + return nil, false, fmt.Errorf("Error Getting ApplicationGateway Name and Group:: %+v", err) } resp, err := client.Get(ctx, resGroup, name) diff --git a/azurerm/resource_arm_application_insights.go b/azurerm/resource_arm_application_insights.go index 7bc184f4ef705..dbd74eedabcf5 100644 --- a/azurerm/resource_arm_application_insights.go +++ b/azurerm/resource_arm_application_insights.go @@ -88,14 +88,19 @@ func resourceArmApplicationInsightsCreateOrUpdate(d *schema.ResourceData, meta i Tags: expandTags(tags), } - _, err := client.CreateOrUpdate(ctx, resGroup, name, insightProperties) + resp, err := client.CreateOrUpdate(ctx, resGroup, name, insightProperties) if err != nil { - return err + // @tombuildsstuff - from 2018-08-14 the Create call started returning a 201 instead of 200 + // which doesn't match the Swagger - this works around it until that's fixed + // BUG: https://github.com/Azure/azure-sdk-for-go/issues/2465 + if resp.StatusCode != http.StatusCreated { + return fmt.Errorf("Error creating Application Insights %q (Resource Group %q): %+v", name, resGroup, err) + } } read, err := client.Get(ctx, resGroup, name) if err != nil { - return err + return fmt.Errorf("Error retrieving Application Insights %q (Resource Group %q): %+v", name, resGroup, err) } if read.ID == nil { return fmt.Errorf("Cannot read AzureRM Application Insights '%s' (Resource Group %s) ID", name, resGroup) diff --git a/azurerm/resource_arm_automation_schedule.go b/azurerm/resource_arm_automation_schedule.go index 2c6a6b0f6024e..d8b1edcc559cc 100644 --- a/azurerm/resource_arm_automation_schedule.go +++ b/azurerm/resource_arm_automation_schedule.go @@ -11,6 +11,7 @@ import ( "github.com/Azure/go-autorest/autorest/date" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/set" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" @@ -107,14 +108,87 @@ func resourceArmAutomationSchedule() *schema.Resource { //todo figure out how to validate this properly }, - //todo missing properties: week_days, month_days, month_week_day from advanced automation section + "week_days": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{ + string(automation.Monday), + string(automation.Tuesday), + string(automation.Wednesday), + string(automation.Thursday), + string(automation.Friday), + string(automation.Saturday), + string(automation.Sunday), + }, true), + }, + Set: set.HashStringIgnoreCase, + ConflictsWith: []string{"month_days", "monthly_occurrence"}, + }, + + "month_days": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeInt, + ValidateFunc: validate.IntBetweenAndNot(-1, 31, 0), + }, + Set: set.HashInt, + ConflictsWith: []string{"week_days", "monthly_occurrence"}, + }, + + "monthly_occurrence": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "day": { + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: suppress.CaseDifference, + ValidateFunc: validation.StringInSlice([]string{ + string(automation.Monday), + string(automation.Tuesday), + string(automation.Wednesday), + string(automation.Thursday), + string(automation.Friday), + string(automation.Saturday), + string(automation.Sunday), + }, true), + }, + "occurrence": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validate.IntBetweenAndNot(-1, 5, 0), + }, + }, + }, + ConflictsWith: []string{"week_days", "month_days"}, + }, }, CustomizeDiff: func(diff *schema.ResourceDiff, v interface{}) error { + frequency := strings.ToLower(diff.Get("frequency").(string)) interval, _ := diff.GetOk("interval") - if strings.ToLower(diff.Get("frequency").(string)) == "onetime" && interval.(int) > 0 { - return fmt.Errorf("interval canot be set when frequency is not OneTime") + if frequency == "onetime" && interval.(int) > 0 { + return fmt.Errorf("`interval` cannot be set when frequency is `OneTime`") + } + + _, hasWeekDays := diff.GetOk("week_days") + if hasWeekDays && frequency != "week" { + return fmt.Errorf("`week_days` can only be set when frequency is `Week`") + } + + _, hasMonthDays := diff.GetOk("month_days") + if hasMonthDays && frequency != "month" { + return fmt.Errorf("`month_days` can only be set when frequency is `Month`") + } + + _, hasMonthlyOccurances := diff.GetOk("monthly_occurrence") + if hasMonthlyOccurances && frequency != "month" { + return fmt.Errorf("`monthly_occurrence` can only be set when frequency is `Month`") } _, hasAccount := diff.GetOk("automation_account_name") @@ -193,6 +267,16 @@ func resourceArmAutomationScheduleCreateUpdate(d *schema.ResourceData, meta inte properties.Interval = 1 } } + + //only pay attention to the advanced schedule fields if frequency is either Week or Month + if properties.Frequency == automation.Week || properties.Frequency == automation.Month { + advancedRef, err := expandArmAutomationScheduleAdvanced(d, d.Id() != "") + if err != nil { + return err + } + properties.AdvancedSchedule = advancedRef + } + _, err := client.CreateOrUpdate(ctx, resGroup, accountName, name, parameters) if err != nil { return err @@ -257,6 +341,18 @@ func resourceArmAutomationScheduleRead(d *schema.ResourceData, meta interface{}) if v := resp.TimeZone; v != nil { d.Set("timezone", v) } + + if v := resp.AdvancedSchedule; v != nil { + if err := d.Set("week_days", flattenArmAutomationScheduleAdvancedWeekDays(v)); err != nil { + return fmt.Errorf("Error setting `week_days`: %+v", err) + } + if err := d.Set("month_days", flattenArmAutomationScheduleAdvancedMonthDays(v)); err != nil { + return fmt.Errorf("Error setting `month_days`: %+v", err) + } + if err := d.Set("monthly_occurrence", flattenArmAutomationScheduleAdvancedMonthlyOccurrences(v)); err != nil { + return fmt.Errorf("Error setting `monthly_occurrence`: %+v", err) + } + } return nil } @@ -282,3 +378,81 @@ func resourceArmAutomationScheduleDelete(d *schema.ResourceData, meta interface{ return nil } + +func expandArmAutomationScheduleAdvanced(d *schema.ResourceData, isUpdate bool) (*automation.AdvancedSchedule, error) { + + expandedAdvancedSchedule := automation.AdvancedSchedule{} + + // If frequency is set to `Month` the `week_days` array cannot be set (even empty), otherwise the API returns an error. + // During update it can be set and it will not return an error. Workaround for the APIs behavior + if v, ok := d.GetOk("week_days"); ok { + weekDays := v.(*schema.Set).List() + expandedWeekDays := make([]string, len(weekDays)) + for i := range weekDays { + expandedWeekDays[i] = weekDays[i].(string) + } + expandedAdvancedSchedule.WeekDays = &expandedWeekDays + } else if isUpdate { + expandedAdvancedSchedule.WeekDays = &[]string{} + } + + // Same as above with `week_days` + if v, ok := d.GetOk("month_days"); ok { + monthDays := v.(*schema.Set).List() + expandedMonthDays := make([]int32, len(monthDays)) + for i := range monthDays { + expandedMonthDays[i] = int32(monthDays[i].(int)) + } + expandedAdvancedSchedule.MonthDays = &expandedMonthDays + } else if isUpdate { + expandedAdvancedSchedule.MonthDays = &[]int32{} + } + + monthlyOccurrences := d.Get("monthly_occurrence").([]interface{}) + expandedMonthlyOccurrences := make([]automation.AdvancedScheduleMonthlyOccurrence, len(monthlyOccurrences)) + for i := range monthlyOccurrences { + m := monthlyOccurrences[i].(map[string]interface{}) + occurrence := int32(m["occurrence"].(int)) + + expandedMonthlyOccurrences[i] = automation.AdvancedScheduleMonthlyOccurrence{ + Occurrence: &occurrence, + Day: automation.ScheduleDay(m["day"].(string)), + } + } + expandedAdvancedSchedule.MonthlyOccurrences = &expandedMonthlyOccurrences + + return &expandedAdvancedSchedule, nil +} + +func flattenArmAutomationScheduleAdvancedWeekDays(s *automation.AdvancedSchedule) *schema.Set { + flattenedWeekDays := schema.NewSet(set.HashStringIgnoreCase, []interface{}{}) + if weekDays := s.WeekDays; weekDays != nil { + for _, v := range *weekDays { + flattenedWeekDays.Add(v) + } + } + return flattenedWeekDays +} + +func flattenArmAutomationScheduleAdvancedMonthDays(s *automation.AdvancedSchedule) *schema.Set { + flattenedMonthDays := schema.NewSet(set.HashInt, []interface{}{}) + if monthDays := s.MonthDays; monthDays != nil { + for _, v := range *monthDays { + flattenedMonthDays.Add(int(v)) + } + } + return flattenedMonthDays +} + +func flattenArmAutomationScheduleAdvancedMonthlyOccurrences(s *automation.AdvancedSchedule) []map[string]interface{} { + flattenedMonthlyOccurrences := make([]map[string]interface{}, 0) + if monthlyOccurrences := s.MonthlyOccurrences; monthlyOccurrences != nil { + for _, v := range *monthlyOccurrences { + f := make(map[string]interface{}) + f["day"] = v.Day + f["occurrence"] = int(*v.Occurrence) + flattenedMonthlyOccurrences = append(flattenedMonthlyOccurrences, f) + } + } + return flattenedMonthlyOccurrences +} diff --git a/azurerm/resource_arm_automation_schedule_test.go b/azurerm/resource_arm_automation_schedule_test.go index 74479f97d8e19..06a6173c343a0 100644 --- a/azurerm/resource_arm_automation_schedule_test.go +++ b/azurerm/resource_arm_automation_schedule_test.go @@ -2,13 +2,14 @@ package azurerm import ( "fmt" + "strconv" + "testing" + "time" + "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" - "strconv" - "testing" - "time" ) func TestAccAzureRMAutomationSchedule_oneTime_basic(t *testing.T) { @@ -174,6 +175,72 @@ func TestAccAzureRMAutomationSchedule_monthly(t *testing.T) { }) } +func TestAccAzureRMAutomationSchedule_weekly_advanced(t *testing.T) { + resourceName := "azurerm_automation_schedule.test" + ri := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMAutomationScheduleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMAutomationSchedule_recurring_advanced_week(ri, testLocation(), "Monday"), + Check: checkAccAzureRMAutomationSchedule_recurring_advanced_week(resourceName, "Monday"), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMAutomationSchedule_monthly_advanced_by_day(t *testing.T) { + resourceName := "azurerm_automation_schedule.test" + ri := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMAutomationScheduleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMAutomationSchedule_recurring_advanced_month(ri, testLocation(), 2), + Check: checkAccAzureRMAutomationSchedule_recurring_advanced_month(resourceName, 2), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMAutomationSchedule_monthly_advanced_by_week_day(t *testing.T) { + resourceName := "azurerm_automation_schedule.test" + ri := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMAutomationScheduleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMAutomationSchedule_recurring_advanced_month_week_day(ri, testLocation(), "Monday", 2), + Check: checkAccAzureRMAutomationSchedule_recurring_advanced_month_week_day(resourceName, "Monday", 2), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func testCheckAzureRMAutomationScheduleDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*ArmClient).automationScheduleClient ctx := testAccProvider.Meta().(*ArmClient).StopContext @@ -263,7 +330,7 @@ func testAccAzureRMAutomationSchedule_oneTime_basic(rInt int, location string) s %s resource "azurerm_automation_schedule" "test" { - name = "acctestAS-%d" + name = "acctestAS-%d" resource_group_name = "${azurerm_resource_group.test.name}" automation_account_name = "${azurerm_automation_account.test.name}" frequency = "OneTime" @@ -288,7 +355,7 @@ func testAccAzureRMAutomationSchedule_oneTime_complete(rInt int, location, start %s resource "azurerm_automation_schedule" "test" { - name = "acctestAS-%d" + name = "acctestAS-%d" resource_group_name = "${azurerm_resource_group.test.name}" automation_account_name = "${azurerm_automation_account.test.name}" frequency = "OneTime" @@ -317,7 +384,7 @@ func testAccAzureRMAutomationSchedule_recurring_basic(rInt int, location, freque %s resource "azurerm_automation_schedule" "test" { - name = "acctestAS-%d" + name = "acctestAS-%d" resource_group_name = "${azurerm_resource_group.test.name}" automation_account_name = "${azurerm_automation_account.test.name}" frequency = "%s" @@ -338,3 +405,97 @@ func checkAccAzureRMAutomationSchedule_recurring_basic(resourceName string, freq resource.TestCheckResourceAttr(resourceName, "timezone", "UTC"), ) } + +func testAccAzureRMAutomationSchedule_recurring_advanced_week(rInt int, location string, weekDay string) string { + return fmt.Sprintf(` +%s + +resource "azurerm_automation_schedule" "test" { + name = "acctestAS-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + automation_account_name = "${azurerm_automation_account.test.name}" + frequency = "Week" + interval = "1" + week_days = ["%s"] +} +`, testAccAzureRMAutomationSchedule_prerequisites(rInt, location), rInt, weekDay) +} + +func checkAccAzureRMAutomationSchedule_recurring_advanced_week(resourceName string, weekDay string) resource.TestCheckFunc { + return resource.ComposeAggregateTestCheckFunc( + testCheckAzureRMAutomationScheduleExists("azurerm_automation_schedule.test"), + resource.TestCheckResourceAttrSet(resourceName, "name"), + resource.TestCheckResourceAttrSet(resourceName, "resource_group_name"), + resource.TestCheckResourceAttrSet(resourceName, "automation_account_name"), + resource.TestCheckResourceAttrSet(resourceName, "start_time"), + resource.TestCheckResourceAttr(resourceName, "frequency", "Week"), + resource.TestCheckResourceAttr(resourceName, "interval", "1"), + resource.TestCheckResourceAttr(resourceName, "timezone", "UTC"), + resource.TestCheckResourceAttr(resourceName, "week_days.#", "1"), + ) +} + +func testAccAzureRMAutomationSchedule_recurring_advanced_month(rInt int, location string, monthDay int) string { + return fmt.Sprintf(` +%s + +resource "azurerm_automation_schedule" "test" { + name = "acctestAS-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + automation_account_name = "${azurerm_automation_account.test.name}" + frequency = "Month" + interval = "1" + month_days = [%d] +} +`, testAccAzureRMAutomationSchedule_prerequisites(rInt, location), rInt, monthDay) +} + +func checkAccAzureRMAutomationSchedule_recurring_advanced_month(resourceName string, monthDay int) resource.TestCheckFunc { + return resource.ComposeAggregateTestCheckFunc( + testCheckAzureRMAutomationScheduleExists("azurerm_automation_schedule.test"), + resource.TestCheckResourceAttrSet(resourceName, "name"), + resource.TestCheckResourceAttrSet(resourceName, "resource_group_name"), + resource.TestCheckResourceAttrSet(resourceName, "automation_account_name"), + resource.TestCheckResourceAttrSet(resourceName, "start_time"), + resource.TestCheckResourceAttr(resourceName, "frequency", "Month"), + resource.TestCheckResourceAttr(resourceName, "interval", "1"), + resource.TestCheckResourceAttr(resourceName, "timezone", "UTC"), + resource.TestCheckResourceAttr(resourceName, "month_days.#", "1"), + ) +} + +func testAccAzureRMAutomationSchedule_recurring_advanced_month_week_day(rInt int, location string, weekDay string, weekDayOccurrence int) string { + + return fmt.Sprintf(` +%s + +resource "azurerm_automation_schedule" "test" { + name = "acctestAS-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + automation_account_name = "${azurerm_automation_account.test.name}" + frequency = "Month" + interval = "1" + + monthly_occurrence { + day = "%s" + occurrence = "%d" + } +} +`, testAccAzureRMAutomationSchedule_prerequisites(rInt, location), rInt, weekDay, weekDayOccurrence) +} + +func checkAccAzureRMAutomationSchedule_recurring_advanced_month_week_day(resourceName string, monthWeekDay string, monthWeekOccurrence int) resource.TestCheckFunc { + return resource.ComposeAggregateTestCheckFunc( + testCheckAzureRMAutomationScheduleExists("azurerm_automation_schedule.test"), + resource.TestCheckResourceAttrSet(resourceName, "name"), + resource.TestCheckResourceAttrSet(resourceName, "resource_group_name"), + resource.TestCheckResourceAttrSet(resourceName, "automation_account_name"), + resource.TestCheckResourceAttrSet(resourceName, "start_time"), + resource.TestCheckResourceAttr(resourceName, "frequency", "Month"), + resource.TestCheckResourceAttr(resourceName, "interval", "1"), + resource.TestCheckResourceAttr(resourceName, "timezone", "UTC"), + resource.TestCheckResourceAttr(resourceName, "monthly_occurrence.#", "1"), + resource.TestCheckResourceAttr(resourceName, "monthly_occurrence.0.day", monthWeekDay), + resource.TestCheckResourceAttr(resourceName, "monthly_occurrence.0.occurrence", strconv.Itoa(monthWeekOccurrence)), + ) +} diff --git a/azurerm/resource_arm_autoscale_setting.go b/azurerm/resource_arm_autoscale_setting.go index af32ffd781f76..36efaa0f20f75 100644 --- a/azurerm/resource_arm_autoscale_setting.go +++ b/azurerm/resource_arm_autoscale_setting.go @@ -432,7 +432,9 @@ func resourceArmAutoScaleSettingRead(d *schema.ResourceData, meta interface{}) e return fmt.Errorf("Error setting `notification` of Autoscale Setting %q (resource group %q): %+v", name, resourceGroup, err) } - flattenAndSetTags(d, resp.Tags) + // Return a new tag map filtered by the specified tag names. + tagMap := filterTags(resp.Tags, "$type") + flattenAndSetTags(d, tagMap) return nil } @@ -714,7 +716,7 @@ func flattenAzureRmAutoScaleSettingCapacity(input *insights.ScaleCapacity) ([]in if minStr := input.Minimum; minStr != nil { min, err := strconv.Atoi(*minStr) if err != nil { - return nil, fmt.Errorf("Error converting Minimum Scale Capacity %q to an int: %+v", minStr, err) + return nil, fmt.Errorf("Error converting Minimum Scale Capacity %q to an int: %+v", *minStr, err) } result["minimum"] = min } @@ -722,7 +724,7 @@ func flattenAzureRmAutoScaleSettingCapacity(input *insights.ScaleCapacity) ([]in if maxStr := input.Maximum; maxStr != nil { max, err := strconv.Atoi(*maxStr) if err != nil { - return nil, fmt.Errorf("Error converting Maximum Scale Capacity %q to an int: %+v", maxStr, err) + return nil, fmt.Errorf("Error converting Maximum Scale Capacity %q to an int: %+v", *maxStr, err) } result["maximum"] = max } @@ -730,7 +732,7 @@ func flattenAzureRmAutoScaleSettingCapacity(input *insights.ScaleCapacity) ([]in if defaultCapacityStr := input.Default; defaultCapacityStr != nil { defaultCapacity, err := strconv.Atoi(*defaultCapacityStr) if err != nil { - return nil, fmt.Errorf("Error converting Default Scale Capacity %q to an int: %+v", defaultCapacityStr, err) + return nil, fmt.Errorf("Error converting Default Scale Capacity %q to an int: %+v", *defaultCapacityStr, err) } result["default"] = defaultCapacity } diff --git a/azurerm/resource_arm_autoscale_setting_test.go b/azurerm/resource_arm_autoscale_setting_test.go index 79a7966c0956e..352d28cc141dd 100644 --- a/azurerm/resource_arm_autoscale_setting_test.go +++ b/azurerm/resource_arm_autoscale_setting_test.go @@ -31,6 +31,7 @@ func TestAccAzureRMAutoScaleSetting_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "profile.0.name", "metricRules"), resource.TestCheckResourceAttr(resourceName, "profile.0.rule.#", "1"), resource.TestCheckResourceAttr(resourceName, "notification.#", "0"), + resource.TestCheckNoResourceAttr(resourceName, "tags.$type"), ), }, }, diff --git a/azurerm/resource_arm_container_group.go b/azurerm/resource_arm_container_group.go index 635b525ddea38..15e14b2cc5b20 100644 --- a/azurerm/resource_arm_container_group.go +++ b/azurerm/resource_arm_container_group.go @@ -2,6 +2,7 @@ package azurerm import ( "fmt" + "log" "strings" "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-04-01/containerinstance" @@ -169,9 +170,19 @@ func resourceArmContainerGroup() *schema.Resource { }, "command": { - Type: schema.TypeString, + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Computed: true, + Deprecated: "Use `commands` instead.", + }, + + "commands": { + Type: schema.TypeList, Optional: true, ForceNew: true, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, "volume": { @@ -227,11 +238,9 @@ func resourceArmContainerGroup() *schema.Resource { } func resourceArmContainerGroupCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) ctx := meta.(*ArmClient).StopContext - containerGroupsClient := client.containerGroupsClient + containerGroupsClient := meta.(*ArmClient).containerGroupsClient - // container group properties resGroup := d.Get("resource_group_name").(string) name := d.Get("name").(string) location := azureRMNormalizeLocation(d.Get("location").(string)) @@ -282,23 +291,22 @@ func resourceArmContainerGroupCreate(d *schema.ResourceData, meta interface{}) e } func resourceArmContainerGroupRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) ctx := meta.(*ArmClient).StopContext - containterGroupsClient := client.containerGroupsClient + client := meta.(*ArmClient).containerGroupsClient id, err := parseAzureResourceID(d.Id()) - if err != nil { return err } - resGroup := id.ResourceGroup + resourceGroup := id.ResourceGroup name := id.Path["containerGroups"] - resp, err := containterGroupsClient.Get(ctx, resGroup, name) + resp, err := client.Get(ctx, resourceGroup, name) if err != nil { if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[DEBUG] Container Group %q was not found in Resource Group %q - removing from state!", name, resourceGroup) d.SetId("") return nil } @@ -306,57 +314,53 @@ func resourceArmContainerGroupRead(d *schema.ResourceData, meta interface{}) err } d.Set("name", name) - d.Set("resource_group_name", resGroup) + d.Set("resource_group_name", resourceGroup) if location := resp.Location; location != nil { d.Set("location", azureRMNormalizeLocation(*location)) } - flattenAndSetTags(d, resp.Tags) - - if err := d.Set("image_registry_credential", flattenContainerImageRegistryCredentials(d, resp.ImageRegistryCredentials)); err != nil { - return fmt.Errorf("Error setting `capabilities`: %+v", err) - } - - d.Set("os_type", string(resp.OsType)) - if address := resp.IPAddress; address != nil { - d.Set("ip_address_type", address.Type) - d.Set("ip_address", address.IP) - d.Set("dns_name_label", address.DNSNameLabel) - d.Set("fqdn", address.Fqdn) - } - d.Set("restart_policy", string(resp.RestartPolicy)) if props := resp.ContainerGroupProperties; props != nil { containerConfigs := flattenContainerGroupContainers(d, resp.Containers, props.IPAddress.Ports, props.Volumes) - err = d.Set("container", containerConfigs) - if err != nil { + if err := d.Set("container", containerConfigs); err != nil { return fmt.Errorf("Error setting `container`: %+v", err) } + + if err := d.Set("image_registry_credential", flattenContainerImageRegistryCredentials(d, props.ImageRegistryCredentials)); err != nil { + return fmt.Errorf("Error setting `capabilities`: %+v", err) + } + + if address := props.IPAddress; address != nil { + d.Set("ip_address_type", address.Type) + d.Set("ip_address", address.IP) + d.Set("dns_name_label", address.DNSNameLabel) + d.Set("fqdn", address.Fqdn) + } + + d.Set("restart_policy", string(props.RestartPolicy)) + d.Set("os_type", string(props.OsType)) } + flattenAndSetTags(d, resp.Tags) return nil } func resourceArmContainerGroupDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) ctx := meta.(*ArmClient).StopContext - containterGroupsClient := client.containerGroupsClient + client := meta.(*ArmClient).containerGroupsClient id, err := parseAzureResourceID(d.Id()) - if err != nil { return err } - // container group properties - resGroup := id.ResourceGroup + resourceGroup := id.ResourceGroup name := id.Path["containerGroups"] - resp, err := containterGroupsClient.Delete(ctx, resGroup, name) + resp, err := client.Delete(ctx, resourceGroup, name) if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - return nil + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Error deleting Container Group %q (Resource Group %q): %+v", name, resourceGroup, err) } - return err } return nil @@ -400,9 +404,15 @@ func flattenContainerGroupContainers(d *schema.ResourceData, containers *[]conta } } + commands := make([]string, 0) if command := container.Command; command != nil { containerConfig["command"] = strings.Join(*command, " ") + + for _, v := range *command { + commands = append(commands, v) + } } + containerConfig["commands"] = commands if containerGroupVolumes != nil && container.VolumeMounts != nil { // Also pass in the container volume config from schema @@ -431,12 +441,14 @@ func flattenContainerGroupContainers(d *schema.ResourceData, containers *[]conta func flattenContainerEnvironmentVariables(input *[]containerinstance.EnvironmentVariable) map[string]interface{} { output := make(map[string]interface{}) + if input == nil { + return output + } for _, envVar := range *input { - k := *envVar.Name - v := *envVar.Value - - output[k] = v + if envVar.Name != nil && envVar.Value != nil { + output[*envVar.Name] = *envVar.Value + } } return output @@ -445,22 +457,40 @@ func flattenContainerEnvironmentVariables(input *[]containerinstance.Environment func flattenContainerVolumes(volumeMounts *[]containerinstance.VolumeMount, containerGroupVolumes *[]containerinstance.Volume, containerVolumesConfig *[]interface{}) []interface{} { volumeConfigs := make([]interface{}, 0) + if volumeMounts == nil { + return volumeConfigs + } + for _, vm := range *volumeMounts { volumeConfig := make(map[string]interface{}) - volumeConfig["name"] = *vm.Name - volumeConfig["mount_path"] = *vm.MountPath + if vm.Name != nil { + volumeConfig["name"] = *vm.Name + } + if vm.MountPath != nil { + volumeConfig["mount_path"] = *vm.MountPath + } if vm.ReadOnly != nil { volumeConfig["read_only"] = *vm.ReadOnly } // find corresponding volume in container group volumes // and use the data - for _, cgv := range *containerGroupVolumes { - if *cgv.Name == *vm.Name { - if cgv.AzureFile != nil { - volumeConfig["share_name"] = *(*cgv.AzureFile).ShareName - volumeConfig["storage_account_name"] = *(*cgv.AzureFile).StorageAccountName - // skip storage_account_key, is always nil + if containerGroupVolumes != nil { + for _, cgv := range *containerGroupVolumes { + if cgv.Name == nil || vm.Name == nil { + continue + } + + 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 + } + // skip storage_account_key, is always nil + } } } } @@ -471,7 +501,7 @@ func flattenContainerVolumes(volumeMounts *[]containerinstance.VolumeMount, cont for _, cvr := range *containerVolumesConfig { cv := cvr.(map[string]interface{}) rawName := cv["name"].(string) - if *vm.Name == rawName { + if vm.Name != nil && *vm.Name == rawName { storageAccountKey := cv["storage_account_key"].(string) volumeConfig["storage_account_key"] = storageAccountKey } @@ -486,27 +516,26 @@ func flattenContainerVolumes(volumeMounts *[]containerinstance.VolumeMount, cont func expandContainerGroupContainers(d *schema.ResourceData) (*[]containerinstance.Container, *[]containerinstance.Port, *[]containerinstance.Volume) { containersConfig := d.Get("container").([]interface{}) - containers := make([]containerinstance.Container, 0, len(containersConfig)) - containerGroupPorts := make([]containerinstance.Port, 0, len(containersConfig)) + containers := make([]containerinstance.Container, 0) + containerGroupPorts := make([]containerinstance.Port, 0) containerGroupVolumes := make([]containerinstance.Volume, 0) for _, containerConfig := range containersConfig { data := containerConfig.(map[string]interface{}) - // required name := data["name"].(string) image := data["image"].(string) cpu := data["cpu"].(float64) memory := data["memory"].(float64) container := containerinstance.Container{ - Name: &name, + Name: utils.String(name), ContainerProperties: &containerinstance.ContainerProperties{ - Image: &image, + Image: utils.String(image), Resources: &containerinstance.ResourceRequirements{ Requests: &containerinstance.ResourceRequests{ - MemoryInGB: &memory, - CPU: &cpu, + MemoryInGB: utils.Float(memory), + CPU: utils.Float(cpu), }, }, }, @@ -516,10 +545,11 @@ func expandContainerGroupContainers(d *schema.ResourceData) (*[]containerinstanc port := int32(v.(int)) // container port (port number) - containerPort := containerinstance.ContainerPort{ - Port: &port, + container.Ports = &[]containerinstance.ContainerPort{ + { + Port: &port, + }, } - container.Ports = &[]containerinstance.ContainerPort{containerPort} // container group port (port number + protocol) containerGroupPort := containerinstance.Port{ @@ -538,11 +568,23 @@ func expandContainerGroupContainers(d *schema.ResourceData) (*[]containerinstanc container.EnvironmentVariables = expandContainerEnvironmentVariables(v) } - if v, _ := data["command"]; v != "" { - command := strings.Split(v.(string), " ") + if v, ok := data["commands"]; ok { + c := v.([]interface{}) + command := make([]string, 0) + for _, v := range c { + command = append(command, v.(string)) + } + container.Command = &command } + if container.Command == nil { + if v, _ := data["command"]; v != "" { + command := strings.Split(v.(string), " ") + container.Command = &command + } + } + if v, ok := data["volume"]; ok { volumeMounts, containerGroupVolumesPartial := expandContainerVolumes(v) container.VolumeMounts = volumeMounts @@ -559,7 +601,7 @@ func expandContainerGroupContainers(d *schema.ResourceData) (*[]containerinstanc func expandContainerEnvironmentVariables(input interface{}) *[]containerinstance.EnvironmentVariable { envVars := input.(map[string]interface{}) - output := make([]containerinstance.EnvironmentVariable, 0, len(envVars)) + output := make([]containerinstance.EnvironmentVariable, 0) for k, v := range envVars { ev := containerinstance.EnvironmentVariable{ @@ -593,15 +635,14 @@ func expandContainerImageRegistryCredentials(d *schema.ResourceData) *[]containe return &output } -func flattenContainerImageRegistryCredentials(d *schema.ResourceData, credsPtr *[]containerinstance.ImageRegistryCredential) []interface{} { - if credsPtr == nil { +func flattenContainerImageRegistryCredentials(d *schema.ResourceData, input *[]containerinstance.ImageRegistryCredential) []interface{} { + if input == nil { return nil } configsOld := d.Get("image_registry_credential").([]interface{}) - creds := *credsPtr - output := make([]interface{}, 0, len(creds)) - for i, cred := range creds { + output := make([]interface{}, 0) + for i, cred := range *input { credConfig := make(map[string]interface{}) if cred.Server != nil { credConfig["server"] = *cred.Server @@ -632,8 +673,8 @@ func expandContainerVolumes(input interface{}) (*[]containerinstance.VolumeMount return nil, nil } - volumeMounts := make([]containerinstance.VolumeMount, 0, len(volumesRaw)) - containerGroupVolumes := make([]containerinstance.Volume, 0, len(volumesRaw)) + volumeMounts := make([]containerinstance.VolumeMount, 0) + containerGroupVolumes := make([]containerinstance.Volume, 0) for _, volumeRaw := range volumesRaw { volumeConfig := volumeRaw.(map[string]interface{}) @@ -646,20 +687,20 @@ func expandContainerVolumes(input interface{}) (*[]containerinstance.VolumeMount storageAccountKey := volumeConfig["storage_account_key"].(string) vm := containerinstance.VolumeMount{ - Name: &name, - MountPath: &mountPath, - ReadOnly: &readOnly, + Name: utils.String(name), + MountPath: utils.String(mountPath), + ReadOnly: utils.Bool(readOnly), } volumeMounts = append(volumeMounts, vm) cv := containerinstance.Volume{ - Name: &name, + Name: utils.String(name), AzureFile: &containerinstance.AzureFileVolume{ - ShareName: &shareName, - ReadOnly: &readOnly, - StorageAccountName: &storageAccountName, - StorageAccountKey: &storageAccountKey, + ShareName: utils.String(shareName), + ReadOnly: utils.Bool(readOnly), + StorageAccountName: utils.String(storageAccountName), + StorageAccountKey: utils.String(storageAccountKey), }, } diff --git a/azurerm/resource_arm_container_group_test.go b/azurerm/resource_arm_container_group_test.go index 1d20e975dcf19..4889930c97d8e 100644 --- a/azurerm/resource_arm_container_group_test.go +++ b/azurerm/resource_arm_container_group_test.go @@ -166,6 +166,10 @@ func TestAccAzureRMContainerGroup_linuxComplete(t *testing.T) { testCheckAzureRMContainerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "container.#", "1"), resource.TestCheckResourceAttr(resourceName, "container.0.command", "/bin/bash -c ls"), + resource.TestCheckResourceAttr(resourceName, "container.0.commands.#", "3"), + resource.TestCheckResourceAttr(resourceName, "container.0.commands.0", "/bin/bash"), + resource.TestCheckResourceAttr(resourceName, "container.0.commands.1", "-c"), + resource.TestCheckResourceAttr(resourceName, "container.0.commands.2", "ls"), resource.TestCheckResourceAttr(resourceName, "container.0.environment_variables.%", "2"), resource.TestCheckResourceAttr(resourceName, "container.0.environment_variables.foo", "bar"), resource.TestCheckResourceAttr(resourceName, "container.0.environment_variables.foo1", "bar1"), @@ -234,6 +238,10 @@ func TestAccAzureRMContainerGroup_windowsComplete(t *testing.T) { testCheckAzureRMContainerGroupExists(resourceName), resource.TestCheckResourceAttr(resourceName, "container.#", "1"), resource.TestCheckResourceAttr(resourceName, "container.0.command", "cmd.exe echo hi"), + resource.TestCheckResourceAttr(resourceName, "container.0.commands.#", "3"), + resource.TestCheckResourceAttr(resourceName, "container.0.commands.0", "cmd.exe"), + resource.TestCheckResourceAttr(resourceName, "container.0.commands.1", "echo"), + resource.TestCheckResourceAttr(resourceName, "container.0.commands.2", "hi"), resource.TestCheckResourceAttr(resourceName, "container.0.environment_variables.%", "2"), resource.TestCheckResourceAttr(resourceName, "container.0.environment_variables.foo", "bar"), resource.TestCheckResourceAttr(resourceName, "container.0.environment_variables.foo1", "bar1"), @@ -461,7 +469,7 @@ resource "azurerm_container_group" "test" { "foo" = "bar" "foo1" = "bar1" } - command = "cmd.exe echo hi" + commands = ["cmd.exe", "echo", "hi"] } tags { @@ -528,7 +536,7 @@ resource "azurerm_container_group" "test" { "foo1" = "bar1" } - command = "/bin/bash -c ls" + commands = ["/bin/bash", "-c", "ls"] } tags { diff --git a/azurerm/resource_arm_cosmos_db_account.go b/azurerm/resource_arm_cosmos_db_account.go index 97e4ccc06b8be..eef0d05078552 100644 --- a/azurerm/resource_arm_cosmos_db_account.go +++ b/azurerm/resource_arm_cosmos_db_account.go @@ -12,9 +12,9 @@ import ( "github.com/hashicorp/terraform/helper/hashcode" "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" + "github.com/hashicorp/terraform/helper/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) diff --git a/azurerm/resource_arm_iothub.go b/azurerm/resource_arm_iothub.go old mode 100644 new mode 100755 index aa3bc77af5943..6dc390482a949 --- a/azurerm/resource_arm_iothub.go +++ b/azurerm/resource_arm_iothub.go @@ -7,12 +7,14 @@ import ( "strconv" "time" - "github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices" + "github.com/Azure/azure-sdk-for-go/services/eventhub/mgmt/2017-04-01/eventhub" + "github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" + "strings" ) func resourceArmIotHub() *schema.Resource { @@ -47,6 +49,9 @@ func resourceArmIotHub() *schema.Resource { Required: true, DiffSuppressFunc: ignoreCaseDiffSuppressFunc, ValidateFunc: validation.StringInSlice([]string{ + string(devices.B1), + string(devices.B2), + string(devices.B3), string(devices.F1), string(devices.S1), string(devices.S2), @@ -59,6 +64,7 @@ func resourceArmIotHub() *schema.Resource { Required: true, DiffSuppressFunc: ignoreCaseDiffSuppressFunc, ValidateFunc: validation.StringInSlice([]string{ + string(devices.Basic), string(devices.Free), string(devices.Standard), }, true), @@ -83,6 +89,24 @@ func resourceArmIotHub() *schema.Resource { Computed: true, }, + "event_hub_events_endpoint": { + Type: schema.TypeString, + Computed: true, + }, + "event_hub_operations_endpoint": { + Type: schema.TypeString, + Computed: true, + }, + + "event_hub_events_path": { + Type: schema.TypeString, + Computed: true, + }, + "event_hub_operations_path": { + Type: schema.TypeString, + Computed: true, + }, + "shared_access_policy": { Type: schema.TypeList, Computed: true, @@ -110,6 +134,115 @@ func resourceArmIotHub() *schema.Resource { }, }, + "endpoint": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + "AzureIotHub.StorageContainer", + "AzureIotHub.ServiceBusQueue", + "AzureIotHub.ServiceBusTopic", + "AzureIotHub.EventHub", + }, false), + }, + "connection_string": { + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { + // As Azure API masks the connection string key suppress diff for this property + if old != "" && strings.HasSuffix(old, "****") { + return true + } + + return false + }, + }, + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateIoTHubEndpointName, + }, + "batch_frequency_in_seconds": { + Type: schema.TypeInt, + Optional: true, + Default: 300, + ValidateFunc: validation.IntBetween(60, 720), + }, + "max_chunk_size_in_bytes": { + Type: schema.TypeInt, + Optional: true, + Default: 314572800, + ValidateFunc: validation.IntBetween(10485760, 524288000), + }, + "container_name": { + Type: schema.TypeString, + Optional: true, + }, + "encoding": { + Type: schema.TypeString, + Optional: true, + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + ValidateFunc: validation.StringInSlice([]string{ + string(eventhub.Avro), + string(eventhub.AvroDeflate), + }, true), + }, + "file_name_format": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validateIoTHubFileNameFormat, + }, + }, + }, + }, + + "route": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(0, 64), + }, + "source": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + "DeviceJobLifecycleEvents", + "DeviceLifecycleEvents", + "DeviceMessages", + "Invalid", + "TwinChangeEvents", + }, false), + }, + "condition": { + // The condition is a string value representing device-to-cloud message routes query expression + // https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-query-language#device-to-cloud-message-routes-query-expressions + Type: schema.TypeString, + Optional: true, + Default: "true", + }, + "endpoint_names": { + Type: schema.TypeList, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Required: true, + }, + "enabled": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + }, + "tags": tagsSchema(), }, } @@ -142,13 +275,28 @@ func resourceArmIotHubCreateAndUpdate(d *schema.ResourceData, meta interface{}) skuInfo := expandIoTHubSku(d) tags := d.Get("tags").(map[string]interface{}) + endpoints, err := expandIoTHubEndpoints(d, subscriptionID) + if err != nil { + return fmt.Errorf("Error expanding `endpoint`: %+v", err) + } + + routes := expandIoTHubRoutes(d) + + routingProperties := devices.RoutingProperties{ + Endpoints: endpoints, + Routes: routes, + } + + iotHubProperties := devices.IotHubProperties{ + Routing: &routingProperties, + } + properties := devices.IotHubDescription{ - Name: utils.String(name), - Location: utils.String(location), - Resourcegroup: utils.String(resourceGroup), - Subscriptionid: utils.String(subscriptionID), - Sku: &skuInfo, - Tags: expandTags(tags), + Name: utils.String(name), + Location: utils.String(location), + Sku: &skuInfo, + Tags: expandTags(tags), + Properties: &iotHubProperties, } future, err := client.CreateOrUpdate(ctx, resourceGroup, name, properties, "") @@ -205,7 +353,40 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { } if properties := hub.Properties; properties != nil { + + for k, v := range properties.EventHubEndpoints { + if v == nil { + continue + } + if k == "events" { + if v.Endpoint != nil { + d.Set("event_hub_events_endpoint", *v.Endpoint) + } + if v.Path != nil { + d.Set("event_hub_events_path", *v.Path) + } + } else if k == "operationsMonitoringEvents" { + if v.Endpoint != nil { + d.Set("event_hub_operations_endpoint", *v.Endpoint) + } + if v.Path != nil { + d.Set("event_hub_operations_path", *v.Path) + } + } + + } + d.Set("hostname", properties.HostName) + + endpoints := flattenIoTHubEndpoint(properties.Routing) + if err := d.Set("endpoint", endpoints); err != nil { + return fmt.Errorf("Error flattening `endpoint` in IoTHub %q: %+v", name, err) + } + + routes := flattenIoTHubRoute(properties.Routing) + if err := d.Set("route", routes); err != nil { + return fmt.Errorf("Error flattening `route` in IoTHub %q: %+v", name, err) + } } d.Set("name", name) @@ -279,10 +460,118 @@ func iothubStateStatusCodeRefreshFunc(ctx context.Context, client devices.IotHub } } +func expandIoTHubRoutes(d *schema.ResourceData) *[]devices.RouteProperties { + routeList := d.Get("route").([]interface{}) + + routeProperties := make([]devices.RouteProperties, 0) + + for _, routeRaw := range routeList { + route := routeRaw.(map[string]interface{}) + + name := route["name"].(string) + source := devices.RoutingSource(route["source"].(string)) + condition := route["condition"].(string) + + endpointNamesRaw := route["endpoint_names"].([]interface{}) + endpointsNames := make([]string, 0) + for _, n := range endpointNamesRaw { + endpointsNames = append(endpointsNames, n.(string)) + } + + isEnabled := route["enabled"].(bool) + + routeProperties = append(routeProperties, devices.RouteProperties{ + Name: &name, + Source: source, + Condition: &condition, + EndpointNames: &endpointsNames, + IsEnabled: &isEnabled, + }) + } + + return &routeProperties +} + +func expandIoTHubEndpoints(d *schema.ResourceData, subscriptionId string) (*devices.RoutingEndpoints, error) { + routeEndpointList := d.Get("endpoint").([]interface{}) + + serviceBusQueueEndpointProperties := make([]devices.RoutingServiceBusQueueEndpointProperties, 0) + serviceBusTopicEndpointProperties := make([]devices.RoutingServiceBusTopicEndpointProperties, 0) + eventHubProperties := make([]devices.RoutingEventHubProperties, 0) + storageContainerProperties := make([]devices.RoutingStorageContainerProperties, 0) + + for _, endpointRaw := range routeEndpointList { + endpoint := endpointRaw.(map[string]interface{}) + + t := endpoint["type"] + connectionStr := endpoint["connection_string"].(string) + name := endpoint["name"].(string) + subscriptionID := subscriptionId + resourceGroup := d.Get("resource_group_name").(string) + + switch t { + case "AzureIotHub.StorageContainer": + containerName := endpoint["container_name"].(string) + fileNameFormat := endpoint["file_name_format"].(string) + batchFrequencyInSeconds := int32(endpoint["batch_frequency_in_seconds"].(int)) + maxChunkSizeInBytes := int32(endpoint["max_chunk_size_in_bytes"].(int)) + encoding := endpoint["encoding"].(string) + + storageContainer := devices.RoutingStorageContainerProperties{ + ConnectionString: &connectionStr, + Name: &name, + SubscriptionID: &subscriptionID, + ResourceGroup: &resourceGroup, + ContainerName: &containerName, + FileNameFormat: &fileNameFormat, + BatchFrequencyInSeconds: &batchFrequencyInSeconds, + MaxChunkSizeInBytes: &maxChunkSizeInBytes, + Encoding: &encoding, + } + storageContainerProperties = append(storageContainerProperties, storageContainer) + break + case "AzureIotHub.ServiceBusQueue": + sbQueue := devices.RoutingServiceBusQueueEndpointProperties{ + ConnectionString: &connectionStr, + Name: &name, + SubscriptionID: &subscriptionID, + ResourceGroup: &resourceGroup, + } + serviceBusQueueEndpointProperties = append(serviceBusQueueEndpointProperties, sbQueue) + break + case "AzureIotHub.ServiceBusTopic": + sbTopic := devices.RoutingServiceBusTopicEndpointProperties{ + ConnectionString: &connectionStr, + Name: &name, + SubscriptionID: &subscriptionID, + ResourceGroup: &resourceGroup, + } + serviceBusTopicEndpointProperties = append(serviceBusTopicEndpointProperties, sbTopic) + break + case "AzureIotHub.EventHub": + eventHub := devices.RoutingEventHubProperties{ + ConnectionString: &connectionStr, + Name: &name, + SubscriptionID: &subscriptionID, + ResourceGroup: &resourceGroup, + } + eventHubProperties = append(eventHubProperties, eventHub) + break + } + } + + return &devices.RoutingEndpoints{ + ServiceBusQueues: &serviceBusQueueEndpointProperties, + ServiceBusTopics: &serviceBusTopicEndpointProperties, + EventHubs: &eventHubProperties, + StorageContainers: &storageContainerProperties, + }, nil +} + func expandIoTHubSku(d *schema.ResourceData) devices.IotHubSkuInfo { skuList := d.Get("sku").([]interface{}) skuMap := skuList[0].(map[string]interface{}) - cap := int64(skuMap["capacity"].(int)) + capacity := int64(skuMap["capacity"].(int)) name := skuMap["name"].(string) tier := skuMap["tier"].(string) @@ -290,7 +579,7 @@ func expandIoTHubSku(d *schema.ResourceData) devices.IotHubSkuInfo { return devices.IotHubSkuInfo{ Name: devices.IotHubSku(name), Tier: devices.IotHubSkuTier(tier), - Capacity: &cap, + Capacity: utils.Int64(capacity), } } @@ -332,3 +621,157 @@ func flattenIoTHubSharedAccessPolicy(input *[]devices.SharedAccessSignatureAutho return results } + +func flattenIoTHubEndpoint(input *devices.RoutingProperties) []interface{} { + results := make([]interface{}, 0) + + if input != nil && input.Endpoints != nil { + + if containers := input.Endpoints.StorageContainers; containers != nil { + for _, container := range *containers { + output := make(map[string]interface{}, 0) + + if connString := container.ConnectionString; connString != nil { + output["connection_string"] = *connString + } + if name := container.Name; name != nil { + output["name"] = *name + } + if containerName := container.ContainerName; containerName != nil { + output["container_name"] = *containerName + } + if fileNameFmt := container.FileNameFormat; fileNameFmt != nil { + output["file_name_format"] = *fileNameFmt + } + if batchFreq := container.BatchFrequencyInSeconds; batchFreq != nil { + output["batch_frequency_in_seconds"] = *batchFreq + } + if chunkSize := container.MaxChunkSizeInBytes; chunkSize != nil { + output["max_chunk_size_in_bytes"] = *chunkSize + } + if encoding := container.Encoding; encoding != nil { + output["encoding"] = *encoding + } + output["type"] = "AzureIotHub.StorageContainer" + + results = append(results, output) + } + } + + if queues := input.Endpoints.ServiceBusQueues; queues != nil { + for _, queue := range *queues { + output := make(map[string]interface{}, 0) + + if connString := queue.ConnectionString; connString != nil { + output["connection_string"] = *connString + } + if name := queue.Name; name != nil { + output["name"] = *name + } + + results = append(results, output) + } + } + + if topics := input.Endpoints.ServiceBusTopics; topics != nil { + for _, topic := range *topics { + output := make(map[string]interface{}, 0) + + if connString := topic.ConnectionString; connString != nil { + output["connection_string"] = *connString + } + if name := topic.Name; name != nil { + output["name"] = *name + } + + results = append(results, output) + } + } + + if eventHubs := input.Endpoints.EventHubs; eventHubs != nil { + for _, eventHub := range *eventHubs { + output := make(map[string]interface{}, 0) + + if connString := eventHub.ConnectionString; connString != nil { + output["connection_string"] = *connString + } + if name := eventHub.Name; name != nil { + output["name"] = *name + } + + results = append(results, output) + } + } + } + + return results +} + +func flattenIoTHubRoute(input *devices.RoutingProperties) []interface{} { + results := make([]interface{}, 0) + + if input != nil && input.Routes != nil { + for _, route := range *input.Routes { + output := make(map[string]interface{}, 0) + + if name := route.Name; name != nil { + output["name"] = *name + } + if condition := route.Condition; condition != nil { + output["condition"] = *condition + } + if endpointNames := route.EndpointNames; endpointNames != nil { + output["endpoint_names"] = *endpointNames + } + if isEnabled := route.IsEnabled; isEnabled != nil { + output["enabled"] = *isEnabled + } + output["source"] = route.Source + + results = append(results, output) + } + } + + return results +} + +func validateIoTHubEndpointName(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + + reservedNames := []string{ + "events", + "operationsMonitoringEvents", + "fileNotifications", + "$default", + } + + for _, name := range reservedNames { + if name == value { + errors = append(errors, fmt.Errorf("The reserved endpoint name %s could not be used as a name for a custom endpoint", name)) + } + } + + return +} + +func validateIoTHubFileNameFormat(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + + requiredComponents := []string{ + "{iothub}", + "{partition}", + "{YYYY}", + "{MM}", + "{DD}", + "{HH}", + "{mm}", + } + + for _, component := range requiredComponents { + if !strings.Contains(value, component) { + errors = append(errors, fmt.Errorf("%s needs to contain %q", k, component)) + } + } + + return +} diff --git a/azurerm/resource_arm_iothub_test.go b/azurerm/resource_arm_iothub_test.go index 40569d1b893fc..3116bd4494e44 100644 --- a/azurerm/resource_arm_iothub_test.go +++ b/azurerm/resource_arm_iothub_test.go @@ -10,7 +10,7 @@ import ( "github.com/hashicorp/terraform/terraform" ) -func TestAccAzureRMIotHub_basicStandard(t *testing.T) { +func TestAccAzureRMIotHub_basic(t *testing.T) { rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ @@ -19,14 +19,50 @@ func TestAccAzureRMIotHub_basicStandard(t *testing.T) { CheckDestroy: testCheckAzureRMIotHubDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMIotHub_basicStandard(rInt, testLocation()), + Config: testAccAzureRMIotHub_basic(rInt, testLocation()), Check: resource.ComposeTestCheckFunc( testCheckAzureRMIotHubExists("azurerm_iothub.test"), ), }, }, }) +} + +func TestAccAzureRMIotHub_standard(t *testing.T) { + rInt := acctest.RandInt() + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMIotHubDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMIotHub_standard(rInt, testLocation()), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMIotHubExists("azurerm_iothub.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMIotHub_customRoutes(t *testing.T) { + rInt := acctest.RandInt() + rStr := acctest.RandString(5) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMIotHubDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMIotHub_customRoutes(rInt, rStr, testLocation()), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMIotHubExists("azurerm_iothub.test"), + ), + }, + }, + }) } func testCheckAzureRMIotHubDestroy(s *terraform.State) error { @@ -83,7 +119,31 @@ func testCheckAzureRMIotHubExists(name string) resource.TestCheckFunc { } } -func testAccAzureRMIotHub_basicStandard(rInt int, location string) string { +func testAccAzureRMIotHub_basic(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "foo" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_iothub" "test" { + name = "acctestIoTHub-%d" + resource_group_name = "${azurerm_resource_group.foo.name}" + location = "${azurerm_resource_group.foo.location}" + sku { + name = "B1" + tier = "Basic" + capacity = "1" + } + + tags { + "purpose" = "testing" + } +} +`, rInt, location, rInt) +} + +func testAccAzureRMIotHub_standard(rInt int, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "foo" { name = "acctestRG-%d" @@ -106,3 +166,61 @@ resource "azurerm_iothub" "test" { } `, rInt, location, rInt) } + +func testAccAzureRMIotHub_customRoutes(rInt int, rStr string, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "foo" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_storage_account" "test" { + name = "acctestsa%s" + resource_group_name = "${azurerm_resource_group.foo.name}" + location = "${azurerm_resource_group.foo.location}" + account_tier = "Standard" + account_replication_type = "LRS" +} + +resource "azurerm_storage_container" "test" { + name = "test" + resource_group_name = "${azurerm_resource_group.foo.name}" + storage_account_name = "${azurerm_storage_account.test.name}" + container_access_type = "private" +} + +resource "azurerm_iothub" "test" { + name = "acctestIoTHub-%d" + resource_group_name = "${azurerm_resource_group.foo.name}" + location = "${azurerm_resource_group.foo.location}" + sku { + name = "S1" + tier = "Standard" + capacity = "1" + } + + endpoint { + type = "AzureIotHub.StorageContainer" + connection_string = "${azurerm_storage_account.test.primary_blob_connection_string}" + name = "export" + batch_frequency_in_seconds = 60 + max_chunk_size_in_bytes = 10485760 + container_name = "test" + encoding = "Avro" + file_name_format = "{iothub}/{partition}_{YYYY}_{MM}_{DD}_{HH}_{mm}" + } + + route { + name = "export" + source = "DeviceMessages" + condition = "true" + endpoint_names = ["export"] + enabled = true + } + + tags { + "purpose" = "testing" + } +} +`, rInt, location, rStr, rInt) +} diff --git a/azurerm/resource_arm_key_vault.go b/azurerm/resource_arm_key_vault.go index 3be569735ffff..f7179cda8d245 100644 --- a/azurerm/resource_arm_key_vault.go +++ b/azurerm/resource_arm_key_vault.go @@ -11,8 +11,8 @@ import ( "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" - uuid "github.com/satori/go.uuid" - azschema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/schema" + "github.com/satori/go.uuid" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -97,9 +97,9 @@ func resourceArmKeyVault() *schema.Resource { Optional: true, ValidateFunc: validateUUID, }, - "certificate_permissions": azschema.KeyVaultCertificatePermissionsSchema(), - "key_permissions": azschema.KeyVaultKeyPermissionsSchema(), - "secret_permissions": azschema.KeyVaultSecretPermissionsSchema(), + "certificate_permissions": azure.SchemaKeyVaultCertificatePermissions(), + "key_permissions": azure.SchemaKeyVaultKeyPermissions(), + "secret_permissions": azure.SchemaKeyVaultSecretPermissions(), }, }, }, @@ -139,7 +139,7 @@ func resourceArmKeyVaultCreateUpdate(d *schema.ResourceData, meta interface{}) e tags := d.Get("tags").(map[string]interface{}) policies := d.Get("access_policy").([]interface{}) - accessPolicies, err := azschema.ExpandKeyVaultAccessPolicies(policies) + accessPolicies, err := azure.ExpandKeyVaultAccessPolicies(policies) if err != nil { return fmt.Errorf("Error expanding `access_policy`: %+v", policies) } @@ -233,12 +233,12 @@ func resourceArmKeyVaultRead(d *schema.ResourceData, meta interface{}) error { d.Set("enabled_for_disk_encryption", props.EnabledForDiskEncryption) d.Set("enabled_for_template_deployment", props.EnabledForTemplateDeployment) if err := d.Set("sku", flattenKeyVaultSku(props.Sku)); err != nil { - return fmt.Errorf("Error flattening `sku` for KeyVault %q: %+v", resp.Name, err) + return fmt.Errorf("Error flattening `sku` for KeyVault %s: %+v", *resp.Name, err) } - flattenedPolicies := azschema.FlattenKeyVaultAccessPolicies(props.AccessPolicies) + flattenedPolicies := azure.FlattenKeyVaultAccessPolicies(props.AccessPolicies) if err := d.Set("access_policy", flattenedPolicies); err != nil { - return fmt.Errorf("Error flattening `access_policy` for KeyVault %q: %+v", resp.Name, err) + return fmt.Errorf("Error flattening `access_policy` for KeyVault %s: %+v", *resp.Name, err) } d.Set("vault_uri", props.VaultURI) } diff --git a/azurerm/resource_arm_key_vault_access_policy.go b/azurerm/resource_arm_key_vault_access_policy.go index 530d165d3dbe7..24c96612df59a 100644 --- a/azurerm/resource_arm_key_vault_access_policy.go +++ b/azurerm/resource_arm_key_vault_access_policy.go @@ -8,8 +8,8 @@ import ( "github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2016-10-01/keyvault" "github.com/hashicorp/terraform/helper/schema" - uuid "github.com/satori/go.uuid" - azschema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/schema" + "github.com/satori/go.uuid" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -53,11 +53,11 @@ func resourceArmKeyVaultAccessPolicy() *schema.Resource { ValidateFunc: validateUUID, }, - "certificate_permissions": azschema.KeyVaultCertificatePermissionsSchema(), + "certificate_permissions": azure.SchemaKeyVaultCertificatePermissions(), - "key_permissions": azschema.KeyVaultKeyPermissionsSchema(), + "key_permissions": azure.SchemaKeyVaultKeyPermissions(), - "secret_permissions": azschema.KeyVaultSecretPermissionsSchema(), + "secret_permissions": azure.SchemaKeyVaultSecretPermissions(), }, } } @@ -79,13 +79,13 @@ func resourceArmKeyVaultAccessPolicyCreateOrDelete(d *schema.ResourceData, meta objectId := d.Get("object_id").(string) certPermissionsRaw := d.Get("certificate_permissions").([]interface{}) - certPermissions := azschema.ExpandCertificatePermissions(certPermissionsRaw) + certPermissions := azure.ExpandCertificatePermissions(certPermissionsRaw) keyPermissionsRaw := d.Get("key_permissions").([]interface{}) - keyPermissions := azschema.ExpandKeyPermissions(keyPermissionsRaw) + keyPermissions := azure.ExpandKeyPermissions(keyPermissionsRaw) secretPermissionsRaw := d.Get("secret_permissions").([]interface{}) - secretPermissions := azschema.ExpandSecretPermissions(secretPermissionsRaw) + secretPermissions := azure.ExpandSecretPermissions(secretPermissionsRaw) accessPolicy := keyvault.AccessPolicyEntry{ ObjectID: utils.String(objectId), @@ -209,17 +209,17 @@ func resourceArmKeyVaultAccessPolicyRead(d *schema.ResourceData, meta interface{ } if permissions := policy.Permissions; permissions != nil { - certificatePermissions := azschema.FlattenCertificatePermissions(permissions.Certificates) + certificatePermissions := azure.FlattenCertificatePermissions(permissions.Certificates) if err := d.Set("certificate_permissions", certificatePermissions); err != nil { return fmt.Errorf("Error flattening `certificate_permissions`: %+v", err) } - keyPermissions := azschema.FlattenKeyPermissions(permissions.Keys) + keyPermissions := azure.FlattenKeyPermissions(permissions.Keys) if err := d.Set("key_permissions", keyPermissions); err != nil { return fmt.Errorf("Error flattening `key_permissions`: %+v", err) } - secretPermissions := azschema.FlattenSecretPermissions(permissions.Secrets) + secretPermissions := azure.FlattenSecretPermissions(permissions.Secrets) if err := d.Set("secret_permissions", secretPermissions); err != nil { return fmt.Errorf("Error flattening `secret_permissions`: %+v", err) } diff --git a/azurerm/resource_arm_kubernetes_cluster.go b/azurerm/resource_arm_kubernetes_cluster.go index dd24e53abdadf..2e245b57d09cf 100644 --- a/azurerm/resource_arm_kubernetes_cluster.go +++ b/azurerm/resource_arm_kubernetes_cluster.go @@ -23,6 +23,7 @@ func resourceArmKubernetesCluster() *schema.Resource { Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, + CustomizeDiff: func(diff *schema.ResourceDiff, v interface{}) error { if v, exists := diff.GetOk("network_profile"); exists { rawProfiles := v.([]interface{}) @@ -34,15 +35,25 @@ func resourceArmKubernetesCluster() *schema.Resource { profile := rawProfiles[0].(map[string]interface{}) networkPlugin := profile["network_plugin"].(string) - if networkPlugin == "kubenet" { - dockerBridgeCidr := profile["docker_bridge_cidr"].(string) - dnsServiceIP := profile["dns_service_ip"].(string) - serviceCidr := profile["service_cidr"].(string) + if networkPlugin != "kubenet" && networkPlugin != "azure" { + return nil + } - if dockerBridgeCidr == "" || dnsServiceIP == "" || serviceCidr == "" { - return fmt.Errorf("If the `network_plugin` is set to `kubenet` then the fields `docker_bridge_cidr`, `dns_service_ip` and `service_cidr` must not be empty.") - } + dockerBridgeCidr := profile["docker_bridge_cidr"].(string) + dnsServiceIP := profile["dns_service_ip"].(string) + serviceCidr := profile["service_cidr"].(string) + + // All empty values. + if dockerBridgeCidr == "" && dnsServiceIP == "" && serviceCidr == "" { + return nil } + + // All set values. + if dockerBridgeCidr != "" && dnsServiceIP != "" && serviceCidr != "" { + return nil + } + + return fmt.Errorf("`docker_bridge_cidr`, `dns_service_ip` and `service_cidr` should all be empty or all should be set.") } return nil @@ -213,6 +224,13 @@ func resourceArmKubernetesCluster() *schema.Resource { }, true), DiffSuppressFunc: ignoreCaseDiffSuppressFunc, }, + + "max_pods": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + ForceNew: true, + }, }, }, }, @@ -226,10 +244,12 @@ func resourceArmKubernetesCluster() *schema.Resource { "client_id": { Type: schema.TypeString, Required: true, + ForceNew: true, }, "client_secret": { Type: schema.TypeString, + ForceNew: true, Required: true, Sensitive: true, }, @@ -287,6 +307,57 @@ func resourceArmKubernetesCluster() *schema.Resource { }, }, + "addon_profile": { + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "http_application_routing": { + Type: schema.TypeList, + MaxItems: 1, + ForceNew: true, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + ForceNew: true, + Required: true, + }, + "http_application_routing_zone_name": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + + "oms_agent": { + Type: schema.TypeList, + MaxItems: 1, + Optional: true, + ForceNew: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Required: true, + ForceNew: true, + }, + "log_analytics_workspace_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + }, + }, + }, + }, + }, + "tags": tagsSchema(), }, } @@ -308,6 +379,7 @@ func resourceArmKubernetesClusterCreate(d *schema.ResourceData, meta interface{} agentProfiles := expandAzureRmKubernetesClusterAgentProfiles(d) servicePrincipalProfile := expandAzureRmKubernetesClusterServicePrincipal(d) networkProfile := expandAzureRmKubernetesClusterNetworkProfile(d) + addonProfiles := expandAzureRmKubernetesClusterAddonProfiles(d) tags := d.Get("tags").(map[string]interface{}) @@ -327,6 +399,7 @@ func resourceArmKubernetesClusterCreate(d *schema.ResourceData, meta interface{} Name: &name, Location: &location, ManagedClusterProperties: &containerservice.ManagedClusterProperties{ + AddonProfiles: addonProfiles, AgentPoolProfiles: &agentProfiles, DNSPrefix: &dnsPrefix, KubernetesVersion: &kubernetesVersion, @@ -406,22 +479,27 @@ func resourceArmKubernetesClusterRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("Error setting `linux_profile`: %+v", err) } + addonProfiles := flattenAzureRmKubernetesClusterAddonProfiles(props.AddonProfiles) + if err := d.Set("addon_profile", addonProfiles); err != nil { + return fmt.Errorf("Error setting `addon_profile`: %+v", err) + } + agentPoolProfiles := flattenAzureRmKubernetesClusterAgentPoolProfiles(props.AgentPoolProfiles, resp.Fqdn) if err := d.Set("agent_pool_profile", agentPoolProfiles); err != nil { return fmt.Errorf("Error setting `agent_pool_profile`: %+v", err) } + networkProfile := flattenAzureRmKubernetesClusterNetworkProfile(props.NetworkProfile) + if err := d.Set("network_profile", networkProfile); err != nil { + return fmt.Errorf("Error setting `network_profile`: %+v", err) + } + servicePrincipal := flattenAzureRmKubernetesClusterServicePrincipalProfile(resp.ManagedClusterProperties.ServicePrincipalProfile) if err := d.Set("service_principal", servicePrincipal); err != nil { return fmt.Errorf("Error setting `service_principal`: %+v", err) } } - networkProfile := flattenAzureRmKubernetesClusterNetworkProfile(resp.NetworkProfile) - if err := d.Set("network_profile", networkProfile); err != nil { - return fmt.Errorf("Error setting `network_profile`: %+v", err) - } - kubeConfigRaw, kubeConfig := flattenAzureRmKubernetesClusterAccessProfile(&profile) d.Set("kube_config_raw", kubeConfigRaw) @@ -519,6 +597,10 @@ func flattenAzureRmKubernetesClusterAgentPoolProfiles(profiles *[]containerservi agentPoolProfile["os_type"] = string(profile.OsType) } + if profile.MaxPods != nil { + agentPoolProfile["max_pods"] = int(*profile.MaxPods) + } + agentPoolProfiles = append(agentPoolProfiles, agentPoolProfile) } @@ -678,6 +760,10 @@ func expandAzureRmKubernetesClusterAgentProfiles(d *schema.ResourceData) []conta OsType: containerservice.OSType(osType), } + if maxPods := int32(config["max_pods"].(int)); maxPods > 0 { + profile.MaxPods = utils.Int32(maxPods) + } + vnetSubnetID := config["vnet_subnet_id"].(string) if vnetSubnetID != "" { profile.VnetSubnetID = utils.String(vnetSubnetID) @@ -725,6 +811,89 @@ func expandAzureRmKubernetesClusterNetworkProfile(d *schema.ResourceData) *conta return &networkProfile } +func expandAzureRmKubernetesClusterAddonProfiles(d *schema.ResourceData) map[string]*containerservice.ManagedClusterAddonProfile { + profiles := d.Get("addon_profile").([]interface{}) + if len(profiles) == 0 { + return nil + } + + profile := profiles[0].(map[string]interface{}) + addonProfiles := map[string]*containerservice.ManagedClusterAddonProfile{} + + httpApplicationRouting := profile["http_application_routing"].([]interface{}) + if len(httpApplicationRouting) > 0 { + value := httpApplicationRouting[0].(map[string]interface{}) + enabled := value["enabled"].(bool) + addonProfiles["httpApplicationRouting"] = &containerservice.ManagedClusterAddonProfile{ + Enabled: utils.Bool(enabled), + } + } + + omsAgent := profile["oms_agent"].([]interface{}) + if len(omsAgent) > 0 { + value := omsAgent[0].(map[string]interface{}) + config := make(map[string]*string) + enabled := value["enabled"].(bool) + + if workspaceId, ok := value["log_analytics_workspace_id"]; ok { + config["logAnalyticsWorkspaceResourceID"] = utils.String(workspaceId.(string)) + } + + addonProfiles["omsAgent"] = &containerservice.ManagedClusterAddonProfile{ + Enabled: utils.Bool(enabled), + Config: config, + } + } + + return addonProfiles +} + +func flattenAzureRmKubernetesClusterAddonProfiles(profile map[string]*containerservice.ManagedClusterAddonProfile) []interface{} { + values := make(map[string]interface{}, 0) + + routes := make([]interface{}, 0) + if httpApplicationRouting := profile["httpApplicationRouting"]; httpApplicationRouting != nil { + enabled := false + if enabledVal := httpApplicationRouting.Enabled; enabledVal != nil { + enabled = *enabledVal + } + + zoneName := "" + if v := httpApplicationRouting.Config["HTTPApplicationRoutingZoneName"]; v != nil { + zoneName = *v + } + + output := map[string]interface{}{ + "enabled": enabled, + "http_application_routing_zone_name": zoneName, + } + routes = append(routes, output) + } + values["http_application_routing"] = routes + + agents := make([]interface{}, 0) + if omsAgent := profile["omsAgent"]; omsAgent != nil { + enabled := false + if enabledVal := omsAgent.Enabled; enabledVal != nil { + enabled = *enabledVal + } + + workspaceId := "" + if workspaceResourceID := omsAgent.Config["logAnalyticsWorkspaceResourceID"]; workspaceResourceID != nil { + workspaceId = *workspaceResourceID + } + + output := map[string]interface{}{ + "enabled": enabled, + "log_analytics_workspace_id": workspaceId, + } + agents = append(agents, output) + } + values["oms_agent"] = agents + + return []interface{}{values} +} + func resourceAzureRMKubernetesClusterServicePrincipalProfileHash(v interface{}) int { var buf bytes.Buffer diff --git a/azurerm/resource_arm_kubernetes_cluster_test.go b/azurerm/resource_arm_kubernetes_cluster_test.go index 1ea7c68a0d2a2..f40e238082056 100644 --- a/azurerm/resource_arm_kubernetes_cluster_test.go +++ b/azurerm/resource_arm_kubernetes_cluster_test.go @@ -11,7 +11,7 @@ import ( "github.com/hashicorp/terraform/terraform" ) -func TestAccAzureRMKubernetesCluster_agentPoolName(t *testing.T) { +func TestAzureRMKubernetesCluster_agentPoolName(t *testing.T) { cases := []struct { Input string ExpectError bool @@ -91,6 +91,7 @@ func TestAccAzureRMKubernetesCluster_basic(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "kube_config.0.host"), resource.TestCheckResourceAttrSet(resourceName, "kube_config.0.username"), resource.TestCheckResourceAttrSet(resourceName, "kube_config.0.password"), + resource.TestCheckResourceAttrSet(resourceName, "agent_pool_profile.0.max_pods"), ), }, }, @@ -172,6 +173,59 @@ func TestAccAzureRMKubernetesCluster_internalNetwork(t *testing.T) { Config: config, Check: resource.ComposeTestCheckFunc( testCheckAzureRMKubernetesClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "agent_pool_profile.0.max_pods", "60"), + ), + }, + }, + }) +} + +func TestAccAzureRMKubernetesCluster_addonProfileOMS(t *testing.T) { + resourceName := "azurerm_kubernetes_cluster.test" + ri := acctest.RandInt() + clientId := os.Getenv("ARM_CLIENT_ID") + clientSecret := os.Getenv("ARM_CLIENT_SECRET") + config := testAccAzureRMKubernetesCluster_addonProfileOMS(ri, clientId, clientSecret, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMKubernetesClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMKubernetesClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "addon_profile.0.http_application_routing.#", "0"), + resource.TestCheckResourceAttr(resourceName, "addon_profile.0.oms_agent.#", "1"), + resource.TestCheckResourceAttr(resourceName, "addon_profile.0.oms_agent.0.enabled", "true"), + resource.TestCheckResourceAttrSet(resourceName, "addon_profile.0.oms_agent.0.log_analytics_workspace_id"), + ), + }, + }, + }) +} + +func TestAccAzureRMKubernetesCluster_addonProfileRouting(t *testing.T) { + resourceName := "azurerm_kubernetes_cluster.test" + ri := acctest.RandInt() + clientId := os.Getenv("ARM_CLIENT_ID") + clientSecret := os.Getenv("ARM_CLIENT_SECRET") + config := testAccAzureRMKubernetesCluster_addonProfileRouting(ri, clientId, clientSecret, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMKubernetesClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMKubernetesClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "addon_profile.0.http_application_routing.#", "1"), + resource.TestCheckResourceAttrSet(resourceName, "addon_profile.0.http_application_routing.0.enabled"), + resource.TestCheckResourceAttrSet(resourceName, "addon_profile.0.http_application_routing.0.http_application_routing_zone_name"), + resource.TestCheckResourceAttr(resourceName, "addon_profile.0.oms_agent.#", "0"), ), }, }, @@ -183,7 +237,7 @@ func TestAccAzureRMKubernetesCluster_advancedNetworkingKubenet(t *testing.T) { ri := acctest.RandInt() clientId := os.Getenv("ARM_CLIENT_ID") clientSecret := os.Getenv("ARM_CLIENT_SECRET") - config := testAccAzureRMKubernetesCluster_advancedNetworkingKubenet(ri, clientId, clientSecret, testLocation()) + config := testAccAzureRMKubernetesCluster_advancedNetworking(ri, clientId, clientSecret, testLocation(), "kubenet") resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -206,7 +260,7 @@ func TestAccAzureRMKubernetesCluster_advancedNetworkingKubenetComplete(t *testin ri := acctest.RandInt() clientId := os.Getenv("ARM_CLIENT_ID") clientSecret := os.Getenv("ARM_CLIENT_SECRET") - config := testAccAzureRMKubernetesCluster_advancedNetworkingKubenetComplete(ri, clientId, clientSecret, testLocation()) + config := testAccAzureRMKubernetesCluster_advancedNetworkingComplete(ri, clientId, clientSecret, testLocation(), "kubenet") resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -229,7 +283,30 @@ func TestAccAzureRMKubernetesCluster_advancedNetworkingAzure(t *testing.T) { ri := acctest.RandInt() clientId := os.Getenv("ARM_CLIENT_ID") clientSecret := os.Getenv("ARM_CLIENT_SECRET") - config := testAccAzureRMKubernetesCluster_advancedNetworkingAzure(ri, clientId, clientSecret, testLocation()) + config := testAccAzureRMKubernetesCluster_advancedNetworking(ri, clientId, clientSecret, testLocation(), "azure") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMKubernetesClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMKubernetesClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "network_profile.0.network_plugin", "azure"), + ), + }, + }, + }) +} + +func TestAccAzureRMKubernetesCluster_advancedNetworkingAzureComplete(t *testing.T) { + resourceName := "azurerm_kubernetes_cluster.test" + ri := acctest.RandInt() + clientId := os.Getenv("ARM_CLIENT_ID") + clientSecret := os.Getenv("ARM_CLIENT_SECRET") + config := testAccAzureRMKubernetesCluster_advancedNetworkingComplete(ri, clientId, clientSecret, testLocation(), "azure") resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -364,6 +441,7 @@ resource "azurerm_kubernetes_cluster" "test" { count = "2" vm_size = "Standard_DS2_v2" vnet_subnet_id = "${azurerm_subnet.test.id}" + max_pods = 60 } service_principal { @@ -374,65 +452,99 @@ resource "azurerm_kubernetes_cluster" "test" { `, rInt, location, rInt, rInt, rInt, rInt, rInt, clientId, clientSecret) } -func testAccAzureRMKubernetesCluster_upgrade(rInt int, clientId string, clientSecret string, location string) string { +func testAccAzureRMKubernetesCluster_addonProfileOMS(rInt int, clientId string, clientSecret string, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" location = "%s" } -resource "azurerm_kubernetes_cluster" "test" { - name = "acctestaks%d" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - dns_prefix = "acctestaks%d" - kubernetes_version = "1.8.1" +resource "azurerm_log_analytics_workspace" "test" { + name = "acctest-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + sku = "PerGB2018" +} +resource "azurerm_kubernetes_cluster" "test" { + name = "acctestaks%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + dns_prefix = "acctestaks%d" + kubernetes_version = "1.7.7" linux_profile { admin_username = "acctestuser%d" - ssh_key { key_data = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCqaZoyiz1qbdOQ8xEf6uEu1cCwYowo5FHtsBhqLoDnnp7KUTEBN+L2NxRIfQ781rxV6Iq5jSav6b2Q8z5KiseOlvKA/RF2wqU0UPYqQviQhLmW6THTpmrv/YkUCuzxDpsH7DUDhZcwySLKVVe0Qm3+5N2Ta6UYH3lsDf9R9wTP2K/+vAnflKebuypNlmocIvakFWoZda18FOmsOoIVXQ8HWFNCuw9ZCunMSN62QGamCe3dL5cXlkgHYv7ekJE15IA9aOJcM7e90oeTqo+7HTcWfdu0qQqPWY5ujyMw/llas8tsXY85LFqRnr3gJ02bAscjc477+X+j/gkpFoN1QEmt terraform@demo.tld" } } agent_pool_profile { - name = "default" - count = "1" - vm_size = "Standard_DS2_v2" + name = "default" + count = "1" + vm_size = "Standard_DS2_v2" } service_principal { client_id = "%s" client_secret = "%s" } + + addon_profile { + oms_agent { + enabled = true + log_analytics_workspace_id = "${azurerm_log_analytics_workspace.test.id}" + } + } } -`, rInt, location, rInt, rInt, rInt, clientId, clientSecret) +`, rInt, location, rInt, rInt, rInt, rInt, clientId, clientSecret) } -func testAccAzureRMKubernetesCluster_advancedNetworkingKubenet(rInt int, clientId string, clientSecret string, location string) string { +func testAccAzureRMKubernetesCluster_addonProfileRouting(rInt int, clientId string, clientSecret string, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" location = "%s" } -resource "azurerm_virtual_network" "test" { - name = "acctestvirtnet%d" - address_space = ["10.1.0.0/16"] +resource "azurerm_kubernetes_cluster" "test" { + name = "acctestaks%d" location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" + dns_prefix = "acctestaks%d" + kubernetes_version = "1.7.7" + linux_profile { + admin_username = "acctestuser%d" + ssh_key { + key_data = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCqaZoyiz1qbdOQ8xEf6uEu1cCwYowo5FHtsBhqLoDnnp7KUTEBN+L2NxRIfQ781rxV6Iq5jSav6b2Q8z5KiseOlvKA/RF2wqU0UPYqQviQhLmW6THTpmrv/YkUCuzxDpsH7DUDhZcwySLKVVe0Qm3+5N2Ta6UYH3lsDf9R9wTP2K/+vAnflKebuypNlmocIvakFWoZda18FOmsOoIVXQ8HWFNCuw9ZCunMSN62QGamCe3dL5cXlkgHYv7ekJE15IA9aOJcM7e90oeTqo+7HTcWfdu0qQqPWY5ujyMw/llas8tsXY85LFqRnr3gJ02bAscjc477+X+j/gkpFoN1QEmt terraform@demo.tld" + } + } - tags { - environment = "Testing" + agent_pool_profile { + name = "default" + count = "1" + vm_size = "Standard_DS2_v2" } + + service_principal { + client_id = "%s" + client_secret = "%s" + } + + addon_profile { + http_application_routing { + enabled = true + } + } +} +`, rInt, location, rInt, rInt, rInt, clientId, clientSecret) } -resource "azurerm_subnet" "test" { - name = "acctestsubnet%d" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.1.0.0/24" +func testAccAzureRMKubernetesCluster_upgrade(rInt int, clientId string, clientSecret string, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" } resource "azurerm_kubernetes_cluster" "test" { @@ -440,7 +552,7 @@ resource "azurerm_kubernetes_cluster" "test" { location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" dns_prefix = "acctestaks%d" - kubernetes_version = "1.7.7" + kubernetes_version = "1.8.1" linux_profile { admin_username = "acctestuser%d" @@ -451,28 +563,20 @@ resource "azurerm_kubernetes_cluster" "test" { } agent_pool_profile { - name = "default" - count = "2" - vm_size = "Standard_DS2_v2" - vnet_subnet_id = "${azurerm_subnet.test.id}" + name = "default" + count = "1" + vm_size = "Standard_DS2_v2" } service_principal { client_id = "%s" client_secret = "%s" } - - network_profile { - network_plugin = "kubenet" - dns_service_ip = "10.10.0.10" - docker_bridge_cidr = "172.18.0.1/16" - service_cidr = "10.10.0.0/16" - } } -`, rInt, location, rInt, rInt, rInt, rInt, rInt, clientId, clientSecret) +`, rInt, location, rInt, rInt, rInt, clientId, clientSecret) } -func testAccAzureRMKubernetesCluster_advancedNetworkingKubenetComplete(rInt int, clientId string, clientSecret string, location string) string { +func testAccAzureRMKubernetesCluster_advancedNetworking(rInt int, clientId string, clientSecret string, location string, networkPlugin string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" @@ -523,18 +627,15 @@ resource "azurerm_kubernetes_cluster" "test" { client_id = "%s" client_secret = "%s" } - + network_profile { - network_plugin = "kubenet" - dns_service_ip = "10.10.0.10" - docker_bridge_cidr = "172.18.0.1/16" - service_cidr = "10.10.0.0/16" + network_plugin = "%s" } } -`, rInt, location, rInt, rInt, rInt, rInt, rInt, clientId, clientSecret) +`, rInt, location, rInt, rInt, rInt, rInt, rInt, clientId, clientSecret, networkPlugin) } -func testAccAzureRMKubernetesCluster_advancedNetworkingAzure(rInt int, clientId string, clientSecret string, location string) string { +func testAccAzureRMKubernetesCluster_advancedNetworkingComplete(rInt int, clientId string, clientSecret string, location string, networkPlugin string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { name = "acctestRG-%d" @@ -585,12 +686,15 @@ resource "azurerm_kubernetes_cluster" "test" { client_id = "%s" client_secret = "%s" } - + network_profile { - network_plugin = "azure" + network_plugin = "%s" + dns_service_ip = "10.10.0.10" + docker_bridge_cidr = "172.18.0.1/16" + service_cidr = "10.10.0.0/16" } } -`, rInt, location, rInt, rInt, rInt, rInt, rInt, clientId, clientSecret) +`, rInt, location, rInt, rInt, rInt, rInt, rInt, clientId, clientSecret, networkPlugin) } func testCheckAzureRMKubernetesClusterExists(name string) resource.TestCheckFunc { diff --git a/azurerm/resource_arm_loadbalancer.go b/azurerm/resource_arm_loadbalancer.go index ca311c6d9a98a..ce5f45e8e02d0 100644 --- a/azurerm/resource_arm_loadbalancer.go +++ b/azurerm/resource_arm_loadbalancer.go @@ -6,7 +6,6 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network" - "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" @@ -141,7 +140,7 @@ func resourceArmLoadBalancerCreate(d *schema.ResourceData, meta interface{}) err client := meta.(*ArmClient).loadBalancerClient ctx := meta.(*ArmClient).StopContext - log.Printf("[INFO] preparing arguments for Azure ARM LoadBalancer creation.") + log.Printf("[INFO] preparing arguments for Azure ARM Load Balancer creation.") name := d.Get("name").(string) location := azureRMNormalizeLocation(d.Get("location").(string)) @@ -168,26 +167,26 @@ func resourceArmLoadBalancerCreate(d *schema.ResourceData, meta interface{}) err future, err := client.CreateOrUpdate(ctx, resGroup, name, loadBalancer) if err != nil { - return fmt.Errorf("Error Creating/Updating LoadBalancer %q (Resource Group %q): %+v", name, resGroup, err) + return fmt.Errorf("Error Creating/Updating Load Balancer %q (Resource Group %q): %+v", name, resGroup, err) } err = future.WaitForCompletionRef(ctx, client.Client) if err != nil { - return fmt.Errorf("Error Creating/Updating LoadBalancer %q (Resource Group %q): %+v", name, resGroup, err) + return fmt.Errorf("Error Creating/Updating Load Balancer %q (Resource Group %q): %+v", name, resGroup, err) } read, err := client.Get(ctx, resGroup, name, "") if err != nil { - return fmt.Errorf("Error Retrieving LoadBalancer %q (Resource Group %q): %+v", name, resGroup, err) + return fmt.Errorf("Error Retrieving Load Balancer %q (Resource Group %q): %+v", name, resGroup, err) } if read.ID == nil { - return fmt.Errorf("Cannot read LoadBalancer %q (resource group %q) ID", name, resGroup) + return fmt.Errorf("Cannot read Load Balancer %q (resource group %q) ID", name, resGroup) } d.SetId(*read.ID) // TODO: is this still needed? - log.Printf("[DEBUG] Waiting for LoadBalancer (%q) to become available", name) + log.Printf("[DEBUG] Waiting for Load Balancer (%q) to become available", name) stateConf := &resource.StateChangeConf{ Pending: []string{"Accepted", "Updating"}, Target: []string{"Succeeded"}, @@ -195,7 +194,7 @@ func resourceArmLoadBalancerCreate(d *schema.ResourceData, meta interface{}) err Timeout: 10 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for LoadBalancer (%q - Resource Group %q) to become available: %s", name, resGroup, err) + return fmt.Errorf("Error waiting for Load Balancer (%q - Resource Group %q) to become available: %s", name, resGroup, err) } return resourceArmLoadBalancerRead(d, meta) @@ -213,7 +212,7 @@ func resourceArmLoadBalancerRead(d *schema.ResourceData, meta interface{}) error } if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Id()) + log.Printf("[INFO] Load Balancer %q not found. Removing from state", d.Id()) return nil } @@ -261,7 +260,7 @@ func resourceArmLoadBalancerDelete(d *schema.ResourceData, meta interface{}) err id, err := parseAzureResourceID(d.Id()) if err != nil { - return errwrap.Wrapf("Error Parsing Azure Resource ID {{err}}", err) + return fmt.Errorf("Error Parsing Azure Resource ID: %+v", err) } resGroup := id.ResourceGroup name := id.Path["loadBalancers"] diff --git a/azurerm/resource_arm_loadbalancer_backend_address_pool.go b/azurerm/resource_arm_loadbalancer_backend_address_pool.go index 79ed02e05007b..cca71e22426a2 100644 --- a/azurerm/resource_arm_loadbalancer_backend_address_pool.go +++ b/azurerm/resource_arm_loadbalancer_backend_address_pool.go @@ -6,9 +6,10 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network" - "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -23,9 +24,10 @@ func resourceArmLoadBalancerBackendAddressPool() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.NoZeroValues, }, "location": deprecatedLocationSchema(), @@ -33,23 +35,30 @@ func resourceArmLoadBalancerBackendAddressPool() *schema.Resource { "resource_group_name": resourceGroupNameSchema(), "loadbalancer_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: azure.ValidateResourceID, }, "backend_ip_configurations": { Type: schema.TypeSet, Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.NoZeroValues, + }, + Set: schema.HashString, }, "load_balancing_rules": { Type: schema.TypeSet, Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.NoZeroValues, + }, + Set: schema.HashString, }, }, } @@ -65,11 +74,11 @@ func resourceArmLoadBalancerBackendAddressPoolCreate(d *schema.ResourceData, met loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta) if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err) + return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err) } if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string)) + log.Printf("[INFO] Load Balancer %q not found. Removing from state", d.Get("name").(string)) return nil } @@ -85,17 +94,17 @@ func resourceArmLoadBalancerBackendAddressPoolCreate(d *schema.ResourceData, met loadBalancer.LoadBalancerPropertiesFormat.BackendAddressPools = &backendAddressPools resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string)) if err != nil { - return fmt.Errorf("Error parsing LoadBalancer Name and Group: %+v", err) + return fmt.Errorf("Error parsing Load Balancer Name and Group: %+v", err) } future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer) if err != nil { - return fmt.Errorf("Error Creating/Updating LoadBalancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error Creating/Updating Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) } err = future.WaitForCompletionRef(ctx, client.Client) if err != nil { - return fmt.Errorf("Error Creating/Updating LoadBalancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error Creating/Updating Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) } read, err := client.Get(ctx, resGroup, loadBalancerName, "") @@ -103,7 +112,7 @@ func resourceArmLoadBalancerBackendAddressPoolCreate(d *schema.ResourceData, met return fmt.Errorf("Error retrieving Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) } if read.ID == nil { - return fmt.Errorf("Cannot read LoadBalancer %q (Resource Group %q) ID", loadBalancerName, resGroup) + return fmt.Errorf("Cannot read Load Balancer %q (Resource Group %q) ID", loadBalancerName, resGroup) } var poolId string @@ -114,13 +123,13 @@ func resourceArmLoadBalancerBackendAddressPoolCreate(d *schema.ResourceData, met } if poolId == "" { - return fmt.Errorf("Cannot find created LoadBalancer Backend Address Pool ID %q", poolId) + return fmt.Errorf("Cannot find created Load Balancer Backend Address Pool ID %q", poolId) } d.SetId(poolId) // TODO: is this still needed? - log.Printf("[DEBUG] Waiting for LoadBalancer (%s) to become available", loadBalancerName) + log.Printf("[DEBUG] Waiting for Load Balancer (%s) to become available", loadBalancerName) stateConf := &resource.StateChangeConf{ Pending: []string{"Accepted", "Updating"}, Target: []string{"Succeeded"}, @@ -128,7 +137,7 @@ func resourceArmLoadBalancerBackendAddressPoolCreate(d *schema.ResourceData, met Timeout: 10 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for LoadBalancer (%q Resource Group %q) to become available: %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error waiting for Load Balancer (%q Resource Group %q) to become available: %+v", loadBalancerName, resGroup, err) } return resourceArmLoadBalancerBackendAddressPoolRead(d, meta) @@ -147,14 +156,14 @@ func resourceArmLoadBalancerBackendAddressPoolRead(d *schema.ResourceData, meta } if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer %q not found. Removing from state", name) + log.Printf("[INFO] Load Balancer %q not found. Removing from state", name) return nil } config, _, exists := findLoadBalancerBackEndAddressPoolByName(loadBalancer, name) if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer Backend Address Pool %q not found. Removing from state", name) + log.Printf("[INFO] Load Balancer Backend Address Pool %q not found. Removing from state", name) return nil } @@ -212,7 +221,7 @@ func resourceArmLoadBalancerBackendAddressPoolDelete(d *schema.ResourceData, met resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string)) if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err) + return fmt.Errorf("Error Getting Load Balancer Name and Group:: %+v", err) } future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer) @@ -227,10 +236,10 @@ func resourceArmLoadBalancerBackendAddressPoolDelete(d *schema.ResourceData, met read, err := client.Get(ctx, resGroup, loadBalancerName, "") if err != nil { - return fmt.Errorf("Error retrieving the LoadBalancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error retrieving the Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) } if read.ID == nil { - return fmt.Errorf("Cannot read LoadBalancer %q (resource group %q) ID", loadBalancerName, resGroup) + return fmt.Errorf("Cannot read Load Balancer %q (resource group %q) ID", loadBalancerName, resGroup) } return nil diff --git a/azurerm/resource_arm_loadbalancer_backend_address_pool_test.go b/azurerm/resource_arm_loadbalancer_backend_address_pool_test.go index a982c7cd6ac44..3ddf86ffaacf5 100644 --- a/azurerm/resource_arm_loadbalancer_backend_address_pool_test.go +++ b/azurerm/resource_arm_loadbalancer_backend_address_pool_test.go @@ -160,12 +160,12 @@ func testCheckAzureRMLoadBalancerBackEndAddressPoolDisappears(addressPoolName st future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, *lb.Name, *lb) if err != nil { - return fmt.Errorf("Error Creating/Updating LoadBalancer %+v", err) + return fmt.Errorf("Error Creating/Updating Load Balancer %+v", err) } err = future.WaitForCompletionRef(ctx, client.Client) if err != nil { - return fmt.Errorf("Error Creating/Updating LoadBalancer %+v", err) + return fmt.Errorf("Error Creating/Updating Load Balancer %+v", err) } _, err = client.Get(ctx, id.ResourceGroup, *lb.Name, "") diff --git a/azurerm/resource_arm_loadbalancer_nat_pool.go b/azurerm/resource_arm_loadbalancer_nat_pool.go index 80cf2c10903ae..d8ffc22972d09 100644 --- a/azurerm/resource_arm_loadbalancer_nat_pool.go +++ b/azurerm/resource_arm_loadbalancer_nat_pool.go @@ -6,9 +6,12 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network" - "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -24,9 +27,10 @@ func resourceArmLoadBalancerNatPool() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.NoZeroValues, }, "location": deprecatedLocationSchema(), @@ -34,36 +38,46 @@ func resourceArmLoadBalancerNatPool() *schema.Resource { "resource_group_name": resourceGroupNameSchema(), "loadbalancer_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: azure.ValidateResourceID, }, "protocol": { Type: schema.TypeString, Required: true, StateFunc: ignoreCaseStateFunc, - DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + DiffSuppressFunc: suppress.CaseDifference, + ValidateFunc: validation.StringInSlice([]string{ + string(network.TransportProtocolAll), + string(network.TransportProtocolTCP), + string(network.TransportProtocolUDP), + }, true), }, "frontend_port_start": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validate.PortNumber, }, "frontend_port_end": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validate.PortNumber, }, "backend_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validate.PortNumber, }, "frontend_ip_configuration_name": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.NoZeroValues, }, "frontend_ip_configuration_id": { @@ -84,17 +98,17 @@ func resourceArmLoadBalancerNatPoolCreate(d *schema.ResourceData, meta interface loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta) if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err) + return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err) } if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string)) + log.Printf("[INFO] Load Balancer %q not found. Removing from state", d.Get("name").(string)) return nil } newNatPool, err := expandAzureRmLoadBalancerNatPool(d, loadBalancer) if err != nil { - return errwrap.Wrapf("Error Expanding NAT Pool {{err}}", err) + return fmt.Errorf("Error Expanding NAT Pool: %+v", err) } natPools := append(*loadBalancer.LoadBalancerPropertiesFormat.InboundNatPools, *newNatPool) @@ -110,7 +124,7 @@ func resourceArmLoadBalancerNatPoolCreate(d *schema.ResourceData, meta interface loadBalancer.LoadBalancerPropertiesFormat.InboundNatPools = &natPools resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string)) if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err) + return fmt.Errorf("Error Getting Load Balancer Name and Group:: %+v", err) } future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer) @@ -128,7 +142,7 @@ func resourceArmLoadBalancerNatPoolCreate(d *schema.ResourceData, meta interface return fmt.Errorf("Error retrieving Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) } if read.ID == nil { - return fmt.Errorf("Cannot read LoadBalancer %q (Resource Group %q) ID", loadBalancerName, resGroup) + return fmt.Errorf("Cannot read Load Balancer %q (Resource Group %q) ID", loadBalancerName, resGroup) } var natPoolId string @@ -139,13 +153,13 @@ func resourceArmLoadBalancerNatPoolCreate(d *schema.ResourceData, meta interface } if natPoolId == "" { - return fmt.Errorf("Cannot find created LoadBalancer NAT Pool ID %q", natPoolId) + return fmt.Errorf("Cannot find created Load Balancer NAT Pool ID %q", natPoolId) } d.SetId(natPoolId) // TODO: is this needed? - log.Printf("[DEBUG] Waiting for LoadBalancer (%q) to become available", loadBalancerName) + log.Printf("[DEBUG] Waiting for Load Balancer (%q) to become available", loadBalancerName) stateConf := &resource.StateChangeConf{ Pending: []string{"Accepted", "Updating"}, Target: []string{"Succeeded"}, @@ -153,7 +167,7 @@ func resourceArmLoadBalancerNatPoolCreate(d *schema.ResourceData, meta interface Timeout: 10 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for LoadBalancer (%q - Resource Group %q) to become available: %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error waiting for Load Balancer (%q - Resource Group %q) to become available: %+v", loadBalancerName, resGroup, err) } return resourceArmLoadBalancerNatPoolRead(d, meta) @@ -172,14 +186,14 @@ func resourceArmLoadBalancerNatPoolRead(d *schema.ResourceData, meta interface{} } if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer %q not found. Removing from state", name) + log.Printf("[INFO] Load Balancer %q not found. Removing from state", name) return nil } config, _, exists := findLoadBalancerNatPoolByName(loadBalancer, name) if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer Nat Pool %q not found. Removing from state", name) + log.Printf("[INFO] Load Balancer Nat Pool %q not found. Removing from state", name) return nil } @@ -216,7 +230,7 @@ func resourceArmLoadBalancerNatPoolDelete(d *schema.ResourceData, meta interface loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta) if err != nil { - return fmt.Errorf("Error retrieving LoadBalancer by ID: %+v", err) + return fmt.Errorf("Error retrieving Load Balancer by ID: %+v", err) } if !exists { d.SetId("") @@ -234,7 +248,7 @@ func resourceArmLoadBalancerNatPoolDelete(d *schema.ResourceData, meta interface resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string)) if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err) + return fmt.Errorf("Error Getting Load Balancer Name and Group:: %+v", err) } future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer) @@ -252,7 +266,7 @@ func resourceArmLoadBalancerNatPoolDelete(d *schema.ResourceData, meta interface return fmt.Errorf("Error retrieving Load Balancer: %+v", err) } if read.ID == nil { - return fmt.Errorf("Cannot read LoadBalancer %q (Resource Group %q) ID", loadBalancerName, resGroup) + return fmt.Errorf("Cannot read Load Balancer %q (Resource Group %q) ID", loadBalancerName, resGroup) } return nil @@ -273,17 +287,13 @@ func expandAzureRmLoadBalancerNatPool(d *schema.ResourceData, lb *network.LoadBa return nil, fmt.Errorf("[ERROR] Cannot find FrontEnd IP Configuration with the name %s", v) } - feip := network.SubResource{ + properties.FrontendIPConfiguration = &network.SubResource{ ID: rule.ID, } - - properties.FrontendIPConfiguration = &feip } - natPool := network.InboundNatPool{ + return &network.InboundNatPool{ Name: utils.String(d.Get("name").(string)), InboundNatPoolPropertiesFormat: &properties, - } - - return &natPool, nil + }, nil } diff --git a/azurerm/resource_arm_loadbalancer_nat_pool_test.go b/azurerm/resource_arm_loadbalancer_nat_pool_test.go index 337e17152251f..8648206c7b1b6 100644 --- a/azurerm/resource_arm_loadbalancer_nat_pool_test.go +++ b/azurerm/resource_arm_loadbalancer_nat_pool_test.go @@ -200,12 +200,12 @@ func testCheckAzureRMLoadBalancerNatPoolDisappears(natPoolName string, lb *netwo future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, *lb.Name, *lb) if err != nil { - return fmt.Errorf("Error Creating/Updating LoadBalancer %+v", err) + return fmt.Errorf("Error Creating/Updating Load Balancer %+v", err) } err = future.WaitForCompletionRef(ctx, client.Client) if err != nil { - return fmt.Errorf("Error waiting for the completion of LoadBalancer %+v", err) + return fmt.Errorf("Error waiting for the completion of Load Balancer %+v", err) } _, err = client.Get(ctx, id.ResourceGroup, *lb.Name, "") @@ -283,49 +283,52 @@ func testAccAzureRMLoadBalancerNatPool_multiplePools(rInt int, natPoolName, natP return fmt.Sprintf(` resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" + name = "acctestRG-%d" location = "%s" } resource "azurerm_public_ip" "test" { - name = "test-ip-%d" - location = "${azurerm_resource_group.test.location}" + name = "test-ip-%d" + location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" + public_ip_address_allocation = "static" } resource "azurerm_lb" "test" { - name = "arm-test-loadbalancer-%d" - location = "${azurerm_resource_group.test.location}" + name = "arm-test-loadbalancer-%d" + location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" frontend_ip_configuration { - name = "one-%d" + name = "one-%d" public_ip_address_id = "${azurerm_public_ip.test.id}" } } resource "azurerm_lb_nat_pool" "test" { - location = "${azurerm_resource_group.test.location}" + location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" - loadbalancer_id = "${azurerm_lb.test.id}" - name = "%s" - protocol = "Tcp" + loadbalancer_id = "${azurerm_lb.test.id}" + name = "%s" + protocol = "Tcp" frontend_port_start = 80 - frontend_port_end = 81 - backend_port = 3389 + frontend_port_end = 81 + backend_port = 3389 + frontend_ip_configuration_name = "one-%d" } resource "azurerm_lb_nat_pool" "test2" { - location = "${azurerm_resource_group.test.location}" + location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" - loadbalancer_id = "${azurerm_lb.test.id}" - name = "%s" - protocol = "Tcp" + loadbalancer_id = "${azurerm_lb.test.id}" + name = "%s" + protocol = "Tcp" frontend_port_start = 82 - frontend_port_end = 83 - backend_port = 3390 + frontend_port_end = 83 + backend_port = 3390 + frontend_ip_configuration_name = "one-%d" } `, rInt, location, rInt, rInt, rInt, natPoolName, rInt, natPool2Name, rInt) diff --git a/azurerm/resource_arm_loadbalancer_nat_rule.go b/azurerm/resource_arm_loadbalancer_nat_rule.go index 09046721e1c87..01570e0c8fb20 100644 --- a/azurerm/resource_arm_loadbalancer_nat_rule.go +++ b/azurerm/resource_arm_loadbalancer_nat_rule.go @@ -6,27 +6,32 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network" - "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) func resourceArmLoadBalancerNatRule() *schema.Resource { return &schema.Resource{ - Create: resourceArmLoadBalancerNatRuleCreate, + Create: resourceArmLoadBalancerNatRuleCreateUpdate, Read: resourceArmLoadBalancerNatRuleRead, - Update: resourceArmLoadBalancerNatRuleCreate, + Update: resourceArmLoadBalancerNatRuleCreateUpdate, Delete: resourceArmLoadBalancerNatRuleDelete, + Importer: &schema.ResourceImporter{ State: loadBalancerSubResourceStateImporter, }, Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.NoZeroValues, }, "location": deprecatedLocationSchema(), @@ -34,16 +39,22 @@ func resourceArmLoadBalancerNatRule() *schema.Resource { "resource_group_name": resourceGroupNameSchema(), "loadbalancer_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: azure.ValidateResourceID, }, "protocol": { Type: schema.TypeString, Required: true, StateFunc: ignoreCaseStateFunc, - DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + DiffSuppressFunc: suppress.CaseDifference, + ValidateFunc: validation.StringInSlice([]string{ + string(network.TransportProtocolAll), + string(network.TransportProtocolTCP), + string(network.TransportProtocolUDP), + }, true), }, "enable_floating_ip": { @@ -53,18 +64,21 @@ func resourceArmLoadBalancerNatRule() *schema.Resource { }, "frontend_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validate.PortNumber, }, "backend_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validate.PortNumber, }, "frontend_ip_configuration_name": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.NoZeroValues, }, "frontend_ip_configuration_id": { @@ -80,7 +94,7 @@ func resourceArmLoadBalancerNatRule() *schema.Resource { } } -func resourceArmLoadBalancerNatRuleCreate(d *schema.ResourceData, meta interface{}) error { +func resourceArmLoadBalancerNatRuleCreateUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*ArmClient).loadBalancerClient ctx := meta.(*ArmClient).StopContext @@ -90,17 +104,17 @@ func resourceArmLoadBalancerNatRuleCreate(d *schema.ResourceData, meta interface loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta) if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err) + return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err) } if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string)) + log.Printf("[INFO] Load Balancer %q not found. Removing from state", d.Get("name").(string)) return nil } newNatRule, err := expandAzureRmLoadBalancerNatRule(d, loadBalancer) if err != nil { - return errwrap.Wrapf("Error Expanding NAT Rule {{err}}", err) + return fmt.Errorf("Error Expanding NAT Rule: %+v", err) } natRules := append(*loadBalancer.LoadBalancerPropertiesFormat.InboundNatRules, *newNatRule) @@ -108,7 +122,7 @@ func resourceArmLoadBalancerNatRuleCreate(d *schema.ResourceData, meta interface existingNatRule, existingNatRuleIndex, exists := findLoadBalancerNatRuleByName(loadBalancer, d.Get("name").(string)) if exists { if d.Get("name").(string) == *existingNatRule.Name { - // this probe is being updated/reapplied remove old copy from the slice + // this nat rule is being updated/reapplied remove old copy from the slice natRules = append(natRules[:existingNatRuleIndex], natRules[existingNatRuleIndex+1:]...) } } @@ -116,12 +130,12 @@ func resourceArmLoadBalancerNatRuleCreate(d *schema.ResourceData, meta interface loadBalancer.LoadBalancerPropertiesFormat.InboundNatRules = &natRules resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string)) if err != nil { - return fmt.Errorf("Error Getting LoadBalancer Name and Group: %+v", err) + return fmt.Errorf("Error Getting Load Balancer Name and Group: %+v", err) } future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer) if err != nil { - return fmt.Errorf("Error Creating / Updating LoadBalancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error Creating / Updating Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) } err = future.WaitForCompletionRef(ctx, client.Client) @@ -131,11 +145,11 @@ func resourceArmLoadBalancerNatRuleCreate(d *schema.ResourceData, meta interface read, err := client.Get(ctx, resGroup, loadBalancerName, "") if err != nil { - return fmt.Errorf("Error retrieving LoadBalancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error retrieving Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) } if read.ID == nil { - return fmt.Errorf("Cannot read LoadBalancer %q (Resource Group %q) ID", loadBalancerName, resGroup) + return fmt.Errorf("Cannot read Load Balancer %q (Resource Group %q) ID", loadBalancerName, resGroup) } var natRuleId string @@ -148,11 +162,11 @@ func resourceArmLoadBalancerNatRuleCreate(d *schema.ResourceData, meta interface if natRuleId != "" { d.SetId(natRuleId) } else { - return fmt.Errorf("Cannot find created LoadBalancer NAT Rule ID %q", natRuleId) + return fmt.Errorf("Cannot find created Load Balancer NAT Rule ID %q", natRuleId) } // TODO: is this still needed? - log.Printf("[DEBUG] Waiting for LoadBalancer (%s) to become available", loadBalancerName) + log.Printf("[DEBUG] Waiting for Load Balancer (%s) to become available", loadBalancerName) stateConf := &resource.StateChangeConf{ Pending: []string{"Accepted", "Updating"}, Target: []string{"Succeeded"}, @@ -160,7 +174,7 @@ func resourceArmLoadBalancerNatRuleCreate(d *schema.ResourceData, meta interface Timeout: 10 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for LoadBalancer (%s) to become available: %s", loadBalancerName, err) + return fmt.Errorf("Error waiting for Load Balancer (%s) to become available: %s", loadBalancerName, err) } return resourceArmLoadBalancerNatRuleRead(d, meta) @@ -175,18 +189,18 @@ func resourceArmLoadBalancerNatRuleRead(d *schema.ResourceData, meta interface{} loadBalancer, exists, err := retrieveLoadBalancerById(d.Get("loadbalancer_id").(string), meta) if err != nil { - return fmt.Errorf("Error Getting LoadBalancer By ID: %+v", err) + return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err) } if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer %q not found. Removing from state", name) + log.Printf("[INFO] Load Balancer %q not found. Removing from state", name) return nil } config, _, exists := findLoadBalancerNatRuleByName(loadBalancer, name) if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer Nat Rule %q not found. Removing from state", name) + log.Printf("[INFO] Load Balancer Nat Rule %q not found. Removing from state", name) return nil } @@ -227,7 +241,7 @@ func resourceArmLoadBalancerNatRuleDelete(d *schema.ResourceData, meta interface loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta) if err != nil { - return fmt.Errorf("Error Getting LoadBalancer By ID: %+v", err) + return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err) } if !exists { d.SetId("") @@ -245,25 +259,25 @@ func resourceArmLoadBalancerNatRuleDelete(d *schema.ResourceData, meta interface resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string)) if err != nil { - return fmt.Errorf("Error Getting LoadBalancer Name and Group: %+v", err) + return fmt.Errorf("Error Getting Load Balancer Name and Group: %+v", err) } future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer) if err != nil { - return fmt.Errorf("Error Creating/Updating LoadBalancer %q (Resource Group %q) %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error Creating/Updating Load Balancer %q (Resource Group %q) %+v", loadBalancerName, resGroup, err) } err = future.WaitForCompletionRef(ctx, client.Client) if err != nil { - return fmt.Errorf("Error waiting for the completion of LoadBalancer updates for %q (Resource Group %q) %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error waiting for the completion of Load Balancer updates for %q (Resource Group %q) %+v", loadBalancerName, resGroup, err) } read, err := client.Get(ctx, resGroup, loadBalancerName, "") if err != nil { - return fmt.Errorf("Error retrieving LoadBalancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error retrieving Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) } if read.ID == nil { - return fmt.Errorf("Cannot read LoadBalancer %q (resource group %q) ID", loadBalancerName, resGroup) + return fmt.Errorf("Cannot read Load Balancer %q (resource group %q) ID", loadBalancerName, resGroup) } return nil @@ -278,8 +292,7 @@ func expandAzureRmLoadBalancerNatRule(d *schema.ResourceData, lb *network.LoadBa } if v, ok := d.GetOk("enable_floating_ip"); ok { - enableFloatingIP := v.(bool) - properties.EnableFloatingIP = utils.Bool(enableFloatingIP) + properties.EnableFloatingIP = utils.Bool(v.(bool)) } if v := d.Get("frontend_ip_configuration_name").(string); v != "" { @@ -288,11 +301,9 @@ func expandAzureRmLoadBalancerNatRule(d *schema.ResourceData, lb *network.LoadBa return nil, fmt.Errorf("[ERROR] Cannot find FrontEnd IP Configuration with the name %s", v) } - feip := network.SubResource{ + properties.FrontendIPConfiguration = &network.SubResource{ ID: rule.ID, } - - properties.FrontendIPConfiguration = &feip } natRule := network.InboundNatRule{ diff --git a/azurerm/resource_arm_loadbalancer_nat_rule_test.go b/azurerm/resource_arm_loadbalancer_nat_rule_test.go index 130d7896e53cc..8fd2fd29af1fc 100644 --- a/azurerm/resource_arm_loadbalancer_nat_rule_test.go +++ b/azurerm/resource_arm_loadbalancer_nat_rule_test.go @@ -260,12 +260,12 @@ func testCheckAzureRMLoadBalancerNatRuleDisappears(natRuleName string, lb *netwo future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, *lb.Name, *lb) if err != nil { - return fmt.Errorf("Error Creating/Updating LoadBalancer %+v", err) + return fmt.Errorf("Error Creating/Updating Load Balancer %+v", err) } err = future.WaitForCompletionRef(ctx, client.Client) if err != nil { - return fmt.Errorf("Error waiting for the completion of LoadBalancer %q (Resource Group %q): %+v", *lb.Name, id.ResourceGroup, err) + return fmt.Errorf("Error waiting for the completion of Load Balancer %q (Resource Group %q): %+v", *lb.Name, id.ResourceGroup, err) } _, err = client.Get(ctx, id.ResourceGroup, *lb.Name, "") diff --git a/azurerm/resource_arm_loadbalancer_probe.go b/azurerm/resource_arm_loadbalancer_probe.go index 3fd6a66d6cbf7..64be089c446e3 100644 --- a/azurerm/resource_arm_loadbalancer_probe.go +++ b/azurerm/resource_arm_loadbalancer_probe.go @@ -6,17 +6,20 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network" - "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) func resourceArmLoadBalancerProbe() *schema.Resource { return &schema.Resource{ - Create: resourceArmLoadBalancerProbeCreate, + Create: resourceArmLoadBalancerProbeCreateUpdate, Read: resourceArmLoadBalancerProbeRead, - Update: resourceArmLoadBalancerProbeCreate, + Update: resourceArmLoadBalancerProbeCreateUpdate, Delete: resourceArmLoadBalancerProbeDelete, Importer: &schema.ResourceImporter{ State: loadBalancerSubResourceStateImporter, @@ -24,9 +27,10 @@ func resourceArmLoadBalancerProbe() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.NoZeroValues, }, "location": deprecatedLocationSchema(), @@ -34,9 +38,10 @@ func resourceArmLoadBalancerProbe() *schema.Resource { "resource_group_name": resourceGroupNameSchema(), "loadbalancer_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: azure.ValidateResourceID, }, "protocol": { @@ -44,12 +49,18 @@ func resourceArmLoadBalancerProbe() *schema.Resource { Computed: true, Optional: true, StateFunc: ignoreCaseStateFunc, - DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + DiffSuppressFunc: suppress.CaseDifference, + ValidateFunc: validation.StringInSlice([]string{ + string(network.ProbeProtocolHTTP), + string(network.ProbeProtocolHTTPS), + string(network.ProbeProtocolTCP), + }, true), }, "port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validate.PortNumber, }, "request_path": { @@ -58,9 +69,10 @@ func resourceArmLoadBalancerProbe() *schema.Resource { }, "interval_in_seconds": { - Type: schema.TypeInt, - Optional: true, - Default: 15, + Type: schema.TypeInt, + Optional: true, + Default: 15, + ValidateFunc: validation.IntAtLeast(5), }, "number_of_probes": { @@ -72,14 +84,17 @@ func resourceArmLoadBalancerProbe() *schema.Resource { "load_balancer_rules": { Type: schema.TypeSet, Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.NoZeroValues, + }, + Set: schema.HashString, }, }, } } -func resourceArmLoadBalancerProbeCreate(d *schema.ResourceData, meta interface{}) error { +func resourceArmLoadBalancerProbeCreateUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*ArmClient).loadBalancerClient ctx := meta.(*ArmClient).StopContext @@ -89,19 +104,15 @@ func resourceArmLoadBalancerProbeCreate(d *schema.ResourceData, meta interface{} loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta) if err != nil { - return fmt.Errorf("Error Getting LoadBalancer By ID: %+v", err) + return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err) } if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string)) + log.Printf("[INFO] Load Balancer %q not found. Removing from state", d.Get("name").(string)) return nil } - newProbe, err := expandAzureRmLoadBalancerProbe(d, loadBalancer) - if err != nil { - return fmt.Errorf("Error Expanding Probe: %+v", err) - } - + newProbe := expandAzureRmLoadBalancerProbe(d) probes := append(*loadBalancer.LoadBalancerPropertiesFormat.Probes, *newProbe) existingProbe, existingProbeIndex, exists := findLoadBalancerProbeByName(loadBalancer, d.Get("name").(string)) @@ -115,7 +126,7 @@ func resourceArmLoadBalancerProbeCreate(d *schema.ResourceData, meta interface{} loadBalancer.LoadBalancerPropertiesFormat.Probes = &probes resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string)) if err != nil { - return fmt.Errorf("Error Getting LoadBalancer Name and Group: %+v", err) + return fmt.Errorf("Error Getting Load Balancer Name and Group: %+v", err) } future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer) @@ -133,7 +144,7 @@ func resourceArmLoadBalancerProbeCreate(d *schema.ResourceData, meta interface{} return fmt.Errorf("Error retrieving Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) } if read.ID == nil { - return fmt.Errorf("Cannot read LoadBalancer %q (resource group %q) ID", loadBalancerName, resGroup) + return fmt.Errorf("Cannot read Load Balancer %q (resource group %q) ID", loadBalancerName, resGroup) } var createdProbeId string @@ -144,12 +155,12 @@ func resourceArmLoadBalancerProbeCreate(d *schema.ResourceData, meta interface{} } if createdProbeId == "" { - return fmt.Errorf("Cannot find created LoadBalancer Probe ID %q", createdProbeId) + return fmt.Errorf("Cannot find created Load Balancer Probe ID %q", createdProbeId) } d.SetId(createdProbeId) - log.Printf("[DEBUG] Waiting for LoadBalancer (%s) to become available", loadBalancerName) + log.Printf("[DEBUG] Waiting for Load Balancer (%s) to become available", loadBalancerName) stateConf := &resource.StateChangeConf{ Pending: []string{"Accepted", "Updating"}, Target: []string{"Succeeded"}, @@ -157,7 +168,7 @@ func resourceArmLoadBalancerProbeCreate(d *schema.ResourceData, meta interface{} Timeout: 10 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for LoadBalancer (%q - Resource Group %q) to become available: %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error waiting for Load Balancer (%q - Resource Group %q) to become available: %+v", loadBalancerName, resGroup, err) } return resourceArmLoadBalancerProbeRead(d, meta) @@ -172,36 +183,43 @@ func resourceArmLoadBalancerProbeRead(d *schema.ResourceData, meta interface{}) loadBalancer, exists, err := retrieveLoadBalancerById(d.Get("loadbalancer_id").(string), meta) if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err) + return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err) } if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer %q not found. Removing from state", name) + log.Printf("[INFO] Load Balancer %q not found. Removing from state", name) return nil } config, _, exists := findLoadBalancerProbeByName(loadBalancer, name) if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer Probe %q not found. Removing from state", name) + log.Printf("[INFO] Load Balancer Probe %q not found. Removing from state", name) return nil } d.Set("name", config.Name) d.Set("resource_group_name", id.ResourceGroup) - d.Set("protocol", config.ProbePropertiesFormat.Protocol) - d.Set("interval_in_seconds", config.ProbePropertiesFormat.IntervalInSeconds) - d.Set("number_of_probes", config.ProbePropertiesFormat.NumberOfProbes) - d.Set("port", config.ProbePropertiesFormat.Port) - d.Set("request_path", config.ProbePropertiesFormat.RequestPath) - - var load_balancer_rules []string - if config.ProbePropertiesFormat.LoadBalancingRules != nil { - for _, ruleConfig := range *config.ProbePropertiesFormat.LoadBalancingRules { - load_balancer_rules = append(load_balancer_rules, *ruleConfig.ID) + + if properties := config.ProbePropertiesFormat; properties != nil { + d.Set("protocol", properties.Protocol) + d.Set("interval_in_seconds", properties.IntervalInSeconds) + d.Set("number_of_probes", properties.NumberOfProbes) + d.Set("port", properties.Port) + d.Set("request_path", properties.RequestPath) + + var load_balancer_rules []string + if rules := properties.LoadBalancingRules; rules != nil { + for _, ruleConfig := range *rules { + if id := ruleConfig.ID; id != nil { + load_balancer_rules = append(load_balancer_rules, *id) + } + } + } + if err := d.Set("load_balancer_rules", load_balancer_rules); err != nil { + return fmt.Errorf("Error setting `load_balancer_rules` (Load Balancer Probe %q): %+v", name, err) } } - d.Set("load_balancer_rules", load_balancer_rules) return nil } @@ -216,7 +234,7 @@ func resourceArmLoadBalancerProbeDelete(d *schema.ResourceData, meta interface{} loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta) if err != nil { - return fmt.Errorf("Error Getting LoadBalancer By ID: %+v", err) + return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err) } if !exists { d.SetId("") @@ -234,31 +252,31 @@ func resourceArmLoadBalancerProbeDelete(d *schema.ResourceData, meta interface{} resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string)) if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err) + return fmt.Errorf("Error Getting Load Balancer Name and Group:: %+v", err) } future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer) if err != nil { - return fmt.Errorf("Error Creating/Updating LoadBalancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error Creating/Updating Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) } err = future.WaitForCompletionRef(ctx, client.Client) if err != nil { - return fmt.Errorf("Error waiting for completion of LoadBalancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error waiting for completion of Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) } read, err := client.Get(ctx, resGroup, loadBalancerName, "") if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err) + return fmt.Errorf("Error Getting LoadBalancer: %+v", err) } if read.ID == nil { - return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup) + return fmt.Errorf("Cannot read Load Balancer %s (resource group %s) ID", loadBalancerName, resGroup) } return nil } -func expandAzureRmLoadBalancerProbe(d *schema.ResourceData, lb *network.LoadBalancer) (*network.Probe, error) { +func expandAzureRmLoadBalancerProbe(d *schema.ResourceData) *network.Probe { properties := network.ProbePropertiesFormat{ NumberOfProbes: utils.Int32(int32(d.Get("number_of_probes").(int))), @@ -274,10 +292,8 @@ func expandAzureRmLoadBalancerProbe(d *schema.ResourceData, lb *network.LoadBala properties.RequestPath = utils.String(v.(string)) } - probe := network.Probe{ + return &network.Probe{ Name: utils.String(d.Get("name").(string)), ProbePropertiesFormat: &properties, } - - return &probe, nil } diff --git a/azurerm/resource_arm_loadbalancer_probe_test.go b/azurerm/resource_arm_loadbalancer_probe_test.go index 557df04a0e137..867a4dc4d8258 100644 --- a/azurerm/resource_arm_loadbalancer_probe_test.go +++ b/azurerm/resource_arm_loadbalancer_probe_test.go @@ -17,7 +17,7 @@ func TestAccAzureRMLoadBalancerProbe_basic(t *testing.T) { probeName := fmt.Sprintf("probe-%d", ri) subscriptionID := os.Getenv("ARM_SUBSCRIPTION_ID") - probe_id := fmt.Sprintf( + probeId := fmt.Sprintf( "/subscriptions/%s/resourceGroups/acctestRG-%d/providers/Microsoft.Network/loadBalancers/arm-test-loadbalancer-%d/probes/%s", subscriptionID, ri, ri, probeName) @@ -32,7 +32,7 @@ func TestAccAzureRMLoadBalancerProbe_basic(t *testing.T) { testCheckAzureRMLoadBalancerExists("azurerm_lb.test", &lb), testCheckAzureRMLoadBalancerProbeExists(probeName, &lb), resource.TestCheckResourceAttr( - "azurerm_lb_probe.test", "id", probe_id), + "azurerm_lb_probe.test", "id", probeId), ), }, }, @@ -68,7 +68,7 @@ func TestAccAzureRMLoadBalancerProbe_removal(t *testing.T) { }) } -func TestAccAzureRMLoadBalancerProbe_update(t *testing.T) { +func maProbe_update(t *testing.T) { var lb network.LoadBalancer ri := acctest.RandInt() probeName := fmt.Sprintf("probe-%d", ri) diff --git a/azurerm/resource_arm_loadbalancer_rule.go b/azurerm/resource_arm_loadbalancer_rule.go index e28add430bd5a..44ca3c0b33226 100644 --- a/azurerm/resource_arm_loadbalancer_rule.go +++ b/azurerm/resource_arm_loadbalancer_rule.go @@ -7,9 +7,12 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network" - "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -19,6 +22,7 @@ func resourceArmLoadBalancerRule() *schema.Resource { Read: resourceArmLoadBalancerRuleRead, Update: resourceArmLoadBalancerRuleCreate, Delete: resourceArmLoadBalancerRuleDelete, + Importer: &schema.ResourceImporter{ State: loadBalancerSubResourceStateImporter, }, @@ -36,14 +40,16 @@ func resourceArmLoadBalancerRule() *schema.Resource { "resource_group_name": resourceGroupNameSchema(), "loadbalancer_id": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: azure.ValidateResourceID, }, "frontend_ip_configuration_name": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.NoZeroValues, }, "frontend_ip_configuration_id": { @@ -61,17 +67,24 @@ func resourceArmLoadBalancerRule() *schema.Resource { Type: schema.TypeString, Required: true, StateFunc: ignoreCaseStateFunc, - DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + DiffSuppressFunc: suppress.CaseDifference, + ValidateFunc: validation.StringInSlice([]string{ + string(network.TransportProtocolAll), + string(network.TransportProtocolTCP), + string(network.TransportProtocolUDP), + }, true), }, "frontend_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validate.PortNumber, }, "backend_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validate.PortNumber, }, "probe_id": { @@ -87,9 +100,10 @@ func resourceArmLoadBalancerRule() *schema.Resource { }, "idle_timeout_in_minutes": { - Type: schema.TypeInt, - Optional: true, - Computed: true, + Type: schema.TypeInt, + Optional: true, + Computed: true, + ValidateFunc: validation.IntBetween(4, 30), }, "load_distribution": { @@ -111,17 +125,17 @@ func resourceArmLoadBalancerRuleCreate(d *schema.ResourceData, meta interface{}) loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta) if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err) + return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err) } if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer %q not found. Removing from state", d.Get("name").(string)) + log.Printf("[INFO] Load Balancer %q not found. Removing from state", d.Get("name").(string)) return nil } newLbRule, err := expandAzureRmLoadBalancerRule(d, loadBalancer) if err != nil { - return errwrap.Wrapf("Error Exanding LoadBalancer Rule {{err}}", err) + return fmt.Errorf("Error Exanding Load Balancer Rule: %+v", err) } lbRules := append(*loadBalancer.LoadBalancerPropertiesFormat.LoadBalancingRules, *newLbRule) @@ -137,25 +151,25 @@ func resourceArmLoadBalancerRuleCreate(d *schema.ResourceData, meta interface{}) loadBalancer.LoadBalancerPropertiesFormat.LoadBalancingRules = &lbRules resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string)) if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err) + return fmt.Errorf("Error Getting Load Balancer Name and Group:: %+v", err) } future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer) if err != nil { - return errwrap.Wrapf("Error Creating/Updating LoadBalancer {{err}}", err) + return fmt.Errorf("Error Creating/Updating LoadBalancer: %+v", err) } err = future.WaitForCompletionRef(ctx, client.Client) if err != nil { - return fmt.Errorf("Error waiting for completion for LoadBalancer updates: %+v", err) + return fmt.Errorf("Error waiting for completion for Load Balancer updates: %+v", err) } read, err := client.Get(ctx, resGroup, loadBalancerName, "") if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err) + return fmt.Errorf("Error Getting LoadBalancer: %+v", err) } if read.ID == nil { - return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", loadBalancerName, resGroup) + return fmt.Errorf("Cannot read Load Balancer %s (resource group %s) ID", loadBalancerName, resGroup) } var ruleId string @@ -166,12 +180,12 @@ func resourceArmLoadBalancerRuleCreate(d *schema.ResourceData, meta interface{}) } if ruleId == "" { - return fmt.Errorf("Cannot find created LoadBalancer Rule ID %q", ruleId) + return fmt.Errorf("Cannot find created Load Balancer Rule ID %q", ruleId) } d.SetId(ruleId) - log.Printf("[DEBUG] Waiting for LoadBalancer (%s) to become available", loadBalancerName) + log.Printf("[DEBUG] Waiting for Load Balancer (%s) to become available", loadBalancerName) stateConf := &resource.StateChangeConf{ Pending: []string{"Accepted", "Updating"}, Target: []string{"Succeeded"}, @@ -179,7 +193,7 @@ func resourceArmLoadBalancerRuleCreate(d *schema.ResourceData, meta interface{}) Timeout: 10 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for LoadBalancer (%s) to become available: %s", loadBalancerName, err) + return fmt.Errorf("Error waiting for Load Balancer (%s) to become available: %s", loadBalancerName, err) } return resourceArmLoadBalancerRuleRead(d, meta) @@ -194,56 +208,58 @@ func resourceArmLoadBalancerRuleRead(d *schema.ResourceData, meta interface{}) e loadBalancer, exists, err := retrieveLoadBalancerById(d.Get("loadbalancer_id").(string), meta) if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err) + return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err) } if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer %q not found. Removing from state", name) + log.Printf("[INFO] Load Balancer %q not found. Removing from state", name) return nil } config, _, exists := findLoadBalancerRuleByName(loadBalancer, name) if !exists { d.SetId("") - log.Printf("[INFO] LoadBalancer Rule %q not found. Removing from state", name) + log.Printf("[INFO] Load Balancer Rule %q not found. Removing from state", name) return nil } d.Set("name", config.Name) d.Set("resource_group_name", id.ResourceGroup) - d.Set("protocol", config.LoadBalancingRulePropertiesFormat.Protocol) - d.Set("frontend_port", config.LoadBalancingRulePropertiesFormat.FrontendPort) - d.Set("backend_port", config.LoadBalancingRulePropertiesFormat.BackendPort) + if properties := config.LoadBalancingRulePropertiesFormat; properties != nil { + d.Set("protocol", properties.Protocol) + d.Set("frontend_port", properties.FrontendPort) + d.Set("backend_port", properties.BackendPort) - if config.LoadBalancingRulePropertiesFormat.EnableFloatingIP != nil { - d.Set("enable_floating_ip", config.LoadBalancingRulePropertiesFormat.EnableFloatingIP) - } - - if config.LoadBalancingRulePropertiesFormat.IdleTimeoutInMinutes != nil { - d.Set("idle_timeout_in_minutes", config.LoadBalancingRulePropertiesFormat.IdleTimeoutInMinutes) - } + if properties.EnableFloatingIP != nil { + d.Set("enable_floating_ip", properties.EnableFloatingIP) + } - if config.LoadBalancingRulePropertiesFormat.FrontendIPConfiguration != nil { - fipID, err := parseAzureResourceID(*config.LoadBalancingRulePropertiesFormat.FrontendIPConfiguration.ID) - if err != nil { - return err + if properties.IdleTimeoutInMinutes != nil { + d.Set("idle_timeout_in_minutes", properties.IdleTimeoutInMinutes) } - d.Set("frontend_ip_configuration_name", fipID.Path["frontendIPConfigurations"]) - d.Set("frontend_ip_configuration_id", config.LoadBalancingRulePropertiesFormat.FrontendIPConfiguration.ID) - } + if properties.FrontendIPConfiguration != nil { + fipID, err := parseAzureResourceID(*properties.FrontendIPConfiguration.ID) + if err != nil { + return err + } - if config.LoadBalancingRulePropertiesFormat.BackendAddressPool != nil { - d.Set("backend_address_pool_id", config.LoadBalancingRulePropertiesFormat.BackendAddressPool.ID) - } + d.Set("frontend_ip_configuration_name", fipID.Path["frontendIPConfigurations"]) + d.Set("frontend_ip_configuration_id", properties.FrontendIPConfiguration.ID) + } - if config.LoadBalancingRulePropertiesFormat.Probe != nil { - d.Set("probe_id", config.LoadBalancingRulePropertiesFormat.Probe.ID) - } + if properties.BackendAddressPool != nil { + d.Set("backend_address_pool_id", properties.BackendAddressPool.ID) + } + + if properties.Probe != nil { + d.Set("probe_id", properties.Probe.ID) + } - if config.LoadBalancingRulePropertiesFormat.LoadDistribution != "" { - d.Set("load_distribution", config.LoadBalancingRulePropertiesFormat.LoadDistribution) + if properties.LoadDistribution != "" { + d.Set("load_distribution", properties.LoadDistribution) + } } return nil @@ -259,7 +275,7 @@ func resourceArmLoadBalancerRuleDelete(d *schema.ResourceData, meta interface{}) loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta) if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer By ID {{err}}", err) + return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err) } if !exists { d.SetId("") @@ -277,25 +293,25 @@ func resourceArmLoadBalancerRuleDelete(d *schema.ResourceData, meta interface{}) resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string)) if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer Name and Group: {{err}}", err) + return fmt.Errorf("Error Getting Load Balancer Name and Group:: %+v", err) } future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer) if err != nil { - return fmt.Errorf("Error Creating/Updating LoadBalancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error Creating/Updating Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) } err = future.WaitForCompletionRef(ctx, client.Client) if err != nil { - return fmt.Errorf("Error waiting for completion of LoadBalancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) + return fmt.Errorf("Error waiting for completion of Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err) } read, err := client.Get(ctx, resGroup, loadBalancerName, "") if err != nil { - return errwrap.Wrapf("Error Getting LoadBalancer {{err}}", err) + return fmt.Errorf("Error Getting LoadBalancer: %+v", err) } if read.ID == nil { - return fmt.Errorf("Cannot read ID of LoadBalancer %q (resource group %s)", loadBalancerName, resGroup) + return fmt.Errorf("Cannot read ID of Load Balancer %q (resource group %s)", loadBalancerName, resGroup) } return nil @@ -324,35 +340,27 @@ func expandAzureRmLoadBalancerRule(d *schema.ResourceData, lb *network.LoadBalan return nil, fmt.Errorf("[ERROR] Cannot find FrontEnd IP Configuration with the name %s", v) } - feip := network.SubResource{ + properties.FrontendIPConfiguration = &network.SubResource{ ID: rule.ID, } - - properties.FrontendIPConfiguration = &feip } if v := d.Get("backend_address_pool_id").(string); v != "" { - beAP := network.SubResource{ + properties.BackendAddressPool = &network.SubResource{ ID: &v, } - - properties.BackendAddressPool = &beAP } if v := d.Get("probe_id").(string); v != "" { - pid := network.SubResource{ + properties.Probe = &network.SubResource{ ID: &v, } - - properties.Probe = &pid } - lbRule := network.LoadBalancingRule{ + return &network.LoadBalancingRule{ Name: utils.String(d.Get("name").(string)), LoadBalancingRulePropertiesFormat: &properties, - } - - return &lbRule, nil + }, nil } func validateArmLoadBalancerRuleName(v interface{}, k string) (ws []string, errors []error) { diff --git a/azurerm/resource_arm_loadbalancer_rule_test.go b/azurerm/resource_arm_loadbalancer_rule_test.go index e1ec17148b050..657d001f74a3f 100644 --- a/azurerm/resource_arm_loadbalancer_rule_test.go +++ b/azurerm/resource_arm_loadbalancer_rule_test.go @@ -62,7 +62,7 @@ func TestResourceAzureRMLoadBalancerRuleNameLabel_validation(t *testing.T) { _, errors := validateArmLoadBalancerRuleName(tc.Value, "azurerm_lb_rule") if len(errors) != tc.ErrCount { - t.Fatalf("Expected the Azure RM LoadBalancer Rule Name Label to trigger a validation error") + t.Fatalf("Expected the Azure RM Load Balancer Rule Name Label to trigger a validation error") } } } @@ -258,7 +258,7 @@ func testCheckAzureRMLoadBalancerRuleExists(lbRuleName string, lb *network.LoadB return func(s *terraform.State) error { _, _, exists := findLoadBalancerRuleByName(lb, lbRuleName) if !exists { - return fmt.Errorf("A LoadBalancer Rule with name %q cannot be found.", lbRuleName) + return fmt.Errorf("A Load Balancer Rule with name %q cannot be found.", lbRuleName) } return nil @@ -269,7 +269,7 @@ func testCheckAzureRMLoadBalancerRuleNotExists(lbRuleName string, lb *network.Lo return func(s *terraform.State) error { _, _, exists := findLoadBalancerRuleByName(lb, lbRuleName) if exists { - return fmt.Errorf("A LoadBalancer Rule with name %q has been found.", lbRuleName) + return fmt.Errorf("A Load Balancer Rule with name %q has been found.", lbRuleName) } return nil @@ -297,12 +297,12 @@ func testCheckAzureRMLoadBalancerRuleDisappears(ruleName string, lb *network.Loa future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, *lb.Name, *lb) if err != nil { - return fmt.Errorf("Error Creating/Updating LoadBalancer %q (Resource Group %q): %+v", lb.Name, id.ResourceGroup, err) + return fmt.Errorf("Error Creating/Updating Load Balancer %q (Resource Group %q): %+v", *lb.Name, id.ResourceGroup, err) } err = future.WaitForCompletionRef(ctx, client.Client) if err != nil { - return fmt.Errorf("Error waiting for completion of LoadBalancer %q (Resource Group %q): %+v", lb.Name, id.ResourceGroup, err) + return fmt.Errorf("Error waiting for completion of Load Balancer %q (Resource Group %q): %+v", *lb.Name, id.ResourceGroup, err) } _, err = client.Get(ctx, id.ResourceGroup, *lb.Name, "") diff --git a/azurerm/resource_arm_loadbalancer_test.go b/azurerm/resource_arm_loadbalancer_test.go index 1eb780dcf834a..82ad66863764f 100644 --- a/azurerm/resource_arm_loadbalancer_test.go +++ b/azurerm/resource_arm_loadbalancer_test.go @@ -42,7 +42,7 @@ func TestResourceAzureRMLoadBalancerPrivateIpAddressAllocation_validation(t *tes _, errors := validateLoadBalancerPrivateIpAddressAllocation(tc.Value, "azurerm_lb") if len(errors) != tc.ErrCount { - t.Fatalf("Expected the Azure RM LoadBalancer private_ip_address_allocation to trigger a validation error") + t.Fatalf("Expected the Azure RM Load Balancer private_ip_address_allocation to trigger a validation error") } } } @@ -193,7 +193,7 @@ func testCheckAzureRMLoadBalancerExists(name string, lb *network.LoadBalancer) r resp, err := client.Get(ctx, resourceGroup, loadBalancerName, "") if err != nil { if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: LoadBalancer %q (resource group: %q) does not exist", loadBalancerName, resourceGroup) + return fmt.Errorf("Bad: Load Balancer %q (resource group: %q) does not exist", loadBalancerName, resourceGroup) } return fmt.Errorf("Bad: Get on loadBalancerClient: %+v", err) diff --git a/azurerm/resource_arm_monitor_action_group.go b/azurerm/resource_arm_monitor_action_group.go new file mode 100644 index 0000000000000..4abbcd7ca4bca --- /dev/null +++ b/azurerm/resource_arm_monitor_action_group.go @@ -0,0 +1,317 @@ +package azurerm + +import ( + "fmt" + + "github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2018-03-01/insights" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmMonitorActionGroup() *schema.Resource { + return &schema.Resource{ + Create: resourceArmMonitorActionGroupCreateOrUpdate, + Read: resourceArmMonitorActionGroupRead, + Update: resourceArmMonitorActionGroupCreateOrUpdate, + Delete: resourceArmMonitorActionGroupDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.NoZeroValues, + }, + + "resource_group_name": resourceGroupNameSchema(), + + "short_name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 12), + }, + + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + + "email_receiver": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.NoZeroValues, + }, + "email_address": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.NoZeroValues, + }, + }, + }, + }, + + "sms_receiver": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.NoZeroValues, + }, + "country_code": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.NoZeroValues, + }, + "phone_number": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.NoZeroValues, + }, + }, + }, + }, + + "webhook_receiver": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.NoZeroValues, + }, + "service_uri": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.NoZeroValues, + }, + }, + }, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmMonitorActionGroupCreateOrUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).actionGroupsClient + ctx := meta.(*ArmClient).StopContext + + name := d.Get("name").(string) + resGroup := d.Get("resource_group_name").(string) + + shortName := d.Get("short_name").(string) + enabled := d.Get("enabled").(bool) + + emailReceiversRaw := d.Get("email_receiver").([]interface{}) + smsReceiversRaw := d.Get("sms_receiver").([]interface{}) + webhookReceiversRaw := d.Get("webhook_receiver").([]interface{}) + + tags := d.Get("tags").(map[string]interface{}) + expandedTags := expandTags(tags) + + parameters := insights.ActionGroupResource{ + Location: utils.String(azureRMNormalizeLocation("Global")), + ActionGroup: &insights.ActionGroup{ + GroupShortName: utils.String(shortName), + Enabled: utils.Bool(enabled), + EmailReceivers: expandMonitorActionGroupEmailReceiver(emailReceiversRaw), + SmsReceivers: expandMonitorActionGroupSmsReceiver(smsReceiversRaw), + WebhookReceivers: expandMonitorActionGroupWebHookReceiver(webhookReceiversRaw), + }, + Tags: expandedTags, + } + + _, err := client.CreateOrUpdate(ctx, resGroup, name, parameters) + if err != nil { + return fmt.Errorf("Error creating or updating action group %q (resource group %q): %+v", name, resGroup, err) + } + + read, err := client.Get(ctx, resGroup, name) + if err != nil { + return fmt.Errorf("Error getting action group %q (resource group %q) after creation: %+v", name, resGroup, err) + } + if read.ID == nil { + return fmt.Errorf("Action group %q (resource group %q) ID is empty", name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmMonitorActionGroupRead(d, meta) +} + +func resourceArmMonitorActionGroupRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).actionGroupsClient + ctx := meta.(*ArmClient).StopContext + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["actionGroups"] + + resp, err := client.Get(ctx, resGroup, name) + if err != nil { + if response.WasNotFound(resp.Response.Response) { + d.SetId("") + return nil + } + return fmt.Errorf("Error getting action group %q (resource group %q): %+v", name, resGroup, err) + } + + d.Set("name", name) + d.Set("resource_group_name", resGroup) + + if group := resp.ActionGroup; group != nil { + d.Set("short_name", group.GroupShortName) + d.Set("enabled", group.Enabled) + + if err = d.Set("email_receiver", flattenMonitorActionGroupEmailReceiver(group.EmailReceivers)); err != nil { + return fmt.Errorf("Error setting `email_receiver`: %+v", err) + } + + if err = d.Set("sms_receiver", flattenMonitorActionGroupSmsReceiver(group.SmsReceivers)); err != nil { + return fmt.Errorf("Error setting `sms_receiver`: %+v", err) + } + + if err = d.Set("webhook_receiver", flattenMonitorActionGroupWebHookReceiver(group.WebhookReceivers)); err != nil { + return fmt.Errorf("Error setting `webhook_receiver`: %+v", err) + } + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmMonitorActionGroupDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).actionGroupsClient + ctx := meta.(*ArmClient).StopContext + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["actionGroups"] + + resp, err := client.Delete(ctx, resGroup, name) + if err != nil { + if !response.WasNotFound(resp.Response) { + return fmt.Errorf("Error deleting action group %q (resource group %q): %+v", name, resGroup, err) + } + } + + return nil +} + +func expandMonitorActionGroupEmailReceiver(v []interface{}) *[]insights.EmailReceiver { + receivers := make([]insights.EmailReceiver, 0) + for _, receiverValue := range v { + val := receiverValue.(map[string]interface{}) + receiver := insights.EmailReceiver{ + Name: utils.String(val["name"].(string)), + EmailAddress: utils.String(val["email_address"].(string)), + } + receivers = append(receivers, receiver) + } + return &receivers +} + +func expandMonitorActionGroupSmsReceiver(v []interface{}) *[]insights.SmsReceiver { + receivers := make([]insights.SmsReceiver, 0) + for _, receiverValue := range v { + val := receiverValue.(map[string]interface{}) + receiver := insights.SmsReceiver{ + Name: utils.String(val["name"].(string)), + CountryCode: utils.String(val["country_code"].(string)), + PhoneNumber: utils.String(val["phone_number"].(string)), + } + receivers = append(receivers, receiver) + } + return &receivers +} + +func expandMonitorActionGroupWebHookReceiver(v []interface{}) *[]insights.WebhookReceiver { + receivers := make([]insights.WebhookReceiver, 0) + for _, receiverValue := range v { + val := receiverValue.(map[string]interface{}) + receiver := insights.WebhookReceiver{ + Name: utils.String(val["name"].(string)), + ServiceURI: utils.String(val["service_uri"].(string)), + } + receivers = append(receivers, receiver) + } + return &receivers +} + +func flattenMonitorActionGroupEmailReceiver(receivers *[]insights.EmailReceiver) []interface{} { + result := make([]interface{}, 0) + if receivers != nil { + for _, receiver := range *receivers { + val := make(map[string]interface{}, 0) + if receiver.Name != nil { + val["name"] = *receiver.Name + } + if receiver.EmailAddress != nil { + val["email_address"] = *receiver.EmailAddress + } + result = append(result, val) + } + } + return result +} + +func flattenMonitorActionGroupSmsReceiver(receivers *[]insights.SmsReceiver) []interface{} { + result := make([]interface{}, 0) + if receivers != nil { + for _, receiver := range *receivers { + val := make(map[string]interface{}, 0) + if receiver.Name != nil { + val["name"] = *receiver.Name + } + if receiver.CountryCode != nil { + val["country_code"] = *receiver.CountryCode + } + if receiver.PhoneNumber != nil { + val["phone_number"] = *receiver.PhoneNumber + } + result = append(result, val) + } + } + return result +} + +func flattenMonitorActionGroupWebHookReceiver(receivers *[]insights.WebhookReceiver) []interface{} { + result := make([]interface{}, 0) + if receivers != nil { + for _, receiver := range *receivers { + val := make(map[string]interface{}, 0) + if receiver.Name != nil { + val["name"] = *receiver.Name + } + if receiver.ServiceURI != nil { + val["service_uri"] = *receiver.ServiceURI + } + result = append(result, val) + } + } + return result +} diff --git a/azurerm/resource_arm_monitor_action_group_test.go b/azurerm/resource_arm_monitor_action_group_test.go new file mode 100644 index 0000000000000..48e0a8a8fd139 --- /dev/null +++ b/azurerm/resource_arm_monitor_action_group_test.go @@ -0,0 +1,505 @@ +package azurerm + +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMMonitorActionGroup_basic(t *testing.T) { + resourceName := "azurerm_monitor_action_group.test" + ri := acctest.RandInt() + config := testAccAzureRMMonitorActionGroup_basic(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMMonitorActionGroupDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMMonitorActionGroup_emailReceiver(t *testing.T) { + resourceName := "azurerm_monitor_action_group.test" + ri := acctest.RandInt() + config := testAccAzureRMMonitorActionGroup_emailReceiver(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMMonitorActionGroupDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.#", "1"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.0.email_address", "admin@contoso.com"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMMonitorActionGroup_smsReceiver(t *testing.T) { + resourceName := "azurerm_monitor_action_group.test" + ri := acctest.RandInt() + config := testAccAzureRMMonitorActionGroup_smsReceiver(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMMonitorActionGroupDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.#", "1"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.0.country_code", "1"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.0.phone_number", "1231231234"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMMonitorActionGroup_webhookReceiver(t *testing.T) { + resourceName := "azurerm_monitor_action_group.test" + ri := acctest.RandInt() + config := testAccAzureRMMonitorActionGroup_webhookReceiver(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMMonitorActionGroupDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.#", "1"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.0.service_uri", "http://example.com/alert"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMMonitorActionGroup_complete(t *testing.T) { + resourceName := "azurerm_monitor_action_group.test" + ri := acctest.RandInt() + config := testAccAzureRMMonitorActionGroup_complete(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMMonitorActionGroupDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.#", "2"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.0.email_address", "admin@contoso.com"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.1.email_address", "devops@contoso.com"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.#", "2"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.0.country_code", "1"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.0.phone_number", "1231231234"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.1.country_code", "86"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.1.phone_number", "13888888888"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.#", "2"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.0.service_uri", "http://example.com/alert"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.1.service_uri", "https://backup.example.com/warning"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMMonitorActionGroup_disabledUpdate(t *testing.T) { + resourceName := "azurerm_monitor_action_group.test" + ri := acctest.RandInt() + location := testLocation() + preConfig := testAccAzureRMMonitorActionGroup_disabledBasic(ri, location) + postConfig := testAccAzureRMMonitorActionGroup_basic(ri, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMMonitorActionGroupDestroy, + Steps: []resource.TestStep{ + { + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "false"), + ), + }, + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + ), + }, + { + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "false"), + ), + }, + }, + }) +} + +func TestAccAzureRMMonitorActionGroup_singleReceiverUpdate(t *testing.T) { + resourceName := "azurerm_monitor_action_group.test" + ri := acctest.RandInt() + location := testLocation() + emailConfig := testAccAzureRMMonitorActionGroup_emailReceiver(ri, location) + smsConfig := testAccAzureRMMonitorActionGroup_smsReceiver(ri, location) + webhookConfig := testAccAzureRMMonitorActionGroup_webhookReceiver(ri, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMMonitorActionGroupDestroy, + Steps: []resource.TestStep{ + { + Config: emailConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.#", "1"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.0.email_address", "admin@contoso.com"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.#", "0"), + ), + }, + { + Config: smsConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.#", "1"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.0.country_code", "1"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.0.phone_number", "1231231234"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.#", "0"), + ), + }, + { + Config: webhookConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.#", "1"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.0.service_uri", "http://example.com/alert"), + ), + }, + }, + }) +} + +func TestAccAzureRMMonitorActionGroup_multipleReceiversUpdate(t *testing.T) { + resourceName := "azurerm_monitor_action_group.test" + ri := acctest.RandInt() + location := testLocation() + basicConfig := testAccAzureRMMonitorActionGroup_basic(ri, location) + completeConfig := testAccAzureRMMonitorActionGroup_complete(ri, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMMonitorActionGroupDestroy, + Steps: []resource.TestStep{ + { + Config: basicConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.#", "0"), + ), + }, + { + Config: completeConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.#", "2"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.0.email_address", "admin@contoso.com"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.1.email_address", "devops@contoso.com"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.#", "2"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.0.country_code", "1"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.0.phone_number", "1231231234"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.1.country_code", "86"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.1.phone_number", "13888888888"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.#", "2"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.0.service_uri", "http://example.com/alert"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.1.service_uri", "https://backup.example.com/warning"), + ), + }, + { + Config: basicConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMonitorActionGroupExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "email_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "sms_receiver.#", "0"), + resource.TestCheckResourceAttr(resourceName, "webhook_receiver.#", "0"), + ), + }, + }, + }) +} + +func testAccAzureRMMonitorActionGroup_basic(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_monitor_action_group" "test" { + name = "acctestActionGroup-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + short_name = "acctestag" +} +`, rInt, location, rInt) +} + +func testAccAzureRMMonitorActionGroup_emailReceiver(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_monitor_action_group" "test" { + name = "acctestActionGroup-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + short_name = "acctestag" + + email_receiver { + name = "sendtoadmin" + email_address = "admin@contoso.com" + } +} +`, rInt, location, rInt) +} + +func testAccAzureRMMonitorActionGroup_smsReceiver(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_monitor_action_group" "test" { + name = "acctestActionGroup-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + short_name = "acctestag" + + sms_receiver { + name = "oncallmsg" + country_code = "1" + phone_number = "1231231234" + } +} +`, rInt, location, rInt) +} + +func testAccAzureRMMonitorActionGroup_webhookReceiver(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_monitor_action_group" "test" { + name = "acctestActionGroup-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + short_name = "acctestag" + + webhook_receiver { + name = "callmyapiaswell" + service_uri = "http://example.com/alert" + } +} +`, rInt, location, rInt) +} + +func testAccAzureRMMonitorActionGroup_complete(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_monitor_action_group" "test" { + name = "acctestActionGroup-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + short_name = "acctestag" + + email_receiver { + name = "sendtoadmin" + email_address = "admin@contoso.com" + } + + email_receiver { + name = "sendtodevops" + email_address = "devops@contoso.com" + } + + sms_receiver { + name = "oncallmsg" + country_code = "1" + phone_number = "1231231234" + } + + sms_receiver { + name = "remotesupport" + country_code = "86" + phone_number = "13888888888" + } + + webhook_receiver { + name = "callmyapiaswell" + service_uri = "http://example.com/alert" + } + + webhook_receiver { + name = "callmybackupapi" + service_uri = "https://backup.example.com/warning" + } +} +`, rInt, location, rInt) +} + +func testAccAzureRMMonitorActionGroup_disabledBasic(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_monitor_action_group" "test" { + name = "acctestActionGroup-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + short_name = "acctestag" + enabled = false +} +`, rInt, location, rInt) +} + +func testCheckAzureRMMonitorActionGroupDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).actionGroupsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_monitor_action_group" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(ctx, resourceGroup, name) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Action Group still exists:\n%#v", resp) + } + } + + return nil +} + +func testCheckAzureRMMonitorActionGroupExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + // Ensure we have enough information in state to look up in API + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + resourceName := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for Action Group Instance: %s", resourceName) + } + + conn := testAccProvider.Meta().(*ArmClient).actionGroupsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + resp, err := conn.Get(ctx, resourceGroup, resourceName) + if err != nil { + return fmt.Errorf("Bad: Get on actionGroupsClient: %+v", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: Action Group Instance %q (resource group: %q) does not exist", resourceName, resourceGroup) + } + + return nil + } +} diff --git a/azurerm/resource_arm_redis_cache.go b/azurerm/resource_arm_redis_cache.go index 0a103f3801423..0b390950e5330 100644 --- a/azurerm/resource_arm_redis_cache.go +++ b/azurerm/resource_arm_redis_cache.go @@ -590,21 +590,21 @@ func flattenRedisConfiguration(input map[string]*string) ([]interface{}, error) if v := input["maxclients"]; v != nil { i, err := strconv.Atoi(*v) if err != nil { - return nil, fmt.Errorf("Error parsing `maxclients` %q: %+v", v, err) + return nil, fmt.Errorf("Error parsing `maxclients` %q: %+v", *v, err) } outputs["maxclients"] = i } if v := input["maxmemory-delta"]; v != nil { i, err := strconv.Atoi(*v) if err != nil { - return nil, fmt.Errorf("Error parsing `maxmemory-delta` %q: %+v", v, err) + return nil, fmt.Errorf("Error parsing `maxmemory-delta` %q: %+v", *v, err) } outputs["maxmemory_delta"] = i } if v := input["maxmemory-reserved"]; v != nil { i, err := strconv.Atoi(*v) if err != nil { - return nil, fmt.Errorf("Error parsing `maxmemory-reserved` %q: %+v", v, err) + return nil, fmt.Errorf("Error parsing `maxmemory-reserved` %q: %+v", *v, err) } outputs["maxmemory_reserved"] = i } @@ -616,21 +616,21 @@ func flattenRedisConfiguration(input map[string]*string) ([]interface{}, error) if v := input["rdb-backup-enabled"]; v != nil { b, err := strconv.ParseBool(*v) if err != nil { - return nil, fmt.Errorf("Error parsing `rdb-backup-enabled` %q: %+v", v, err) + return nil, fmt.Errorf("Error parsing `rdb-backup-enabled` %q: %+v", *v, err) } outputs["rdb_backup_enabled"] = b } if v := input["rdb-backup-frequency"]; v != nil { i, err := strconv.Atoi(*v) if err != nil { - return nil, fmt.Errorf("Error parsing `rdb-backup-frequency` %q: %+v", v, err) + return nil, fmt.Errorf("Error parsing `rdb-backup-frequency` %q: %+v", *v, err) } outputs["rdb_backup_frequency"] = i } if v := input["rdb-backup-max-snapshot-count"]; v != nil { i, err := strconv.Atoi(*v) if err != nil { - return nil, fmt.Errorf("Error parsing `rdb-backup-max-snapshot-count` %q: %+v", v, err) + return nil, fmt.Errorf("Error parsing `rdb-backup-max-snapshot-count` %q: %+v", *v, err) } outputs["rdb_backup_max_snapshot_count"] = i } diff --git a/azurerm/resource_arm_role_assignment.go b/azurerm/resource_arm_role_assignment.go index 113c57dd04deb..e9f6d307d28b3 100644 --- a/azurerm/resource_arm_role_assignment.go +++ b/azurerm/resource_arm_role_assignment.go @@ -4,9 +4,11 @@ import ( "fmt" "log" "strings" + "time" "github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2018-01-01-preview/authorization" "github.com/hashicorp/go-uuid" + "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -105,7 +107,7 @@ func resourceArmRoleAssignmentCreate(d *schema.ResourceData, meta interface{}) e }, } - _, err := roleAssignmentsClient.Create(ctx, scope, name, properties) + err := resource.Retry(300*time.Second, retryRoleAssignmentsClient(scope, name, properties, meta)) if err != nil { return err } @@ -176,3 +178,19 @@ func validateRoleDefinitionName(i interface{}, k string) ([]string, []error) { } return nil, nil } + +func retryRoleAssignmentsClient(scope string, name string, properties authorization.RoleAssignmentCreateParameters, meta interface{}) func() *resource.RetryError { + + return func() *resource.RetryError { + roleAssignmentsClient := meta.(*ArmClient).roleAssignmentsClient + ctx := meta.(*ArmClient).StopContext + + _, err := roleAssignmentsClient.Create(ctx, scope, name, properties) + + if err != nil { + return resource.RetryableError(err) + } + return nil + + } +} diff --git a/azurerm/resource_arm_route.go b/azurerm/resource_arm_route.go index 0269bc5c143e2..b5f889f52a85a 100644 --- a/azurerm/resource_arm_route.go +++ b/azurerm/resource_arm_route.go @@ -6,6 +6,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -15,23 +16,26 @@ func resourceArmRoute() *schema.Resource { Read: resourceArmRouteRead, Update: resourceArmRouteCreateUpdate, Delete: resourceArmRouteDelete, + Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.NoZeroValues, }, "resource_group_name": resourceGroupNameSchema(), "route_table_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.NoZeroValues, }, "address_prefix": { @@ -49,7 +53,7 @@ func resourceArmRoute() *schema.Resource { string(network.RouteNextHopTypeVirtualAppliance), string(network.RouteNextHopTypeNone), }, true), - DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + DiffSuppressFunc: suppress.CaseDifference, }, "next_hop_in_ip_address": { @@ -75,19 +79,16 @@ func resourceArmRouteCreateUpdate(d *schema.ResourceData, meta interface{}) erro azureRMLockByName(rtName, routeTableResourceName) defer azureRMUnlockByName(rtName, routeTableResourceName) - properties := network.RoutePropertiesFormat{ - AddressPrefix: &addressPrefix, - NextHopType: network.RouteNextHopType(nextHopType), + route := network.Route{ + Name: &name, + RoutePropertiesFormat: &network.RoutePropertiesFormat{ + AddressPrefix: &addressPrefix, + NextHopType: network.RouteNextHopType(nextHopType), + }, } if v, ok := d.GetOk("next_hop_in_ip_address"); ok { - nextHopInIpAddress := v.(string) - properties.NextHopIPAddress = &nextHopInIpAddress - } - - route := network.Route{ - Name: &name, - RoutePropertiesFormat: &properties, + route.RoutePropertiesFormat.NextHopIPAddress = utils.String(v.(string)) } future, err := client.CreateOrUpdate(ctx, resGroup, rtName, name, route) @@ -95,8 +96,7 @@ func resourceArmRouteCreateUpdate(d *schema.ResourceData, meta interface{}) erro return fmt.Errorf("Error Creating/Updating Route %q (Route Table %q / Resource Group %q): %+v", name, rtName, resGroup, err) } - err = future.WaitForCompletionRef(ctx, client.Client) - if err != nil { + if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { return fmt.Errorf("Error waiting for completion for Route %q (Route Table %q / Resource Group %q): %+v", name, rtName, resGroup, err) } diff --git a/azurerm/resource_arm_route_table.go b/azurerm/resource_arm_route_table.go index a870f32de9037..773193a47a0f3 100644 --- a/azurerm/resource_arm_route_table.go +++ b/azurerm/resource_arm_route_table.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -15,9 +16,9 @@ var routeTableResourceName = "azurerm_route_table" func resourceArmRouteTable() *schema.Resource { return &schema.Resource{ - Create: resourceArmRouteTableCreate, + Create: resourceArmRouteTableCreateUpdate, Read: resourceArmRouteTableRead, - Update: resourceArmRouteTableCreate, + Update: resourceArmRouteTableCreateUpdate, Delete: resourceArmRouteTableDelete, Importer: &schema.ResourceImporter{ @@ -64,7 +65,7 @@ func resourceArmRouteTable() *schema.Resource { string(network.RouteNextHopTypeVirtualAppliance), string(network.RouteNextHopTypeNone), }, true), - DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + DiffSuppressFunc: suppress.CaseDifference, }, "next_hop_in_ip_address": { @@ -95,7 +96,7 @@ func resourceArmRouteTable() *schema.Resource { } } -func resourceArmRouteTableCreate(d *schema.ResourceData, meta interface{}) error { +func resourceArmRouteTableCreateUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*ArmClient).routeTablesClient ctx := meta.(*ArmClient).StopContext @@ -106,16 +107,11 @@ func resourceArmRouteTableCreate(d *schema.ResourceData, meta interface{}) error resGroup := d.Get("resource_group_name").(string) tags := d.Get("tags").(map[string]interface{}) - routes, err := expandRouteTableRoutes(d) - if err != nil { - return fmt.Errorf("Error Expanding list of Route Table Routes: %+v", err) - } - routeSet := network.RouteTable{ Name: &name, Location: &location, RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{ - Routes: &routes, + Routes: expandRouteTableRoutes(d), DisableBgpRoutePropagation: utils.Bool(d.Get("disable_bgp_route_propagation").(bool)), }, Tags: expandTags(tags), @@ -126,8 +122,7 @@ func resourceArmRouteTableCreate(d *schema.ResourceData, meta interface{}) error return fmt.Errorf("Error Creating/Updating Route Table %q (Resource Group %q): %+v", name, resGroup, err) } - err = future.WaitForCompletionRef(ctx, client.Client) - if err != nil { + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { return fmt.Errorf("Error waiting for completion of Route Table %q (Resource Group %q): %+v", name, resGroup, err) } @@ -204,43 +199,36 @@ func resourceArmRouteTableDelete(d *schema.ResourceData, meta interface{}) error } } - err = future.WaitForCompletionRef(ctx, client.Client) - if err != nil { + if err := future.WaitForCompletionRef(ctx, client.Client); err != nil { return fmt.Errorf("Error waiting for deletion of Route Table %q (Resource Group %q): %+v", name, resGroup, err) } return nil } -func expandRouteTableRoutes(d *schema.ResourceData) ([]network.Route, error) { +func expandRouteTableRoutes(d *schema.ResourceData) *[]network.Route { configs := d.Get("route").([]interface{}) routes := make([]network.Route, 0, len(configs)) for _, configRaw := range configs { data := configRaw.(map[string]interface{}) - addressPrefix := data["address_prefix"].(string) - nextHopType := data["next_hop_type"].(string) - - properties := network.RoutePropertiesFormat{ - AddressPrefix: &addressPrefix, - NextHopType: network.RouteNextHopType(nextHopType), + route := network.Route{ + Name: utils.String(data["name"].(string)), + RoutePropertiesFormat: &network.RoutePropertiesFormat{ + AddressPrefix: utils.String(data["address_prefix"].(string)), + NextHopType: network.RouteNextHopType(data["next_hop_type"].(string)), + }, } if v := data["next_hop_in_ip_address"].(string); v != "" { - properties.NextHopIPAddress = &v - } - - name := data["name"].(string) - route := network.Route{ - Name: &name, - RoutePropertiesFormat: &properties, + route.RoutePropertiesFormat.NextHopIPAddress = &v } routes = append(routes, route) } - return routes, nil + return &routes } func flattenRouteTableRoutes(input *[]network.Route) []interface{} { @@ -267,10 +255,10 @@ func flattenRouteTableRoutes(input *[]network.Route) []interface{} { return results } -func flattenRouteTableSubnets(input *[]network.Subnet) []string { +func flattenRouteTableSubnets(subnets *[]network.Subnet) []string { output := []string{} - if subnets := input; subnets != nil { + if subnets != nil { for _, subnet := range *subnets { output = append(output, *subnet.ID) } diff --git a/azurerm/resource_arm_route_table_test.go b/azurerm/resource_arm_route_table_test.go index f014f9cfb7e5f..60e174970aa87 100644 --- a/azurerm/resource_arm_route_table_test.go +++ b/azurerm/resource_arm_route_table_test.go @@ -382,19 +382,19 @@ resource "azurerm_route_table" "test" { func testAccAzureRMRouteTable_singleRoute(rInt int, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" + name = "acctestRG-%d" location = "%s" } resource "azurerm_route_table" "test" { - name = "acctestrt%d" - location = "${azurerm_resource_group.test.location}" + name = "acctestrt%d" + location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" route { - name = "route1" + name = "route1" address_prefix = "10.1.0.0/16" - next_hop_type = "vnetlocal" + next_hop_type = "vnetlocal" } } `, rInt, location, rInt) @@ -403,15 +403,15 @@ resource "azurerm_route_table" "test" { func testAccAzureRMRouteTable_singleRouteRemoved(rInt int, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" + name = "acctestRG-%d" location = "%s" } resource "azurerm_route_table" "test" { - name = "acctestrt%d" - location = "${azurerm_resource_group.test.location}" + name = "acctestrt%d" + location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" - route = [] + route = [] } `, rInt, location, rInt) } @@ -419,25 +419,25 @@ resource "azurerm_route_table" "test" { func testAccAzureRMRouteTable_multipleRoutes(rInt int, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" + name = "acctestRG-%d" location = "%s" } resource "azurerm_route_table" "test" { - name = "acctestrt%d" - location = "${azurerm_resource_group.test.location}" + name = "acctestrt%d" + location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" route { - name = "route1" + name = "route1" address_prefix = "10.1.0.0/16" - next_hop_type = "vnetlocal" + next_hop_type = "vnetlocal" } route { - name = "route2" + name = "route2" address_prefix = "10.2.0.0/16" - next_hop_type = "vnetlocal" + next_hop_type = "vnetlocal" } } `, rInt, location, rInt) @@ -446,19 +446,19 @@ resource "azurerm_route_table" "test" { func testAccAzureRMRouteTable_withTags(rInt int, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" + name = "acctestRG-%d" location = "%s" } resource "azurerm_route_table" "test" { - name = "acctestrt%d" - location = "${azurerm_resource_group.test.location}" + name = "acctestrt%d" + location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" route { - name = "route1" + name = "route1" address_prefix = "10.1.0.0/16" - next_hop_type = "vnetlocal" + next_hop_type = "vnetlocal" } tags { @@ -472,19 +472,19 @@ resource "azurerm_route_table" "test" { func testAccAzureRMRouteTable_withTagsUpdate(rInt int, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" + name = "acctestRG-%d" location = "%s" } resource "azurerm_route_table" "test" { - name = "acctestrt%d" - location = "${azurerm_resource_group.test.location}" + name = "acctestrt%d" + location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" route { - name = "route1" + name = "route1" address_prefix = "10.1.0.0/16" - next_hop_type = "vnetlocal" + next_hop_type = "vnetlocal" } tags { diff --git a/azurerm/resource_arm_route_test.go b/azurerm/resource_arm_route_test.go index 8e532863a260d..d70e4eee85c02 100644 --- a/azurerm/resource_arm_route_test.go +++ b/azurerm/resource_arm_route_test.go @@ -171,23 +171,23 @@ func testCheckAzureRMRouteDestroy(s *terraform.State) error { func testAccAzureRMRoute_basic(rInt int, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" + name = "acctestRG-%d" location = "%s" } resource "azurerm_route_table" "test" { - name = "acctestrt%d" - location = "${azurerm_resource_group.test.location}" + name = "acctestrt%d" + location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" } resource "azurerm_route" "test" { - name = "acctestroute%d" + name = "acctestroute%d" resource_group_name = "${azurerm_resource_group.test.name}" - route_table_name = "${azurerm_route_table.test.name}" + route_table_name = "${azurerm_route_table.test.name}" address_prefix = "10.1.0.0/16" - next_hop_type = "vnetlocal" + next_hop_type = "vnetlocal" } `, rInt, location, rInt, rInt) } @@ -195,23 +195,23 @@ resource "azurerm_route" "test" { func testAccAzureRMRoute_multipleRoutes(rInt int, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { - name = "acctestRG-%d" + name = "acctestRG-%d" location = "%s" } resource "azurerm_route_table" "test" { - name = "acctestrt%d" - location = "${azurerm_resource_group.test.location}" + name = "acctestrt%d" + location = "${azurerm_resource_group.test.location}" resource_group_name = "${azurerm_resource_group.test.name}" } resource "azurerm_route" "test1" { - name = "acctestroute%d" + name = "acctestroute%d" resource_group_name = "${azurerm_resource_group.test.name}" - route_table_name = "${azurerm_route_table.test.name}" + route_table_name = "${azurerm_route_table.test.name}" address_prefix = "10.2.0.0/16" - next_hop_type = "none" + next_hop_type = "none" } `, rInt, location, rInt, rInt) } diff --git a/azurerm/resource_arm_scheduler_job_collection.go b/azurerm/resource_arm_scheduler_job_collection.go index 6beb54466b965..7227fa60d2300 100644 --- a/azurerm/resource_arm_scheduler_job_collection.go +++ b/azurerm/resource_arm_scheduler_job_collection.go @@ -199,7 +199,7 @@ func resourceArmSchedulerJobCollectionRead(d *schema.ResourceData, meta interfac d.Set("state", string(properties.State)) if err := d.Set("quota", flattenAzureArmSchedulerJobCollectionQuota(properties.Quota)); err != nil { - return fmt.Errorf("Error flattening quota for Job Collection %q (Resource Group %q): %+v", collection.Name, resourceGroup, err) + return fmt.Errorf("Error flattening quota for Job Collection %q (Resource Group %q): %+v", *collection.Name, resourceGroup, err) } } diff --git a/azurerm/resource_arm_service_fabric_cluster.go b/azurerm/resource_arm_service_fabric_cluster.go new file mode 100644 index 0000000000000..8ddd315ad51ac --- /dev/null +++ b/azurerm/resource_arm_service_fabric_cluster.go @@ -0,0 +1,824 @@ +package azurerm + +import ( + "fmt" + "log" + + "github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmServiceFabricCluster() *schema.Resource { + return &schema.Resource{ + Create: resourceArmServiceFabricClusterCreate, + Read: resourceArmServiceFabricClusterRead, + Update: resourceArmServiceFabricClusterUpdate, + Delete: resourceArmServiceFabricClusterDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "resource_group_name": resourceGroupNameSchema(), + + "location": locationSchema(), + + "reliability_level": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(servicefabric.ReliabilityLevelNone), + string(servicefabric.ReliabilityLevelBronze), + string(servicefabric.ReliabilityLevelSilver), + string(servicefabric.ReliabilityLevelGold), + string(servicefabric.ReliabilityLevelPlatinum), + }, false), + }, + + "upgrade_mode": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(servicefabric.Automatic), + string(servicefabric.Manual), + }, false), + }, + + "management_endpoint": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "vm_image": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "add_on_features": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + + "certificate": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "thumbprint": { + Type: schema.TypeString, + Required: true, + }, + "thumbprint_secondary": { + Type: schema.TypeString, + Optional: true, + }, + "x509_store_name": { + Type: schema.TypeString, + Required: true, + }, + }, + }, + }, + + "client_certificate_thumbprint": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "thumbprint": { + Type: schema.TypeString, + Required: true, + }, + "is_admin": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + }, + + "diagnostics_config": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "storage_account_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "protected_account_key_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "blob_endpoint": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "queue_endpoint": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "table_endpoint": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + }, + }, + + "fabric_settings": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + "parameters": { + Type: schema.TypeMap, + Optional: true, + }, + }, + }, + }, + + "node_type": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "instance_count": { + Type: schema.TypeInt, + Required: true, + }, + "is_primary": { + Type: schema.TypeBool, + Required: true, + ForceNew: true, + }, + "client_endpoint_port": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + }, + "http_endpoint_port": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + }, + "durability_level": { + Type: schema.TypeString, + Optional: true, + Default: string(servicefabric.Bronze), + ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{ + string(servicefabric.Bronze), + string(servicefabric.Gold), + string(servicefabric.Silver), + }, false), + }, + + "application_ports": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "start_port": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + }, + "end_port": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + }, + }, + }, + }, + + "ephemeral_ports": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "start_port": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + }, + "end_port": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + }, + }, + }, + }, + }, + }, + }, + + "tags": tagsSchema(), + + "cluster_endpoint": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceArmServiceFabricClusterCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).serviceFabricClustersClient + ctx := meta.(*ArmClient).StopContext + + log.Printf("[INFO] preparing arguments for Service Fabric Cluster creation.") + + resourceGroup := d.Get("resource_group_name").(string) + name := d.Get("name").(string) + location := d.Get("location").(string) + reliabilityLevel := d.Get("reliability_level").(string) + managementEndpoint := d.Get("management_endpoint").(string) + upgradeMode := d.Get("upgrade_mode").(string) + vmImage := d.Get("vm_image").(string) + tags := d.Get("tags").(map[string]interface{}) + + addOnFeaturesRaw := d.Get("add_on_features").(*schema.Set).List() + addOnFeatures := expandServiceFabricClusterAddOnFeatures(addOnFeaturesRaw) + + certificateRaw := d.Get("certificate").([]interface{}) + certificate := expandServiceFabricClusterCertificate(certificateRaw) + + clientCertificateThumbprintRaw := d.Get("client_certificate_thumbprint").([]interface{}) + clientCertificateThumbprints := expandServiceFabricClusterClientCertificateThumbprints(clientCertificateThumbprintRaw) + + diagnosticsRaw := d.Get("diagnostics_config").([]interface{}) + diagnostics := expandServiceFabricClusterDiagnosticsConfig(diagnosticsRaw) + + fabricSettingsRaw := d.Get("fabric_settings").([]interface{}) + fabricSettings := expandServiceFabricClusterFabricSettings(fabricSettingsRaw) + + nodeTypesRaw := d.Get("node_type").([]interface{}) + nodeTypes := expandServiceFabricClusterNodeTypes(nodeTypesRaw) + + cluster := servicefabric.Cluster{ + Location: utils.String(location), + Tags: expandTags(tags), + ClusterProperties: &servicefabric.ClusterProperties{ + AddOnFeatures: addOnFeatures, + Certificate: certificate, + ClientCertificateThumbprints: clientCertificateThumbprints, + DiagnosticsStorageAccountConfig: diagnostics, + FabricSettings: fabricSettings, + ManagementEndpoint: utils.String(managementEndpoint), + NodeTypes: nodeTypes, + ReliabilityLevel: servicefabric.ReliabilityLevel(reliabilityLevel), + UpgradeMode: servicefabric.UpgradeMode(upgradeMode), + VMImage: utils.String(vmImage), + }, + } + + future, err := client.Create(ctx, resourceGroup, name, cluster) + if err != nil { + return fmt.Errorf("Error creating Service Fabric Cluster %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + err = future.WaitForCompletionRef(ctx, client.Client) + if err != nil { + return fmt.Errorf("Error waiting for creation of Service Fabric Cluster %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + read, err := client.Get(ctx, resourceGroup, name) + if err != nil { + return fmt.Errorf("Error retrieving Service Fabric Cluster %q (Resource Group %q): %+v", name, resourceGroup, err) + } + if read.ID == nil { + return fmt.Errorf("Cannot read ID of Service Fabric Cluster %q (Resource Group %q)", name, resourceGroup) + } + + d.SetId(*read.ID) + + return resourceArmServiceFabricClusterRead(d, meta) +} + +func resourceArmServiceFabricClusterUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).serviceFabricClustersClient + ctx := meta.(*ArmClient).StopContext + + log.Printf("[INFO] preparing arguments for Service Fabric Cluster update.") + + resourceGroup := d.Get("resource_group_name").(string) + name := d.Get("name").(string) + reliabilityLevel := d.Get("reliability_level").(string) + upgradeMode := d.Get("upgrade_mode").(string) + tags := d.Get("tags").(map[string]interface{}) + + addOnFeaturesRaw := d.Get("add_on_features").(*schema.Set).List() + addOnFeatures := expandServiceFabricClusterAddOnFeatures(addOnFeaturesRaw) + + certificateRaw := d.Get("certificate").([]interface{}) + certificate := expandServiceFabricClusterCertificate(certificateRaw) + + clientCertificateThumbprintsRaw := d.Get("client_certificate_thumbprint").([]interface{}) + clientCertificateThumbprints := expandServiceFabricClusterClientCertificateThumbprints(clientCertificateThumbprintsRaw) + + fabricSettingsRaw := d.Get("fabric_settings").([]interface{}) + fabricSettings := expandServiceFabricClusterFabricSettings(fabricSettingsRaw) + + nodeTypesRaw := d.Get("node_type").([]interface{}) + nodeTypes := expandServiceFabricClusterNodeTypes(nodeTypesRaw) + + parameters := servicefabric.ClusterUpdateParameters{ + ClusterPropertiesUpdateParameters: &servicefabric.ClusterPropertiesUpdateParameters{ + AddOnFeatures: addOnFeatures, + Certificate: certificate, + ClientCertificateThumbprints: clientCertificateThumbprints, + FabricSettings: fabricSettings, + NodeTypes: nodeTypes, + ReliabilityLevel: servicefabric.ReliabilityLevel1(reliabilityLevel), + UpgradeMode: servicefabric.UpgradeMode1(upgradeMode), + }, + Tags: expandTags(tags), + } + + future, err := client.Update(ctx, resourceGroup, name, parameters) + if err != nil { + return fmt.Errorf("Error updating Service Fabric Cluster %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + err = future.WaitForCompletionRef(ctx, client.Client) + if err != nil { + return fmt.Errorf("Error waiting for update of Service Fabric Cluster %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + return resourceArmServiceFabricClusterRead(d, meta) +} + +func resourceArmServiceFabricClusterRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).serviceFabricClustersClient + ctx := meta.(*ArmClient).StopContext + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + + resourceGroup := id.ResourceGroup + name := id.Path["clusters"] + + resp, err := client.Get(ctx, resourceGroup, name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[WARN] Service Fabric Cluster %q (Resource Group %q) was not found - removing from state!", name, resourceGroup) + d.SetId("") + return nil + } + + return fmt.Errorf("Error retrieving Service Fabric Cluster %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + d.Set("name", name) + d.Set("resource_group_name", resourceGroup) + if location := resp.Location; location != nil { + d.Set("location", azureRMNormalizeLocation(*location)) + } + + if props := resp.ClusterProperties; props != nil { + d.Set("cluster_endpoint", props.ClusterEndpoint) + d.Set("management_endpoint", props.ManagementEndpoint) + d.Set("reliability_level", string(props.ReliabilityLevel)) + d.Set("upgrade_mode", string(props.UpgradeMode)) + d.Set("vm_image", props.VMImage) + + addOnFeatures := flattenServiceFabricClusterAddOnFeatures(props.AddOnFeatures) + if err := d.Set("add_on_features", schema.NewSet(schema.HashString, addOnFeatures)); err != nil { + return fmt.Errorf("Error setting `add_on_features`: %+v", err) + } + + certificate := flattenServiceFabricClusterCertificate(props.Certificate) + if err := d.Set("certificate", certificate); err != nil { + return fmt.Errorf("Error setting `certificate`: %+v", err) + } + + clientCertificateThumbprints := flattenServiceFabricClusterClientCertificateThumbprints(props.ClientCertificateThumbprints) + if err := d.Set("client_certificate_thumbprint", clientCertificateThumbprints); err != nil { + return fmt.Errorf("Error setting `client_certificate_thumbprint`: %+v", err) + } + + diagnostics := flattenServiceFabricClusterDiagnosticsConfig(props.DiagnosticsStorageAccountConfig) + if err := d.Set("diagnostics_config", diagnostics); err != nil { + return fmt.Errorf("Error setting `diagnostics_config`: %+v", err) + } + + fabricSettings := flattenServiceFabricClusterFabricSettings(props.FabricSettings) + if err := d.Set("fabric_settings", fabricSettings); err != nil { + return fmt.Errorf("Error setting `fabric_settings`: %+v", err) + } + + nodeTypes := flattenServiceFabricClusterNodeTypes(props.NodeTypes) + if err := d.Set("node_type", nodeTypes); err != nil { + return fmt.Errorf("Error setting `node_type`: %+v", err) + } + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmServiceFabricClusterDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).serviceFabricClustersClient + ctx := meta.(*ArmClient).StopContext + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resourceGroup := id.ResourceGroup + name := id.Path["clusters"] + + log.Printf("[DEBUG] Deleting Service Fabric Cluster %q (Resource Group %q)", name, resourceGroup) + + resp, err := client.Delete(ctx, resourceGroup, name) + if err != nil { + if !response.WasNotFound(resp.Response) { + return fmt.Errorf("Error deleting Service Fabric Cluster %q (Resource Group %q): %+v", name, resourceGroup, err) + } + } + + return nil +} + +func expandServiceFabricClusterAddOnFeatures(input []interface{}) *[]string { + output := make([]string, 0) + + for _, v := range input { + output = append(output, v.(string)) + } + + return &output +} + +func flattenServiceFabricClusterAddOnFeatures(input *[]string) []interface{} { + output := make([]interface{}, 0) + + if input != nil { + for _, v := range *input { + output = append(output, v) + } + } + + return output +} + +func expandServiceFabricClusterCertificate(input []interface{}) *servicefabric.CertificateDescription { + if len(input) == 0 { + return nil + } + + v := input[0].(map[string]interface{}) + + thumbprint := v["thumbprint"].(string) + x509StoreName := v["x509_store_name"].(string) + + result := servicefabric.CertificateDescription{ + Thumbprint: utils.String(thumbprint), + X509StoreName: servicefabric.X509StoreName(x509StoreName), + } + + if thumb, ok := v["thumbprint_secondary"]; ok { + result.ThumbprintSecondary = utils.String(thumb.(string)) + } + + return &result +} + +func flattenServiceFabricClusterCertificate(input *servicefabric.CertificateDescription) []interface{} { + results := make([]interface{}, 0) + + if v := input; v != nil { + output := make(map[string]interface{}, 0) + + if thumbprint := input.Thumbprint; thumbprint != nil { + output["thumbprint"] = *thumbprint + } + + if thumbprint := input.ThumbprintSecondary; thumbprint != nil { + output["thumbprint_secondary"] = *thumbprint + } + + output["x509_store_name"] = string(input.X509StoreName) + results = append(results, output) + } + + return results +} + +func expandServiceFabricClusterClientCertificateThumbprints(input []interface{}) *[]servicefabric.ClientCertificateThumbprint { + results := make([]servicefabric.ClientCertificateThumbprint, 0) + + for _, v := range input { + val := v.(map[string]interface{}) + + thumbprint := val["thumbprint"].(string) + isAdmin := val["is_admin"].(bool) + + result := servicefabric.ClientCertificateThumbprint{ + CertificateThumbprint: utils.String(thumbprint), + IsAdmin: utils.Bool(isAdmin), + } + results = append(results, result) + } + + return &results +} + +func flattenServiceFabricClusterClientCertificateThumbprints(input *[]servicefabric.ClientCertificateThumbprint) []interface{} { + if input == nil { + return []interface{}{} + } + + results := make([]interface{}, 0) + + for _, v := range *input { + result := make(map[string]interface{}, 0) + + if thumbprint := v.CertificateThumbprint; thumbprint != nil { + result["thumbprint"] = *thumbprint + } + + if isAdmin := v.IsAdmin; isAdmin != nil { + result["is_admin"] = *isAdmin + } + + results = append(results, result) + } + + return results +} + +func expandServiceFabricClusterDiagnosticsConfig(input []interface{}) *servicefabric.DiagnosticsStorageAccountConfig { + if len(input) == 0 { + return nil + } + + v := input[0].(map[string]interface{}) + + storageAccountName := v["storage_account_name"].(string) + protectedAccountKeyName := v["protected_account_key_name"].(string) + blobEndpoint := v["blob_endpoint"].(string) + queueEndpoint := v["queue_endpoint"].(string) + tableEndpoint := v["table_endpoint"].(string) + + config := servicefabric.DiagnosticsStorageAccountConfig{ + StorageAccountName: utils.String(storageAccountName), + ProtectedAccountKeyName: utils.String(protectedAccountKeyName), + BlobEndpoint: utils.String(blobEndpoint), + QueueEndpoint: utils.String(queueEndpoint), + TableEndpoint: utils.String(tableEndpoint), + } + return &config +} + +func flattenServiceFabricClusterDiagnosticsConfig(input *servicefabric.DiagnosticsStorageAccountConfig) []interface{} { + results := make([]interface{}, 0) + + if v := input; v != nil { + output := make(map[string]interface{}, 0) + + if name := v.StorageAccountName; name != nil { + output["storage_account_name"] = *name + } + + if name := v.ProtectedAccountKeyName; name != nil { + output["protected_account_key_name"] = *name + } + + if endpoint := v.BlobEndpoint; endpoint != nil { + output["blob_endpoint"] = *endpoint + } + + if endpoint := v.QueueEndpoint; endpoint != nil { + output["queue_endpoint"] = *endpoint + } + + if endpoint := v.TableEndpoint; endpoint != nil { + output["table_endpoint"] = *endpoint + } + + results = append(results, output) + } + + return results +} + +func expandServiceFabricClusterFabricSettings(input []interface{}) *[]servicefabric.SettingsSectionDescription { + results := make([]servicefabric.SettingsSectionDescription, 0) + + for _, v := range input { + val := v.(map[string]interface{}) + + name := val["name"].(string) + params := make([]servicefabric.SettingsParameterDescription, 0) + paramsRaw := val["parameters"].(map[string]interface{}) + for k, v := range paramsRaw { + param := servicefabric.SettingsParameterDescription{ + Name: utils.String(k), + Value: utils.String(v.(string)), + } + params = append(params, param) + } + + result := servicefabric.SettingsSectionDescription{ + Name: utils.String(name), + Parameters: ¶ms, + } + results = append(results, result) + } + + return &results +} + +func flattenServiceFabricClusterFabricSettings(input *[]servicefabric.SettingsSectionDescription) []interface{} { + if input == nil { + return []interface{}{} + } + + results := make([]interface{}, 0) + + for _, v := range *input { + result := make(map[string]interface{}, 0) + + if name := v.Name; name != nil { + result["name"] = *name + } + + parameters := make(map[string]interface{}, 0) + if paramsRaw := v.Parameters; paramsRaw != nil { + for _, p := range *paramsRaw { + if p.Name == nil || p.Value == nil { + continue + } + + parameters[*p.Name] = *p.Value + } + } + result["parameters"] = parameters + results = append(results, result) + } + + return results +} + +func expandServiceFabricClusterNodeTypes(input []interface{}) *[]servicefabric.NodeTypeDescription { + results := make([]servicefabric.NodeTypeDescription, 0) + + for _, v := range input { + node := v.(map[string]interface{}) + + name := node["name"].(string) + instanceCount := node["instance_count"].(int) + clientEndpointPort := node["client_endpoint_port"].(int) + httpEndpointPort := node["http_endpoint_port"].(int) + isPrimary := node["is_primary"].(bool) + durabilityLevel := node["durability_level"].(string) + + result := servicefabric.NodeTypeDescription{ + Name: utils.String(name), + VMInstanceCount: utils.Int32(int32(instanceCount)), + IsPrimary: utils.Bool(isPrimary), + ClientConnectionEndpointPort: utils.Int32(int32(clientEndpointPort)), + HTTPGatewayEndpointPort: utils.Int32(int32(httpEndpointPort)), + DurabilityLevel: servicefabric.DurabilityLevel(durabilityLevel), + } + + applicationPortsRaw := node["application_ports"].([]interface{}) + if len(applicationPortsRaw) > 0 { + portsRaw := applicationPortsRaw[0].(map[string]interface{}) + + startPort := portsRaw["start_port"].(int) + endPort := portsRaw["end_port"].(int) + + result.ApplicationPorts = &servicefabric.EndpointRangeDescription{ + StartPort: utils.Int32(int32(startPort)), + EndPort: utils.Int32(int32(endPort)), + } + } + + ephemeralPortsRaw := node["ephemeral_ports"].([]interface{}) + if len(ephemeralPortsRaw) > 0 { + portsRaw := ephemeralPortsRaw[0].(map[string]interface{}) + + startPort := portsRaw["start_port"].(int) + endPort := portsRaw["end_port"].(int) + + result.EphemeralPorts = &servicefabric.EndpointRangeDescription{ + StartPort: utils.Int32(int32(startPort)), + EndPort: utils.Int32(int32(endPort)), + } + } + + results = append(results, result) + } + + return &results +} + +func flattenServiceFabricClusterNodeTypes(input *[]servicefabric.NodeTypeDescription) []interface{} { + if input == nil { + return []interface{}{} + } + + results := make([]interface{}, 0) + + for _, v := range *input { + output := make(map[string]interface{}, 0) + + if name := v.Name; name != nil { + output["name"] = *name + } + + if count := v.VMInstanceCount; count != nil { + output["instance_count"] = int(*count) + } + + if primary := v.IsPrimary; primary != nil { + output["is_primary"] = *primary + } + + if port := v.ClientConnectionEndpointPort; port != nil { + output["client_endpoint_port"] = *port + } + + if port := v.HTTPGatewayEndpointPort; port != nil { + output["http_endpoint_port"] = *port + } + + output["durability_level"] = string(v.DurabilityLevel) + + applicationPorts := make([]interface{}, 0) + if ports := v.ApplicationPorts; ports != nil { + r := make(map[string]interface{}, 0) + if start := ports.StartPort; start != nil { + r["start_port"] = int(*start) + } + if end := ports.EndPort; end != nil { + r["end_port"] = int(*end) + } + applicationPorts = append(applicationPorts, r) + } + output["application_ports"] = applicationPorts + + ephermeralPorts := make([]interface{}, 0) + if ports := v.EphemeralPorts; ports != nil { + r := make(map[string]interface{}, 0) + if start := ports.StartPort; start != nil { + r["start_port"] = int(*start) + } + if end := ports.EndPort; end != nil { + r["end_port"] = int(*end) + } + ephermeralPorts = append(ephermeralPorts, r) + } + output["ephemeral_ports"] = ephermeralPorts + + results = append(results, output) + } + + return results +} diff --git a/azurerm/resource_arm_service_fabric_cluster_test.go b/azurerm/resource_arm_service_fabric_cluster_test.go new file mode 100644 index 0000000000000..439eea3a56fad --- /dev/null +++ b/azurerm/resource_arm_service_fabric_cluster_test.go @@ -0,0 +1,727 @@ +package azurerm + +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMServiceFabricCluster_basic(t *testing.T) { + resourceName := "azurerm_service_fabric_cluster.test" + ri := acctest.RandInt() + location := testLocation() + config := testAccAzureRMServiceFabricCluster_basic(ri, location, 3) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMServiceFabricClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServiceFabricClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "management_endpoint", "http://example:80"), + resource.TestCheckResourceAttr(resourceName, "add_on_features.#", "0"), + resource.TestCheckResourceAttr(resourceName, "certificate.#", "0"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_thumbprint.#", "0"), + resource.TestCheckResourceAttr(resourceName, "diagnostics_config.#", "0"), + resource.TestCheckResourceAttr(resourceName, "node_type.#", "1"), + resource.TestCheckResourceAttr(resourceName, "node_type.0.instance_count", "3"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMServiceFabricCluster_addOnFeatures(t *testing.T) { + resourceName := "azurerm_service_fabric_cluster.test" + ri := acctest.RandInt() + location := testLocation() + config := testAccAzureRMServiceFabricCluster_addOnFeatures(ri, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMServiceFabricClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServiceFabricClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "add_on_features.#", "2"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMServiceFabricCluster_certificate(t *testing.T) { + resourceName := "azurerm_service_fabric_cluster.test" + ri := acctest.RandInt() + location := testLocation() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMServiceFabricClusterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMServiceFabricCluster_certificates(ri, location), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServiceFabricClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "certificate.#", "1"), + resource.TestCheckResourceAttr(resourceName, "certificate.0.thumbprint", "33:41:DB:6C:F2:AF:72:C6:11:DF:3B:E3:72:1A:65:3A:F1:D4:3E:CD:50:F5:84:F8:28:79:3D:BE:91:03:C3:EE"), + resource.TestCheckResourceAttr(resourceName, "certificate.0.x509_store_name", "My"), + resource.TestCheckResourceAttr(resourceName, "fabric_settings.0.name", "Security"), + resource.TestCheckResourceAttr(resourceName, "fabric_settings.0.parameters.ClusterProtectionLevel", "EncryptAndSign"), + resource.TestCheckResourceAttr(resourceName, "management_endpoint", "https://example:80"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMServiceFabricCluster_clientCertificateThumbprint(t *testing.T) { + resourceName := "azurerm_service_fabric_cluster.test" + ri := acctest.RandInt() + location := testLocation() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMServiceFabricClusterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMServiceFabricCluster_clientCertificateThumbprint(ri, location), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServiceFabricClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "certificate.#", "1"), + resource.TestCheckResourceAttr(resourceName, "certificate.0.thumbprint", "33:41:DB:6C:F2:AF:72:C6:11:DF:3B:E3:72:1A:65:3A:F1:D4:3E:CD:50:F5:84:F8:28:79:3D:BE:91:03:C3:EE"), + resource.TestCheckResourceAttr(resourceName, "certificate.0.x509_store_name", "My"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_thumbprint.#", "1"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_thumbprint.0.thumbprint", "33:41:DB:6C:F2:AF:72:C6:11:DF:3B:E3:72:1A:65:3A:F1:D4:3E:CD:50:F5:84:F8:28:79:3D:BE:91:03:C3:EE"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_thumbprint.0.is_admin", "true"), + resource.TestCheckResourceAttr(resourceName, "fabric_settings.0.name", "Security"), + resource.TestCheckResourceAttr(resourceName, "fabric_settings.0.parameters.ClusterProtectionLevel", "EncryptAndSign"), + resource.TestCheckResourceAttr(resourceName, "management_endpoint", "https://example:80"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMServiceFabricCluster_diagnosticsConfig(t *testing.T) { + resourceName := "azurerm_service_fabric_cluster.test" + ri := acctest.RandInt() + rs := acctest.RandString(4) + location := testLocation() + config := testAccAzureRMServiceFabricCluster_diagnosticsConfig(ri, rs, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMServiceFabricClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServiceFabricClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "diagnostics_config.#", "1"), + resource.TestCheckResourceAttrSet(resourceName, "diagnostics_config.0.storage_account_name"), + resource.TestCheckResourceAttrSet(resourceName, "diagnostics_config.0.protected_account_key_name"), + resource.TestCheckResourceAttrSet(resourceName, "diagnostics_config.0.blob_endpoint"), + resource.TestCheckResourceAttrSet(resourceName, "diagnostics_config.0.queue_endpoint"), + resource.TestCheckResourceAttrSet(resourceName, "diagnostics_config.0.table_endpoint"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMServiceFabricCluster_fabricSettings(t *testing.T) { + resourceName := "azurerm_service_fabric_cluster.test" + ri := acctest.RandInt() + location := testLocation() + config := testAccAzureRMServiceFabricCluster_fabricSettings(ri, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMServiceFabricClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServiceFabricClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "fabric_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "fabric_settings.0.name", "Security"), + resource.TestCheckResourceAttr(resourceName, "fabric_settings.0.parameters.%", "1"), + resource.TestCheckResourceAttr(resourceName, "fabric_settings.0.parameters.ClusterProtectionLevel", "None"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMServiceFabricCluster_fabricSettingsRemove(t *testing.T) { + resourceName := "azurerm_service_fabric_cluster.test" + ri := acctest.RandInt() + location := testLocation() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMServiceFabricClusterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMServiceFabricCluster_fabricSettings(ri, location), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServiceFabricClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "fabric_settings.#", "1"), + ), + }, + { + Config: testAccAzureRMServiceFabricCluster_basic(ri, location, 3), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServiceFabricClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "fabric_settings.#", "0"), + ), + }, + }, + }) +} + +func TestAccAzureRMServiceFabricCluster_nodeTypeCustomPorts(t *testing.T) { + resourceName := "azurerm_service_fabric_cluster.test" + ri := acctest.RandInt() + location := testLocation() + config := testAccAzureRMServiceFabricCluster_nodeTypeCustomPorts(ri, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMServiceFabricClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServiceFabricClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "node_type.#", "1"), + resource.TestCheckResourceAttr(resourceName, "node_type.0.application_ports.#", "1"), + resource.TestCheckResourceAttr(resourceName, "node_type.0.application_ports.0.start_port", "20000"), + resource.TestCheckResourceAttr(resourceName, "node_type.0.application_ports.0.end_port", "29999"), + resource.TestCheckResourceAttr(resourceName, "node_type.0.ephemeral_ports.#", "1"), + resource.TestCheckResourceAttr(resourceName, "node_type.0.ephemeral_ports.0.start_port", "30000"), + resource.TestCheckResourceAttr(resourceName, "node_type.0.ephemeral_ports.0.end_port", "39999"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMServiceFabricCluster_nodeTypesMultiple(t *testing.T) { + resourceName := "azurerm_service_fabric_cluster.test" + ri := acctest.RandInt() + location := testLocation() + config := testAccAzureRMServiceFabricCluster_nodeTypeMultiple(ri, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMServiceFabricClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServiceFabricClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "node_type.#", "2"), + resource.TestCheckResourceAttr(resourceName, "node_type.0.name", "first"), + resource.TestCheckResourceAttr(resourceName, "node_type.0.instance_count", "3"), + resource.TestCheckResourceAttr(resourceName, "node_type.0.is_primary", "true"), + resource.TestCheckResourceAttr(resourceName, "node_type.1.name", "second"), + resource.TestCheckResourceAttr(resourceName, "node_type.1.instance_count", "4"), + resource.TestCheckResourceAttr(resourceName, "node_type.1.is_primary", "false"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMServiceFabricCluster_nodeTypesUpdate(t *testing.T) { + resourceName := "azurerm_service_fabric_cluster.test" + ri := acctest.RandInt() + location := testLocation() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMServiceFabricClusterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMServiceFabricCluster_basic(ri, location, 3), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServiceFabricClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "node_type.0.instance_count", "3"), + ), + }, + { + Config: testAccAzureRMServiceFabricCluster_basic(ri, location, 4), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServiceFabricClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "node_type.0.instance_count", "4"), + ), + }, + }, + }) +} + +func TestAccAzureRMServiceFabricCluster_tags(t *testing.T) { + resourceName := "azurerm_service_fabric_cluster.test" + ri := acctest.RandInt() + location := testLocation() + config := testAccAzureRMServiceFabricCluster_tags(ri, location) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMServiceFabricClusterDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMServiceFabricClusterExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Hello", "World"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testCheckAzureRMServiceFabricClusterDestroy(s *terraform.State) error { + client := testAccProvider.Meta().(*ArmClient).serviceFabricClustersClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_service_fabric_cluster" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := client.Get(ctx, resourceGroup, name) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Service Fabric Cluster still exists:\n%+v", resp) + } + } + + return nil +} + +func testCheckAzureRMServiceFabricClusterExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + // Ensure we have enough information in state to look up in API + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + clusterName := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for Service Fabric Cluster %q", clusterName) + } + + client := testAccProvider.Meta().(*ArmClient).serviceFabricClustersClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + resp, err := client.Get(ctx, resourceGroup, clusterName) + if err != nil { + return fmt.Errorf("Bad: Get on serviceFabricClustersClient: %+v", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: Service Fabric Cluster %q (Resource Group: %q) does not exist", clusterName, resourceGroup) + } + + return nil + } +} + +func testAccAzureRMServiceFabricCluster_basic(rInt int, location string, count int) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_service_fabric_cluster" "test" { + name = "acctest-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + reliability_level = "Bronze" + upgrade_mode = "Automatic" + vm_image = "Windows" + management_endpoint = "http://example:80" + + node_type { + name = "first" + instance_count = %d + is_primary = true + client_endpoint_port = 2020 + http_endpoint_port = 80 + } +} +`, rInt, location, rInt, count) +} + +func testAccAzureRMServiceFabricCluster_addOnFeatures(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_service_fabric_cluster" "test" { + name = "acctest-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + reliability_level = "Bronze" + upgrade_mode = "Automatic" + vm_image = "Windows" + management_endpoint = "http://example:80" + add_on_features = [ "DnsService", "RepairManager" ] + + node_type { + name = "first" + instance_count = 3 + is_primary = true + client_endpoint_port = 2020 + http_endpoint_port = 80 + } +} +`, rInt, location, rInt) +} + +func testAccAzureRMServiceFabricCluster_certificates(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_service_fabric_cluster" "test" { + name = "acctest-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + reliability_level = "Bronze" + upgrade_mode = "Automatic" + vm_image = "Windows" + management_endpoint = "https://example:80" + + certificate { + thumbprint = "33:41:DB:6C:F2:AF:72:C6:11:DF:3B:E3:72:1A:65:3A:F1:D4:3E:CD:50:F5:84:F8:28:79:3D:BE:91:03:C3:EE" + x509_store_name = "My" + } + + fabric_settings { + name = "Security" + + parameters { + "ClusterProtectionLevel" = "EncryptAndSign" + } + } + + node_type { + name = "first" + instance_count = 3 + is_primary = true + client_endpoint_port = 2020 + http_endpoint_port = 80 + } +} +`, rInt, location, rInt) +} + +func testAccAzureRMServiceFabricCluster_clientCertificateThumbprint(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_service_fabric_cluster" "test" { + name = "acctest-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + reliability_level = "Bronze" + upgrade_mode = "Automatic" + vm_image = "Windows" + management_endpoint = "https://example:80" + + certificate { + thumbprint = "33:41:DB:6C:F2:AF:72:C6:11:DF:3B:E3:72:1A:65:3A:F1:D4:3E:CD:50:F5:84:F8:28:79:3D:BE:91:03:C3:EE" + x509_store_name = "My" + } + + client_certificate_thumbprint { + thumbprint = "33:41:DB:6C:F2:AF:72:C6:11:DF:3B:E3:72:1A:65:3A:F1:D4:3E:CD:50:F5:84:F8:28:79:3D:BE:91:03:C3:EE" + is_admin = true + } + + fabric_settings { + name = "Security" + + parameters { + "ClusterProtectionLevel" = "EncryptAndSign" + } + } + + node_type { + name = "first" + instance_count = 3 + is_primary = true + client_endpoint_port = 2020 + http_endpoint_port = 80 + } +} +`, rInt, location, rInt) +} + +func testAccAzureRMServiceFabricCluster_diagnosticsConfig(rInt int, rString, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_storage_account" "test" { + name = "acctestsa%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + account_tier = "Standard" + account_replication_type = "GRS" +} + +resource "azurerm_service_fabric_cluster" "test" { + name = "acctest-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + reliability_level = "Bronze" + upgrade_mode = "Automatic" + vm_image = "Windows" + management_endpoint = "http://example:80" + + diagnostics_config { + storage_account_name = "${azurerm_storage_account.test.name}" + protected_account_key_name = "StorageAccountKey1" + blob_endpoint = "${azurerm_storage_account.test.primary_blob_endpoint}" + queue_endpoint = "${azurerm_storage_account.test.primary_queue_endpoint}" + table_endpoint = "${azurerm_storage_account.test.primary_table_endpoint}" + } + + node_type { + name = "first" + instance_count = 3 + is_primary = true + client_endpoint_port = 2020 + http_endpoint_port = 80 + } +} +`, rInt, location, rString, rInt) +} + +func testAccAzureRMServiceFabricCluster_fabricSettings(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_service_fabric_cluster" "test" { + name = "acctest-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + reliability_level = "Bronze" + upgrade_mode = "Automatic" + vm_image = "Windows" + management_endpoint = "http://example:80" + + fabric_settings { + name = "Security" + + parameters { + "ClusterProtectionLevel" = "None" + } + } + + node_type { + name = "first" + instance_count = 3 + is_primary = true + client_endpoint_port = 2020 + http_endpoint_port = 80 + } +} +`, rInt, location, rInt) +} + +func testAccAzureRMServiceFabricCluster_nodeTypeCustomPorts(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_service_fabric_cluster" "test" { + name = "acctest-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + reliability_level = "Bronze" + upgrade_mode = "Automatic" + vm_image = "Windows" + management_endpoint = "http://example:80" + + node_type { + name = "first" + instance_count = 3 + is_primary = true + client_endpoint_port = 2020 + http_endpoint_port = 80 + + application_ports { + start_port = 20000 + end_port = 29999 + } + + ephemeral_ports { + start_port = 30000 + end_port = 39999 + } + } +} +`, rInt, location, rInt) +} + +func testAccAzureRMServiceFabricCluster_nodeTypeMultiple(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_service_fabric_cluster" "test" { + name = "acctest-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + reliability_level = "Bronze" + upgrade_mode = "Automatic" + vm_image = "Windows" + management_endpoint = "http://example:80" + + node_type { + name = "first" + instance_count = 3 + is_primary = true + client_endpoint_port = 2020 + http_endpoint_port = 80 + } + + node_type { + name = "second" + instance_count = 4 + is_primary = false + client_endpoint_port = 2121 + http_endpoint_port = 81 + } +} +`, rInt, location, rInt) +} + +func testAccAzureRMServiceFabricCluster_tags(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_service_fabric_cluster" "test" { + name = "acctest-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + reliability_level = "Bronze" + upgrade_mode = "Automatic" + vm_image = "Windows" + management_endpoint = "http://example:80" + + node_type { + name = "first" + instance_count = 3 + is_primary = true + client_endpoint_port = 2020 + http_endpoint_port = 80 + } + + tags { + "Hello" = "World" + } +} +`, rInt, location, rInt) +} diff --git a/azurerm/resource_arm_subnet.go b/azurerm/resource_arm_subnet.go index 887ef32a8257d..82c993d53113d 100644 --- a/azurerm/resource_arm_subnet.go +++ b/azurerm/resource_arm_subnet.go @@ -247,8 +247,7 @@ func resourceArmSubnetDelete(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Error deleting Subnet %q (VN %q / Resource Group %q): %+v", name, vnetName, resGroup, err) } - err = future.WaitForCompletionRef(ctx, client.Client) - if err != nil { + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { return fmt.Errorf("Error waiting for completion for Subnet %q (VN %q / Resource Group %q): %+v", name, vnetName, resGroup, err) } diff --git a/azurerm/resource_arm_virtual_machine.go b/azurerm/resource_arm_virtual_machine.go index 2f0f70df2a126..72237a6a615aa 100644 --- a/azurerm/resource_arm_virtual_machine.go +++ b/azurerm/resource_arm_virtual_machine.go @@ -1181,6 +1181,9 @@ func flattenAzureRmVirtualMachineOsDisk(disk *compute.OSDisk, diskInfo *compute. if disk.Vhd != nil { result["vhd_uri"] = *disk.Vhd.URI } + if disk.Image != nil && disk.Image.URI != nil { + result["image_uri"] = *disk.Image.URI + } if disk.ManagedDisk != nil { result["managed_disk_type"] = string(disk.ManagedDisk.StorageAccountType) if disk.ManagedDisk.ID != nil { diff --git a/azurerm/resource_arm_virtual_machine_scale_set.go b/azurerm/resource_arm_virtual_machine_scale_set.go index a05fffecedecb..18aa18f5126c3 100644 --- a/azurerm/resource_arm_virtual_machine_scale_set.go +++ b/azurerm/resource_arm_virtual_machine_scale_set.go @@ -128,7 +128,6 @@ func resourceArmVirtualMachineScaleSet() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Default: string(compute.Regular), ValidateFunc: validation.StringInSlice([]string{ string(compute.Low), string(compute.Regular), diff --git a/azurerm/resource_arm_virtual_machine_unmanaged_disks_test.go b/azurerm/resource_arm_virtual_machine_unmanaged_disks_test.go index c711ba8c7d5ff..b27559639fd29 100644 --- a/azurerm/resource_arm_virtual_machine_unmanaged_disks_test.go +++ b/azurerm/resource_arm_virtual_machine_unmanaged_disks_test.go @@ -2,6 +2,7 @@ package azurerm import ( "fmt" + "regexp" "strings" "testing" @@ -102,6 +103,29 @@ func TestAccAzureRMVirtualMachine_basicLinuxMachine_disappears(t *testing.T) { }) } +func TestAccAzureRMVirtualMachine_basicLinuxMachineUseExistingOsDiskImage(t *testing.T) { + var vm, mirrorVm compute.VirtualMachine + ri := acctest.RandInt() + config := testAccAzureRMVirtualMachine_basicLinuxMachineUseExistingOsDiskImage(ri, testLocation()) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test", &vm), + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.mirror", &mirrorVm), + testCheckAzureRMVirtualMachineVHDExistence("myosdisk1.vhd", true), + testCheckAzureRMVirtualMachineVHDExistence("mirrorosdisk.vhd", true), + resource.TestMatchResourceAttr("azurerm_virtual_machine.mirror", "storage_os_disk.0.image_uri", regexp.MustCompile("myosdisk1.vhd$")), + ), + }, + }, + }) +} + func TestAccAzureRMVirtualMachine_withDataDisk(t *testing.T) { var vm compute.VirtualMachine @@ -919,6 +943,50 @@ resource "azurerm_virtual_machine" "test" { `, rInt, location, rInt, rInt, rInt, rInt, rInt, rInt) } +func testAccAzureRMVirtualMachine_basicLinuxMachineUseExistingOsDiskImage(rInt int, location string) string { + baseConfig := testAccAzureRMVirtualMachine_basicLinuxMachine(rInt, location) + return fmt.Sprintf(`%s +resource "azurerm_network_interface" "mirror" { + name = "acctmirrorni-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_virtual_machine" "mirror" { + name = "acctmirrorvm-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + network_interface_ids = ["${azurerm_network_interface.mirror.id}"] + vm_size = "Standard_F2" + delete_os_disk_on_termination = false + + os_profile { + computer_name = "hnmirror%d" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_linux_config { + disable_password_authentication = false + } + + storage_os_disk { + name = "mirror" + image_uri = "${azurerm_virtual_machine.test.storage_os_disk.0.vhd_uri}" + vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/mirrorosdisk.vhd" + create_option = "FromImage" + os_type = "Linux" + } +} +`, baseConfig, rInt, rInt, rInt) +} + func testAccAzureRMVirtualMachine_machineNameBeforeUpdate(rInt int, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { diff --git a/azurerm/resource_arm_virtual_network_gateway_connection.go b/azurerm/resource_arm_virtual_network_gateway_connection.go index 3477d23db1b69..1d2e92b449b0d 100644 --- a/azurerm/resource_arm_virtual_network_gateway_connection.go +++ b/azurerm/resource_arm_virtual_network_gateway_connection.go @@ -5,7 +5,6 @@ import ( "log" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network" - "github.com/hashicorp/errwrap" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" @@ -365,7 +364,7 @@ func getArmVirtualNetworkGatewayConnectionProperties(d *schema.ResourceData) (*n virtualNetworkGatewayId := v.(string) _, name, err := resourceGroupAndVirtualNetworkGatewayFromId(virtualNetworkGatewayId) if err != nil { - return nil, errwrap.Wrapf("Error Getting VirtualNetworkGateway Name and Group: {{err}}", err) + return nil, fmt.Errorf("Error Getting VirtualNetworkGateway Name and Group:: %+v", err) } props.VirtualNetworkGateway1 = &network.VirtualNetworkGateway{ @@ -393,7 +392,7 @@ func getArmVirtualNetworkGatewayConnectionProperties(d *schema.ResourceData) (*n peerVirtualNetworkGatewayId := v.(string) _, name, err := resourceGroupAndVirtualNetworkGatewayFromId(peerVirtualNetworkGatewayId) if err != nil { - return nil, errwrap.Wrapf("Error Getting VirtualNetworkGateway Name and Group: {{err}}", err) + return nil, fmt.Errorf("Error Getting VirtualNetworkGateway Name and Group:: %+v", err) } props.VirtualNetworkGateway2 = &network.VirtualNetworkGateway{ @@ -409,7 +408,7 @@ func getArmVirtualNetworkGatewayConnectionProperties(d *schema.ResourceData) (*n localNetworkGatewayId := v.(string) _, name, err := resourceGroupAndLocalNetworkGatewayFromId(localNetworkGatewayId) if err != nil { - return nil, errwrap.Wrapf("Error Getting LocalNetworkGateway Name and Group: {{err}}", err) + return nil, fmt.Errorf("Error Getting LocalNetworkGateway Name and Group:: %+v", err) } props.LocalNetworkGateway2 = &network.LocalNetworkGateway{ diff --git a/azurerm/tags_test.go b/azurerm/tags_test.go index bf95c29c5d6e0..69375046db409 100644 --- a/azurerm/tags_test.go +++ b/azurerm/tags_test.go @@ -90,7 +90,7 @@ func TestExpandARMTags(t *testing.T) { } if *expanded[k] != strVal { - t.Fatalf("Expanded value %q incorrect: expected %q, got %q", k, strVal, expanded[k]) + t.Fatalf("Expanded value %q incorrect: expected %q, got %q", k, strVal, *expanded[k]) } } } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/models.go deleted file mode 100644 index f7b9cea946640..0000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/models.go +++ /dev/null @@ -1,850 +0,0 @@ -package dns - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "encoding/json" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/to" - "net/http" -) - -// HTTPStatusCode enumerates the values for http status code. -type HTTPStatusCode string - -const ( - // Accepted ... - Accepted HTTPStatusCode = "Accepted" - // Ambiguous ... - Ambiguous HTTPStatusCode = "Ambiguous" - // BadGateway ... - BadGateway HTTPStatusCode = "BadGateway" - // BadRequest ... - BadRequest HTTPStatusCode = "BadRequest" - // Conflict ... - Conflict HTTPStatusCode = "Conflict" - // Continue ... - Continue HTTPStatusCode = "Continue" - // Created ... - Created HTTPStatusCode = "Created" - // ExpectationFailed ... - ExpectationFailed HTTPStatusCode = "ExpectationFailed" - // Forbidden ... - Forbidden HTTPStatusCode = "Forbidden" - // Found ... - Found HTTPStatusCode = "Found" - // GatewayTimeout ... - GatewayTimeout HTTPStatusCode = "GatewayTimeout" - // Gone ... - Gone HTTPStatusCode = "Gone" - // HTTPVersionNotSupported ... - HTTPVersionNotSupported HTTPStatusCode = "HttpVersionNotSupported" - // InternalServerError ... - InternalServerError HTTPStatusCode = "InternalServerError" - // LengthRequired ... - LengthRequired HTTPStatusCode = "LengthRequired" - // MethodNotAllowed ... - MethodNotAllowed HTTPStatusCode = "MethodNotAllowed" - // Moved ... - Moved HTTPStatusCode = "Moved" - // MovedPermanently ... - MovedPermanently HTTPStatusCode = "MovedPermanently" - // MultipleChoices ... - MultipleChoices HTTPStatusCode = "MultipleChoices" - // NoContent ... - NoContent HTTPStatusCode = "NoContent" - // NonAuthoritativeInformation ... - NonAuthoritativeInformation HTTPStatusCode = "NonAuthoritativeInformation" - // NotAcceptable ... - NotAcceptable HTTPStatusCode = "NotAcceptable" - // NotFound ... - NotFound HTTPStatusCode = "NotFound" - // NotImplemented ... - NotImplemented HTTPStatusCode = "NotImplemented" - // NotModified ... - NotModified HTTPStatusCode = "NotModified" - // OK ... - OK HTTPStatusCode = "OK" - // PartialContent ... - PartialContent HTTPStatusCode = "PartialContent" - // PaymentRequired ... - PaymentRequired HTTPStatusCode = "PaymentRequired" - // PreconditionFailed ... - PreconditionFailed HTTPStatusCode = "PreconditionFailed" - // ProxyAuthenticationRequired ... - ProxyAuthenticationRequired HTTPStatusCode = "ProxyAuthenticationRequired" - // Redirect ... - Redirect HTTPStatusCode = "Redirect" - // RedirectKeepVerb ... - RedirectKeepVerb HTTPStatusCode = "RedirectKeepVerb" - // RedirectMethod ... - RedirectMethod HTTPStatusCode = "RedirectMethod" - // RequestedRangeNotSatisfiable ... - RequestedRangeNotSatisfiable HTTPStatusCode = "RequestedRangeNotSatisfiable" - // RequestEntityTooLarge ... - RequestEntityTooLarge HTTPStatusCode = "RequestEntityTooLarge" - // RequestTimeout ... - RequestTimeout HTTPStatusCode = "RequestTimeout" - // RequestURITooLong ... - RequestURITooLong HTTPStatusCode = "RequestUriTooLong" - // ResetContent ... - ResetContent HTTPStatusCode = "ResetContent" - // SeeOther ... - SeeOther HTTPStatusCode = "SeeOther" - // ServiceUnavailable ... - ServiceUnavailable HTTPStatusCode = "ServiceUnavailable" - // SwitchingProtocols ... - SwitchingProtocols HTTPStatusCode = "SwitchingProtocols" - // TemporaryRedirect ... - TemporaryRedirect HTTPStatusCode = "TemporaryRedirect" - // Unauthorized ... - Unauthorized HTTPStatusCode = "Unauthorized" - // UnsupportedMediaType ... - UnsupportedMediaType HTTPStatusCode = "UnsupportedMediaType" - // Unused ... - Unused HTTPStatusCode = "Unused" - // UpgradeRequired ... - UpgradeRequired HTTPStatusCode = "UpgradeRequired" - // UseProxy ... - UseProxy HTTPStatusCode = "UseProxy" -) - -// PossibleHTTPStatusCodeValues returns an array of possible values for the HTTPStatusCode const type. -func PossibleHTTPStatusCodeValues() []HTTPStatusCode { - return []HTTPStatusCode{Accepted, Ambiguous, BadGateway, BadRequest, Conflict, Continue, Created, ExpectationFailed, Forbidden, Found, GatewayTimeout, Gone, HTTPVersionNotSupported, InternalServerError, LengthRequired, MethodNotAllowed, Moved, MovedPermanently, MultipleChoices, NoContent, NonAuthoritativeInformation, NotAcceptable, NotFound, NotImplemented, NotModified, OK, PartialContent, PaymentRequired, PreconditionFailed, ProxyAuthenticationRequired, Redirect, RedirectKeepVerb, RedirectMethod, RequestedRangeNotSatisfiable, RequestEntityTooLarge, RequestTimeout, RequestURITooLong, ResetContent, SeeOther, ServiceUnavailable, SwitchingProtocols, TemporaryRedirect, Unauthorized, UnsupportedMediaType, Unused, UpgradeRequired, UseProxy} -} - -// OperationStatus enumerates the values for operation status. -type OperationStatus string - -const ( - // Failed ... - Failed OperationStatus = "Failed" - // InProgress ... - InProgress OperationStatus = "InProgress" - // Succeeded ... - Succeeded OperationStatus = "Succeeded" -) - -// PossibleOperationStatusValues returns an array of possible values for the OperationStatus const type. -func PossibleOperationStatusValues() []OperationStatus { - return []OperationStatus{Failed, InProgress, Succeeded} -} - -// RecordType enumerates the values for record type. -type RecordType string - -const ( - // A ... - A RecordType = "A" - // AAAA ... - AAAA RecordType = "AAAA" - // CNAME ... - CNAME RecordType = "CNAME" - // MX ... - MX RecordType = "MX" - // NS ... - NS RecordType = "NS" - // PTR ... - PTR RecordType = "PTR" - // SOA ... - SOA RecordType = "SOA" - // SRV ... - SRV RecordType = "SRV" - // TXT ... - TXT RecordType = "TXT" -) - -// PossibleRecordTypeValues returns an array of possible values for the RecordType const type. -func PossibleRecordTypeValues() []RecordType { - return []RecordType{A, AAAA, CNAME, MX, NS, PTR, SOA, SRV, TXT} -} - -// AaaaRecord an AAAA record. -type AaaaRecord struct { - // Ipv6Address - The IPv6 address of this AAAA record. - Ipv6Address *string `json:"ipv6Address,omitempty"` -} - -// ARecord an A record. -type ARecord struct { - // Ipv4Address - The IPv4 address of this A record. - Ipv4Address *string `json:"ipv4Address,omitempty"` -} - -// CloudError ... -type CloudError struct { - Error *CloudErrorBody `json:"error,omitempty"` -} - -// CloudErrorBody ... -type CloudErrorBody struct { - Code *string `json:"code,omitempty"` - Message *string `json:"message,omitempty"` - Target *string `json:"target,omitempty"` - Details *[]CloudErrorBody `json:"details,omitempty"` -} - -// CnameRecord a CNAME record. -type CnameRecord struct { - // Cname - The canonical name for this CNAME record. - Cname *string `json:"cname,omitempty"` -} - -// MxRecord an MX record. -type MxRecord struct { - // Preference - The preference value for this MX record. - Preference *int32 `json:"preference,omitempty"` - // Exchange - The domain name of the mail host for this MX record. - Exchange *string `json:"exchange,omitempty"` -} - -// NsRecord an NS record. -type NsRecord struct { - // Nsdname - The name server name for this NS record. - Nsdname *string `json:"nsdname,omitempty"` -} - -// PtrRecord a PTR record. -type PtrRecord struct { - // Ptrdname - The PTR target domain name for this PTR record. - Ptrdname *string `json:"ptrdname,omitempty"` -} - -// RecordSet describes a DNS record set (a collection of DNS records with the same name and type). -type RecordSet struct { - autorest.Response `json:"-"` - // ID - The ID of the record set. - ID *string `json:"id,omitempty"` - // Name - The name of the record set. - Name *string `json:"name,omitempty"` - // Type - The type of the record set. - Type *string `json:"type,omitempty"` - // Etag - The etag of the record set. - Etag *string `json:"etag,omitempty"` - // RecordSetProperties - The properties of the record set. - *RecordSetProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for RecordSet. -func (rs RecordSet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rs.ID != nil { - objectMap["id"] = rs.ID - } - if rs.Name != nil { - objectMap["name"] = rs.Name - } - if rs.Type != nil { - objectMap["type"] = rs.Type - } - if rs.Etag != nil { - objectMap["etag"] = rs.Etag - } - if rs.RecordSetProperties != nil { - objectMap["properties"] = rs.RecordSetProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for RecordSet struct. -func (rs *RecordSet) 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 - } - rs.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rs.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - rs.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - rs.Etag = &etag - } - case "properties": - if v != nil { - var recordSetProperties RecordSetProperties - err = json.Unmarshal(*v, &recordSetProperties) - if err != nil { - return err - } - rs.RecordSetProperties = &recordSetProperties - } - } - } - - return nil -} - -// RecordSetListResult the response to a record set List operation. -type RecordSetListResult struct { - autorest.Response `json:"-"` - // Value - Information about the record sets in the response. - Value *[]RecordSet `json:"value,omitempty"` - // NextLink - The continuation token for the next page of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RecordSetListResultIterator provides access to a complete listing of RecordSet values. -type RecordSetListResultIterator struct { - i int - page RecordSetListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RecordSetListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RecordSetListResultIterator) 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 RecordSetListResultIterator) Response() RecordSetListResult { - 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 RecordSetListResultIterator) Value() RecordSet { - if !iter.page.NotDone() { - return RecordSet{} - } - return iter.page.Values()[iter.i] -} - -// IsEmpty returns true if the ListResult contains no values. -func (rslr RecordSetListResult) IsEmpty() bool { - return rslr.Value == nil || len(*rslr.Value) == 0 -} - -// recordSetListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rslr RecordSetListResult) recordSetListResultPreparer() (*http.Request, error) { - if rslr.NextLink == nil || len(to.String(rslr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rslr.NextLink))) -} - -// RecordSetListResultPage contains a page of RecordSet values. -type RecordSetListResultPage struct { - fn func(RecordSetListResult) (RecordSetListResult, error) - rslr RecordSetListResult -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RecordSetListResultPage) Next() error { - next, err := page.fn(page.rslr) - if err != nil { - return err - } - page.rslr = next - return nil -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RecordSetListResultPage) NotDone() bool { - return !page.rslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RecordSetListResultPage) Response() RecordSetListResult { - return page.rslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RecordSetListResultPage) Values() []RecordSet { - if page.rslr.IsEmpty() { - return nil - } - return *page.rslr.Value -} - -// RecordSetProperties represents the properties of the records in the record set. -type RecordSetProperties struct { - // Metadata - The metadata attached to the record set. - Metadata map[string]*string `json:"metadata"` - // TTL - The TTL (time-to-live) of the records in the record set. - TTL *int64 `json:"TTL,omitempty"` - // ARecords - The list of A records in the record set. - ARecords *[]ARecord `json:"ARecords,omitempty"` - // AaaaRecords - The list of AAAA records in the record set. - AaaaRecords *[]AaaaRecord `json:"AAAARecords,omitempty"` - // MxRecords - The list of MX records in the record set. - MxRecords *[]MxRecord `json:"MXRecords,omitempty"` - // NsRecords - The list of NS records in the record set. - NsRecords *[]NsRecord `json:"NSRecords,omitempty"` - // PtrRecords - The list of PTR records in the record set. - PtrRecords *[]PtrRecord `json:"PTRRecords,omitempty"` - // SrvRecords - The list of SRV records in the record set. - SrvRecords *[]SrvRecord `json:"SRVRecords,omitempty"` - // TxtRecords - The list of TXT records in the record set. - TxtRecords *[]TxtRecord `json:"TXTRecords,omitempty"` - // CnameRecord - The CNAME record in the record set. - CnameRecord *CnameRecord `json:"CNAMERecord,omitempty"` - // SoaRecord - The SOA record in the record set. - SoaRecord *SoaRecord `json:"SOARecord,omitempty"` -} - -// MarshalJSON is the custom marshaler for RecordSetProperties. -func (rsp RecordSetProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rsp.Metadata != nil { - objectMap["metadata"] = rsp.Metadata - } - if rsp.TTL != nil { - objectMap["TTL"] = rsp.TTL - } - if rsp.ARecords != nil { - objectMap["ARecords"] = rsp.ARecords - } - if rsp.AaaaRecords != nil { - objectMap["AAAARecords"] = rsp.AaaaRecords - } - if rsp.MxRecords != nil { - objectMap["MXRecords"] = rsp.MxRecords - } - if rsp.NsRecords != nil { - objectMap["NSRecords"] = rsp.NsRecords - } - if rsp.PtrRecords != nil { - objectMap["PTRRecords"] = rsp.PtrRecords - } - if rsp.SrvRecords != nil { - objectMap["SRVRecords"] = rsp.SrvRecords - } - if rsp.TxtRecords != nil { - objectMap["TXTRecords"] = rsp.TxtRecords - } - if rsp.CnameRecord != nil { - objectMap["CNAMERecord"] = rsp.CnameRecord - } - if rsp.SoaRecord != nil { - objectMap["SOARecord"] = rsp.SoaRecord - } - return json.Marshal(objectMap) -} - -// RecordSetUpdateParameters parameters supplied to update a record set. -type RecordSetUpdateParameters struct { - // RecordSet - Specifies information about the record set being updated. - RecordSet *RecordSet `json:"RecordSet,omitempty"` -} - -// Resource ... -type Resource struct { - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - Resource name. - Name *string `json:"name,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - 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.ID != nil { - objectMap["id"] = r.ID - } - if r.Name != nil { - objectMap["name"] = r.Name - } - if r.Type != nil { - objectMap["type"] = r.Type - } - if r.Location != nil { - objectMap["location"] = r.Location - } - if r.Tags != nil { - objectMap["tags"] = r.Tags - } - return json.Marshal(objectMap) -} - -// SoaRecord an SOA record. -type SoaRecord struct { - // Host - The domain name of the authoritative name server for this SOA record. - Host *string `json:"host,omitempty"` - // Email - The email contact for this SOA record. - Email *string `json:"email,omitempty"` - // SerialNumber - The serial number for this SOA record. - SerialNumber *int64 `json:"serialNumber,omitempty"` - // RefreshTime - The refresh value for this SOA record. - RefreshTime *int64 `json:"refreshTime,omitempty"` - // RetryTime - The retry time for this SOA record. - RetryTime *int64 `json:"retryTime,omitempty"` - // ExpireTime - The expire time for this SOA record. - ExpireTime *int64 `json:"expireTime,omitempty"` - // MinimumTTL - The minimum value for this SOA record. By convention this is used to determine the negative caching duration. - MinimumTTL *int64 `json:"minimumTTL,omitempty"` -} - -// SrvRecord an SRV record. -type SrvRecord struct { - // Priority - The priority value for this SRV record. - Priority *int32 `json:"priority,omitempty"` - // Weight - The weight value for this SRV record. - Weight *int32 `json:"weight,omitempty"` - // Port - The port value for this SRV record. - Port *int32 `json:"port,omitempty"` - // Target - The target domain name for this SRV record. - Target *string `json:"target,omitempty"` -} - -// SubResource ... -type SubResource struct { - // ID - Resource Id. - ID *string `json:"id,omitempty"` -} - -// TxtRecord a TXT record. -type TxtRecord struct { - // Value - The text value of this TXT record. - Value *[]string `json:"value,omitempty"` -} - -// Zone describes a DNS zone. -type Zone struct { - autorest.Response `json:"-"` - // Etag - The etag of the zone. - Etag *string `json:"etag,omitempty"` - // ZoneProperties - The properties of the zone. - *ZoneProperties `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - Resource name. - Name *string `json:"name,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Zone. -func (z Zone) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if z.Etag != nil { - objectMap["etag"] = z.Etag - } - if z.ZoneProperties != nil { - objectMap["properties"] = z.ZoneProperties - } - if z.ID != nil { - objectMap["id"] = z.ID - } - if z.Name != nil { - objectMap["name"] = z.Name - } - if z.Type != nil { - objectMap["type"] = z.Type - } - if z.Location != nil { - objectMap["location"] = z.Location - } - if z.Tags != nil { - objectMap["tags"] = z.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Zone struct. -func (z *Zone) 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 "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - z.Etag = &etag - } - case "properties": - if v != nil { - var zoneProperties ZoneProperties - err = json.Unmarshal(*v, &zoneProperties) - if err != nil { - return err - } - z.ZoneProperties = &zoneProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - z.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - z.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - z.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - z.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - z.Tags = tags - } - } - } - - return nil -} - -// ZoneDeleteResult the response to a Zone Delete operation. -type ZoneDeleteResult struct { - autorest.Response `json:"-"` - // AzureAsyncOperation - Users can perform a Get on Azure-AsyncOperation to get the status of their delete Zone operations. - AzureAsyncOperation *string `json:"azureAsyncOperation,omitempty"` - // Status - Possible values include: 'InProgress', 'Succeeded', 'Failed' - Status OperationStatus `json:"status,omitempty"` - // StatusCode - Possible values include: 'Continue', 'SwitchingProtocols', 'OK', 'Created', 'Accepted', 'NonAuthoritativeInformation', 'NoContent', 'ResetContent', 'PartialContent', 'MultipleChoices', 'Ambiguous', 'MovedPermanently', 'Moved', 'Found', 'Redirect', 'SeeOther', 'RedirectMethod', 'NotModified', 'UseProxy', 'Unused', 'TemporaryRedirect', 'RedirectKeepVerb', 'BadRequest', 'Unauthorized', 'PaymentRequired', 'Forbidden', 'NotFound', 'MethodNotAllowed', 'NotAcceptable', 'ProxyAuthenticationRequired', 'RequestTimeout', 'Conflict', 'Gone', 'LengthRequired', 'PreconditionFailed', 'RequestEntityTooLarge', 'RequestURITooLong', 'UnsupportedMediaType', 'RequestedRangeNotSatisfiable', 'ExpectationFailed', 'UpgradeRequired', 'InternalServerError', 'NotImplemented', 'BadGateway', 'ServiceUnavailable', 'GatewayTimeout', 'HTTPVersionNotSupported' - StatusCode HTTPStatusCode `json:"statusCode,omitempty"` - RequestID *string `json:"requestId,omitempty"` -} - -// ZoneListResult the response to a Zone List or ListAll operation. -type ZoneListResult struct { - autorest.Response `json:"-"` - // Value - Information about the DNS zones. - Value *[]Zone `json:"value,omitempty"` - // NextLink - The continuation token for the next page of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ZoneListResultIterator provides access to a complete listing of Zone values. -type ZoneListResultIterator struct { - i int - page ZoneListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ZoneListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ZoneListResultIterator) 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 ZoneListResultIterator) Response() ZoneListResult { - 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 ZoneListResultIterator) Value() Zone { - if !iter.page.NotDone() { - return Zone{} - } - return iter.page.Values()[iter.i] -} - -// IsEmpty returns true if the ListResult contains no values. -func (zlr ZoneListResult) IsEmpty() bool { - return zlr.Value == nil || len(*zlr.Value) == 0 -} - -// zoneListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (zlr ZoneListResult) zoneListResultPreparer() (*http.Request, error) { - if zlr.NextLink == nil || len(to.String(zlr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(zlr.NextLink))) -} - -// ZoneListResultPage contains a page of Zone values. -type ZoneListResultPage struct { - fn func(ZoneListResult) (ZoneListResult, error) - zlr ZoneListResult -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ZoneListResultPage) Next() error { - next, err := page.fn(page.zlr) - if err != nil { - return err - } - page.zlr = next - return nil -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ZoneListResultPage) NotDone() bool { - return !page.zlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ZoneListResultPage) Response() ZoneListResult { - return page.zlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ZoneListResultPage) Values() []Zone { - if page.zlr.IsEmpty() { - return nil - } - return *page.zlr.Value -} - -// ZoneProperties represents the properties of the zone. -type ZoneProperties struct { - // MaxNumberOfRecordSets - The maximum number of record sets that can be created in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - MaxNumberOfRecordSets *int64 `json:"maxNumberOfRecordSets,omitempty"` - // NumberOfRecordSets - The current number of record sets in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - NumberOfRecordSets *int64 `json:"numberOfRecordSets,omitempty"` - // NameServers - The name servers for this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - NameServers *[]string `json:"nameServers,omitempty"` -} - -// ZonesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type ZonesDeleteFuture struct { - azure.Future -} - -// Result returns the result of the asynchronous operation. -// If the operation has not completed it will return an error. -func (future *ZonesDeleteFuture) Result(client ZonesClient) (zdr ZoneDeleteResult, err error) { - var done bool - done, err = future.Done(client) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - err = azure.NewAsyncOpIncompleteError("dns.ZonesDeleteFuture") - return - } - sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if zdr.Response.Response, err = future.GetResult(sender); err == nil && zdr.Response.Response.StatusCode != http.StatusNoContent { - zdr, err = client.DeleteResponder(zdr.Response.Response) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesDeleteFuture", "Result", zdr.Response.Response, "Failure responding to request") - } - } - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/recordsets.go b/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/recordsets.go deleted file mode 100644 index e3d2bc1160aac..0000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/recordsets.go +++ /dev/null @@ -1,616 +0,0 @@ -package dns - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "net/http" -) - -// RecordSetsClient is the the DNS Management Client. -type RecordSetsClient struct { - BaseClient -} - -// NewRecordSetsClient creates an instance of the RecordSetsClient client. -func NewRecordSetsClient(subscriptionID string) RecordSetsClient { - return NewRecordSetsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRecordSetsClientWithBaseURI creates an instance of the RecordSetsClient client. -func NewRecordSetsClientWithBaseURI(baseURI string, subscriptionID string) RecordSetsClient { - return RecordSetsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a record set within a DNS zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// relativeRecordSetName - the name of the record set, relative to the name of the zone. -// recordType - the type of DNS record in this record set. Record sets of type SOA can be updated but not -// created (they are created when the DNS zone is created). -// parameters - parameters supplied to the CreateOrUpdate operation. -// ifMatch - the etag of the record set. Omit this value to always overwrite the current record set. Specify -// the last-seen etag value to prevent accidentally overwritting any concurrent changes. -// ifNoneMatch - set to '*' to allow a new record set to be created, but to prevent updating an existing record -// set. Other values will be ignored. -func (client RecordSetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string, ifNoneMatch string) (result RecordSet, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RecordSetsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string, ifNoneMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2016-04-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", 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 RecordSetsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) CreateOrUpdateResponder(resp *http.Response) (result RecordSet, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a record set from a DNS zone. This operation cannot be undone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// relativeRecordSetName - the name of the record set, relative to the name of the zone. -// recordType - the type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are -// deleted when the DNS zone is deleted). -// ifMatch - the etag of the record set. Omit this value to always delete the current record set. Specify the -// last-seen etag value to prevent accidentally deleting any concurrent changes. -func (client RecordSetsClient) Delete(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, ifMatch string) (result autorest.Response, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Delete", resp, "Failure responding to request") - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RecordSetsClient) DeletePreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2016-04-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", pathParameters), - 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)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a record set. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// relativeRecordSetName - the name of the record set, relative to the name of the zone. -// recordType - the type of DNS record in this record set. -func (client RecordSetsClient) Get(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType) (result RecordSet, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client RecordSetsClient) GetPreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2016-04-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", 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 RecordSetsClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) GetResponder(resp *http.Response) (result RecordSet, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByDNSZone lists all record sets in a DNS zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// top - the maximum number of record sets to return. If not specified, returns up to 100 record sets. -// recordsetnamesuffix - the suffix label of the record set name that has to be used to filter the record set -// enumerations. If this parameter is specified, Enumeration will return only records that end with -// . -func (client RecordSetsClient) ListByDNSZone(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordsetnamesuffix string) (result RecordSetListResultPage, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "ListByDNSZone", err.Error()) - } - - result.fn = client.listByDNSZoneNextResults - req, err := client.ListByDNSZonePreparer(ctx, resourceGroupName, zoneName, top, recordsetnamesuffix) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByDNSZone", nil, "Failure preparing request") - return - } - - resp, err := client.ListByDNSZoneSender(req) - if err != nil { - result.rslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByDNSZone", resp, "Failure sending request") - return - } - - result.rslr, err = client.ListByDNSZoneResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByDNSZone", resp, "Failure responding to request") - } - - return -} - -// ListByDNSZonePreparer prepares the ListByDNSZone request. -func (client RecordSetsClient) ListByDNSZonePreparer(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordsetnamesuffix string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2016-04-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(recordsetnamesuffix) > 0 { - queryParameters["$recordsetnamesuffix"] = autorest.Encode("query", recordsetnamesuffix) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByDNSZoneSender sends the ListByDNSZone request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) ListByDNSZoneSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListByDNSZoneResponder handles the response to the ListByDNSZone request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) ListByDNSZoneResponder(resp *http.Response) (result RecordSetListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByDNSZoneNextResults retrieves the next set of results, if any. -func (client RecordSetsClient) listByDNSZoneNextResults(lastResults RecordSetListResult) (result RecordSetListResult, err error) { - req, err := lastResults.recordSetListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByDNSZoneNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByDNSZoneSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByDNSZoneNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByDNSZoneResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByDNSZoneNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByDNSZoneComplete enumerates all values, automatically crossing page boundaries as required. -func (client RecordSetsClient) ListByDNSZoneComplete(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordsetnamesuffix string) (result RecordSetListResultIterator, err error) { - result.page, err = client.ListByDNSZone(ctx, resourceGroupName, zoneName, top, recordsetnamesuffix) - return -} - -// ListByType lists the record sets of a specified type in a DNS zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// recordType - the type of record sets to enumerate. -// top - the maximum number of record sets to return. If not specified, returns up to 100 record sets. -// recordsetnamesuffix - the suffix label of the record set name that has to be used to filter the record set -// enumerations. If this parameter is specified, Enumeration will return only records that end with -// . -func (client RecordSetsClient) ListByType(ctx context.Context, resourceGroupName string, zoneName string, recordType RecordType, top *int32, recordsetnamesuffix string) (result RecordSetListResultPage, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "ListByType", err.Error()) - } - - result.fn = client.listByTypeNextResults - req, err := client.ListByTypePreparer(ctx, resourceGroupName, zoneName, recordType, top, recordsetnamesuffix) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByType", nil, "Failure preparing request") - return - } - - resp, err := client.ListByTypeSender(req) - if err != nil { - result.rslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByType", resp, "Failure sending request") - return - } - - result.rslr, err = client.ListByTypeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByType", resp, "Failure responding to request") - } - - return -} - -// ListByTypePreparer prepares the ListByType request. -func (client RecordSetsClient) ListByTypePreparer(ctx context.Context, resourceGroupName string, zoneName string, recordType RecordType, top *int32, recordsetnamesuffix string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2016-04-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(recordsetnamesuffix) > 0 { - queryParameters["$recordsetnamesuffix"] = autorest.Encode("query", recordsetnamesuffix) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByTypeSender sends the ListByType request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) ListByTypeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListByTypeResponder handles the response to the ListByType request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) ListByTypeResponder(resp *http.Response) (result RecordSetListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByTypeNextResults retrieves the next set of results, if any. -func (client RecordSetsClient) listByTypeNextResults(lastResults RecordSetListResult) (result RecordSetListResult, err error) { - req, err := lastResults.recordSetListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByTypeNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByTypeSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByTypeNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByTypeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByTypeNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByTypeComplete enumerates all values, automatically crossing page boundaries as required. -func (client RecordSetsClient) ListByTypeComplete(ctx context.Context, resourceGroupName string, zoneName string, recordType RecordType, top *int32, recordsetnamesuffix string) (result RecordSetListResultIterator, err error) { - result.page, err = client.ListByType(ctx, resourceGroupName, zoneName, recordType, top, recordsetnamesuffix) - return -} - -// Update updates a record set within a DNS zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// relativeRecordSetName - the name of the record set, relative to the name of the zone. -// recordType - the type of DNS record in this record set. -// parameters - parameters supplied to the Update operation. -// ifMatch - the etag of the record set. Omit this value to always overwrite the current record set. Specify -// the last-seen etag value to prevent accidentally overwritting concurrent changes. -func (client RecordSetsClient) Update(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string) (result RecordSet, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Update", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Update", resp, "Failure sending request") - return - } - - result, err = client.UpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Update", resp, "Failure responding to request") - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client RecordSetsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2016-04-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", 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 RecordSetsClient) UpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) UpdateResponder(resp *http.Response) (result RecordSet, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/version.go deleted file mode 100644 index 23497fd198d1f..0000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/version.go +++ /dev/null @@ -1,30 +0,0 @@ -package dns - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// UserAgent returns the UserAgent string to use when sending http.Requests. -func UserAgent() string { - return "Azure-SDK-For-Go/" + version.Number + " dns/2016-04-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/dns/mgmt/2016-04-01/dns/zones.go b/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/zones.go deleted file mode 100644 index 5e17378320f6f..0000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/zones.go +++ /dev/null @@ -1,492 +0,0 @@ -package dns - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "net/http" -) - -// ZonesClient is the the DNS Management Client. -type ZonesClient struct { - BaseClient -} - -// NewZonesClient creates an instance of the ZonesClient client. -func NewZonesClient(subscriptionID string) ZonesClient { - return NewZonesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewZonesClientWithBaseURI creates an instance of the ZonesClient client. -func NewZonesClientWithBaseURI(baseURI string, subscriptionID string) ZonesClient { - return ZonesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a DNS zone. Does not modify DNS records within the zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// parameters - parameters supplied to the CreateOrUpdate operation. -// ifMatch - the etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the -// last-seen etag value to prevent accidentally overwritting any concurrent changes. -// ifNoneMatch - set to '*' to allow a new DNS zone to be created, but to prevent updating an existing zone. -// Other values will be ignored. -func (client ZonesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, zoneName string, parameters Zone, ifMatch string, ifNoneMatch string) (result Zone, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.ZonesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, zoneName, parameters, ifMatch, ifNoneMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ZonesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, zoneName string, parameters Zone, ifMatch string, ifNoneMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2016-04-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", 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 ZonesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ZonesClient) CreateOrUpdateResponder(resp *http.Response) (result Zone, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be -// undone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// ifMatch - the etag of the DNS zone. Omit this value to always delete the current zone. Specify the last-seen -// etag value to prevent accidentally deleting any concurrent changes. -func (client ZonesClient) Delete(ctx context.Context, resourceGroupName string, zoneName string, ifMatch string) (result ZonesDeleteFuture, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.ZonesClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, zoneName, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ZonesClient) DeletePreparer(ctx context.Context, resourceGroupName string, zoneName string, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2016-04-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", pathParameters), - 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)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ZonesClient) DeleteSender(req *http.Request) (future ZonesDeleteFuture, err error) { - var resp *http.Response - resp, err = autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) - if err != nil { - return - } - future.Future, err = azure.NewFutureFromResponse(resp) - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ZonesClient) DeleteResponder(resp *http.Response) (result ZoneDeleteResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Get gets a DNS zone. Retrieves the zone properties, but not the record sets within the zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -func (client ZonesClient) Get(ctx context.Context, resourceGroupName string, zoneName string) (result Zone, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.ZonesClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, zoneName) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client ZonesClient) GetPreparer(ctx context.Context, resourceGroupName string, zoneName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2016-04-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", 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 ZonesClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ZonesClient) GetResponder(resp *http.Response) (result Zone, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists the DNS zones in all resource groups in a subscription. -// Parameters: -// top - the maximum number of DNS zones to return. If not specified, returns up to 100 zones. -func (client ZonesClient) List(ctx context.Context, top *int32) (result ZoneListResultPage, err error) { - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, top) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.zlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "List", resp, "Failure sending request") - return - } - - result.zlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "List", resp, "Failure responding to request") - } - - return -} - -// ListPreparer prepares the List request. -func (client ZonesClient) ListPreparer(ctx context.Context, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2016-04-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.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones", 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 ZonesClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ZonesClient) ListResponder(resp *http.Response) (result ZoneListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ZonesClient) listNextResults(lastResults ZoneListResult) (result ZoneListResult, err error) { - req, err := lastResults.zoneListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.ZonesClient", "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, "dns.ZonesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ZonesClient) ListComplete(ctx context.Context, top *int32) (result ZoneListResultIterator, err error) { - result.page, err = client.List(ctx, top) - return -} - -// ListByResourceGroup lists the DNS zones within a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// top - the maximum number of record sets to return. If not specified, returns up to 100 record sets. -func (client ZonesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, top *int32) (result ZoneListResultPage, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.ZonesClient", "ListByResourceGroup", err.Error()) - } - - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, top) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.zlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.zlr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "ListByResourceGroup", resp, "Failure responding to request") - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ZonesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2016-04-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.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones", 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 ZonesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ZonesClient) ListByResourceGroupResponder(resp *http.Response) (result ZoneListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client ZonesClient) listByResourceGroupNextResults(lastResults ZoneListResult) (result ZoneListResult, err error) { - req, err := lastResults.zoneListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.ZonesClient", "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, "dns.ZonesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ZonesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, top *int32) (result ZoneListResultIterator, err error) { - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName, top) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/client.go deleted file mode 100644 index a89f2dd318a12..0000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/client.go +++ /dev/null @@ -1,51 +0,0 @@ -// Package dns implements the Azure ARM Dns service API version 2017-10-01. -// -// The DNS Management Client. -package dns - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/Azure/go-autorest/autorest" -) - -const ( - // DefaultBaseURI is the default URI used for the service Dns - DefaultBaseURI = "https://management.azure.com" -) - -// BaseClient is the base client for Dns. -type BaseClient struct { - autorest.Client - BaseURI string - SubscriptionID string -} - -// New creates an instance of the BaseClient client. -func New(subscriptionID string) BaseClient { - return NewWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewWithBaseURI creates an instance of the BaseClient client. -func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { - return BaseClient{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: baseURI, - SubscriptionID: subscriptionID, - } -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/models.go deleted file mode 100644 index 9d292001a329d..0000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/models.go +++ /dev/null @@ -1,752 +0,0 @@ -package dns - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "encoding/json" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/to" - "net/http" -) - -// RecordType enumerates the values for record type. -type RecordType string - -const ( - // A ... - A RecordType = "A" - // AAAA ... - AAAA RecordType = "AAAA" - // CAA ... - CAA RecordType = "CAA" - // CNAME ... - CNAME RecordType = "CNAME" - // MX ... - MX RecordType = "MX" - // NS ... - NS RecordType = "NS" - // PTR ... - PTR RecordType = "PTR" - // SOA ... - SOA RecordType = "SOA" - // SRV ... - SRV RecordType = "SRV" - // TXT ... - TXT RecordType = "TXT" -) - -// PossibleRecordTypeValues returns an array of possible values for the RecordType const type. -func PossibleRecordTypeValues() []RecordType { - return []RecordType{A, AAAA, CAA, CNAME, MX, NS, PTR, SOA, SRV, TXT} -} - -// AaaaRecord an AAAA record. -type AaaaRecord struct { - // Ipv6Address - The IPv6 address of this AAAA record. - Ipv6Address *string `json:"ipv6Address,omitempty"` -} - -// ARecord an A record. -type ARecord struct { - // Ipv4Address - The IPv4 address of this A record. - Ipv4Address *string `json:"ipv4Address,omitempty"` -} - -// CaaRecord a CAA record. -type CaaRecord struct { - // Flags - The flags for this CAA record as an integer between 0 and 255. - Flags *int32 `json:"flags,omitempty"` - // Tag - The tag for this CAA record. - Tag *string `json:"tag,omitempty"` - // Value - The value for this CAA record. - Value *string `json:"value,omitempty"` -} - -// CloudError an error message -type CloudError struct { - // Error - The error message body - Error *CloudErrorBody `json:"error,omitempty"` -} - -// CloudErrorBody the body of an error message -type CloudErrorBody struct { - // Code - The error code - Code *string `json:"code,omitempty"` - // Message - A description of what caused the error - Message *string `json:"message,omitempty"` - // Target - The target resource of the error message - Target *string `json:"target,omitempty"` - // Details - Extra error information - Details *[]CloudErrorBody `json:"details,omitempty"` -} - -// CnameRecord a CNAME record. -type CnameRecord struct { - // Cname - The canonical name for this CNAME record. - Cname *string `json:"cname,omitempty"` -} - -// MxRecord an MX record. -type MxRecord struct { - // Preference - The preference value for this MX record. - Preference *int32 `json:"preference,omitempty"` - // Exchange - The domain name of the mail host for this MX record. - Exchange *string `json:"exchange,omitempty"` -} - -// NsRecord an NS record. -type NsRecord struct { - // Nsdname - The name server name for this NS record. - Nsdname *string `json:"nsdname,omitempty"` -} - -// PtrRecord a PTR record. -type PtrRecord struct { - // Ptrdname - The PTR target domain name for this PTR record. - Ptrdname *string `json:"ptrdname,omitempty"` -} - -// RecordSet describes a DNS record set (a collection of DNS records with the same name and type). -type RecordSet struct { - autorest.Response `json:"-"` - // ID - The ID of the record set. - ID *string `json:"id,omitempty"` - // Name - The name of the record set. - Name *string `json:"name,omitempty"` - // Type - The type of the record set. - Type *string `json:"type,omitempty"` - // Etag - The etag of the record set. - Etag *string `json:"etag,omitempty"` - // RecordSetProperties - The properties of the record set. - *RecordSetProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for RecordSet. -func (rs RecordSet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rs.ID != nil { - objectMap["id"] = rs.ID - } - if rs.Name != nil { - objectMap["name"] = rs.Name - } - if rs.Type != nil { - objectMap["type"] = rs.Type - } - if rs.Etag != nil { - objectMap["etag"] = rs.Etag - } - if rs.RecordSetProperties != nil { - objectMap["properties"] = rs.RecordSetProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for RecordSet struct. -func (rs *RecordSet) 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 - } - rs.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rs.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - rs.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - rs.Etag = &etag - } - case "properties": - if v != nil { - var recordSetProperties RecordSetProperties - err = json.Unmarshal(*v, &recordSetProperties) - if err != nil { - return err - } - rs.RecordSetProperties = &recordSetProperties - } - } - } - - return nil -} - -// RecordSetListResult the response to a record set List operation. -type RecordSetListResult struct { - autorest.Response `json:"-"` - // Value - Information about the record sets in the response. - Value *[]RecordSet `json:"value,omitempty"` - // NextLink - The continuation token for the next page of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RecordSetListResultIterator provides access to a complete listing of RecordSet values. -type RecordSetListResultIterator struct { - i int - page RecordSetListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RecordSetListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RecordSetListResultIterator) 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 RecordSetListResultIterator) Response() RecordSetListResult { - 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 RecordSetListResultIterator) Value() RecordSet { - if !iter.page.NotDone() { - return RecordSet{} - } - return iter.page.Values()[iter.i] -} - -// IsEmpty returns true if the ListResult contains no values. -func (rslr RecordSetListResult) IsEmpty() bool { - return rslr.Value == nil || len(*rslr.Value) == 0 -} - -// recordSetListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rslr RecordSetListResult) recordSetListResultPreparer() (*http.Request, error) { - if rslr.NextLink == nil || len(to.String(rslr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rslr.NextLink))) -} - -// RecordSetListResultPage contains a page of RecordSet values. -type RecordSetListResultPage struct { - fn func(RecordSetListResult) (RecordSetListResult, error) - rslr RecordSetListResult -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RecordSetListResultPage) Next() error { - next, err := page.fn(page.rslr) - if err != nil { - return err - } - page.rslr = next - return nil -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RecordSetListResultPage) NotDone() bool { - return !page.rslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RecordSetListResultPage) Response() RecordSetListResult { - return page.rslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RecordSetListResultPage) Values() []RecordSet { - if page.rslr.IsEmpty() { - return nil - } - return *page.rslr.Value -} - -// RecordSetProperties represents the properties of the records in the record set. -type RecordSetProperties struct { - // Metadata - The metadata attached to the record set. - Metadata map[string]*string `json:"metadata"` - // TTL - The TTL (time-to-live) of the records in the record set. - TTL *int64 `json:"TTL,omitempty"` - // Fqdn - Fully qualified domain name of the record set. - Fqdn *string `json:"fqdn,omitempty"` - // ARecords - The list of A records in the record set. - ARecords *[]ARecord `json:"ARecords,omitempty"` - // AaaaRecords - The list of AAAA records in the record set. - AaaaRecords *[]AaaaRecord `json:"AAAARecords,omitempty"` - // MxRecords - The list of MX records in the record set. - MxRecords *[]MxRecord `json:"MXRecords,omitempty"` - // NsRecords - The list of NS records in the record set. - NsRecords *[]NsRecord `json:"NSRecords,omitempty"` - // PtrRecords - The list of PTR records in the record set. - PtrRecords *[]PtrRecord `json:"PTRRecords,omitempty"` - // SrvRecords - The list of SRV records in the record set. - SrvRecords *[]SrvRecord `json:"SRVRecords,omitempty"` - // TxtRecords - The list of TXT records in the record set. - TxtRecords *[]TxtRecord `json:"TXTRecords,omitempty"` - // CnameRecord - The CNAME record in the record set. - CnameRecord *CnameRecord `json:"CNAMERecord,omitempty"` - // SoaRecord - The SOA record in the record set. - SoaRecord *SoaRecord `json:"SOARecord,omitempty"` - // CaaRecords - The list of CAA records in the record set. - CaaRecords *[]CaaRecord `json:"caaRecords,omitempty"` -} - -// MarshalJSON is the custom marshaler for RecordSetProperties. -func (rsp RecordSetProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rsp.Metadata != nil { - objectMap["metadata"] = rsp.Metadata - } - if rsp.TTL != nil { - objectMap["TTL"] = rsp.TTL - } - if rsp.Fqdn != nil { - objectMap["fqdn"] = rsp.Fqdn - } - if rsp.ARecords != nil { - objectMap["ARecords"] = rsp.ARecords - } - if rsp.AaaaRecords != nil { - objectMap["AAAARecords"] = rsp.AaaaRecords - } - if rsp.MxRecords != nil { - objectMap["MXRecords"] = rsp.MxRecords - } - if rsp.NsRecords != nil { - objectMap["NSRecords"] = rsp.NsRecords - } - if rsp.PtrRecords != nil { - objectMap["PTRRecords"] = rsp.PtrRecords - } - if rsp.SrvRecords != nil { - objectMap["SRVRecords"] = rsp.SrvRecords - } - if rsp.TxtRecords != nil { - objectMap["TXTRecords"] = rsp.TxtRecords - } - if rsp.CnameRecord != nil { - objectMap["CNAMERecord"] = rsp.CnameRecord - } - if rsp.SoaRecord != nil { - objectMap["SOARecord"] = rsp.SoaRecord - } - if rsp.CaaRecords != nil { - objectMap["caaRecords"] = rsp.CaaRecords - } - return json.Marshal(objectMap) -} - -// RecordSetUpdateParameters parameters supplied to update a record set. -type RecordSetUpdateParameters struct { - // RecordSet - Specifies information about the record set being updated. - RecordSet *RecordSet `json:"RecordSet,omitempty"` -} - -// Resource common properties of an Azure Resource Manager resource -type Resource struct { - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - Resource name. - Name *string `json:"name,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - 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.ID != nil { - objectMap["id"] = r.ID - } - if r.Name != nil { - objectMap["name"] = r.Name - } - if r.Type != nil { - objectMap["type"] = r.Type - } - if r.Location != nil { - objectMap["location"] = r.Location - } - if r.Tags != nil { - objectMap["tags"] = r.Tags - } - return json.Marshal(objectMap) -} - -// SoaRecord an SOA record. -type SoaRecord struct { - // Host - The domain name of the authoritative name server for this SOA record. - Host *string `json:"host,omitempty"` - // Email - The email contact for this SOA record. - Email *string `json:"email,omitempty"` - // SerialNumber - The serial number for this SOA record. - SerialNumber *int64 `json:"serialNumber,omitempty"` - // RefreshTime - The refresh value for this SOA record. - RefreshTime *int64 `json:"refreshTime,omitempty"` - // RetryTime - The retry time for this SOA record. - RetryTime *int64 `json:"retryTime,omitempty"` - // ExpireTime - The expire time for this SOA record. - ExpireTime *int64 `json:"expireTime,omitempty"` - // MinimumTTL - The minimum value for this SOA record. By convention this is used to determine the negative caching duration. - MinimumTTL *int64 `json:"minimumTTL,omitempty"` -} - -// SrvRecord an SRV record. -type SrvRecord struct { - // Priority - The priority value for this SRV record. - Priority *int32 `json:"priority,omitempty"` - // Weight - The weight value for this SRV record. - Weight *int32 `json:"weight,omitempty"` - // Port - The port value for this SRV record. - Port *int32 `json:"port,omitempty"` - // Target - The target domain name for this SRV record. - Target *string `json:"target,omitempty"` -} - -// SubResource a reference to a another resource -type SubResource struct { - // ID - Resource Id. - ID *string `json:"id,omitempty"` -} - -// TxtRecord a TXT record. -type TxtRecord struct { - // Value - The text value of this TXT record. - Value *[]string `json:"value,omitempty"` -} - -// Zone describes a DNS zone. -type Zone struct { - autorest.Response `json:"-"` - // Etag - The etag of the zone. - Etag *string `json:"etag,omitempty"` - // ZoneProperties - The properties of the zone. - *ZoneProperties `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - Resource name. - Name *string `json:"name,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Zone. -func (z Zone) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if z.Etag != nil { - objectMap["etag"] = z.Etag - } - if z.ZoneProperties != nil { - objectMap["properties"] = z.ZoneProperties - } - if z.ID != nil { - objectMap["id"] = z.ID - } - if z.Name != nil { - objectMap["name"] = z.Name - } - if z.Type != nil { - objectMap["type"] = z.Type - } - if z.Location != nil { - objectMap["location"] = z.Location - } - if z.Tags != nil { - objectMap["tags"] = z.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Zone struct. -func (z *Zone) 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 "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - z.Etag = &etag - } - case "properties": - if v != nil { - var zoneProperties ZoneProperties - err = json.Unmarshal(*v, &zoneProperties) - if err != nil { - return err - } - z.ZoneProperties = &zoneProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - z.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - z.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - z.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - z.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - z.Tags = tags - } - } - } - - return nil -} - -// ZoneListResult the response to a Zone List or ListAll operation. -type ZoneListResult struct { - autorest.Response `json:"-"` - // Value - Information about the DNS zones. - Value *[]Zone `json:"value,omitempty"` - // NextLink - The continuation token for the next page of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ZoneListResultIterator provides access to a complete listing of Zone values. -type ZoneListResultIterator struct { - i int - page ZoneListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ZoneListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ZoneListResultIterator) 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 ZoneListResultIterator) Response() ZoneListResult { - 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 ZoneListResultIterator) Value() Zone { - if !iter.page.NotDone() { - return Zone{} - } - return iter.page.Values()[iter.i] -} - -// IsEmpty returns true if the ListResult contains no values. -func (zlr ZoneListResult) IsEmpty() bool { - return zlr.Value == nil || len(*zlr.Value) == 0 -} - -// zoneListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (zlr ZoneListResult) zoneListResultPreparer() (*http.Request, error) { - if zlr.NextLink == nil || len(to.String(zlr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(zlr.NextLink))) -} - -// ZoneListResultPage contains a page of Zone values. -type ZoneListResultPage struct { - fn func(ZoneListResult) (ZoneListResult, error) - zlr ZoneListResult -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ZoneListResultPage) Next() error { - next, err := page.fn(page.zlr) - if err != nil { - return err - } - page.zlr = next - return nil -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ZoneListResultPage) NotDone() bool { - return !page.zlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ZoneListResultPage) Response() ZoneListResult { - return page.zlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ZoneListResultPage) Values() []Zone { - if page.zlr.IsEmpty() { - return nil - } - return *page.zlr.Value -} - -// ZoneProperties represents the properties of the zone. -type ZoneProperties struct { - // MaxNumberOfRecordSets - The maximum number of record sets that can be created in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - MaxNumberOfRecordSets *int64 `json:"maxNumberOfRecordSets,omitempty"` - // NumberOfRecordSets - The current number of record sets in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - NumberOfRecordSets *int64 `json:"numberOfRecordSets,omitempty"` - // NameServers - The name servers for this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - NameServers *[]string `json:"nameServers,omitempty"` -} - -// ZonesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type ZonesDeleteFuture struct { - azure.Future -} - -// Result returns the result of the asynchronous operation. -// If the operation has not completed it will return an error. -func (future *ZonesDeleteFuture) Result(client ZonesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.Done(client) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - err = azure.NewAsyncOpIncompleteError("dns.ZonesDeleteFuture") - return - } - ar.Response = future.Response() - return -} - -// ZoneUpdate describes a request to update a DNS zone. -type ZoneUpdate struct { - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for ZoneUpdate. -func (zu ZoneUpdate) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if zu.Tags != nil { - objectMap["tags"] = zu.Tags - } - return json.Marshal(objectMap) -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/recordsets.go b/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/recordsets.go deleted file mode 100644 index 1210b701d3595..0000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/recordsets.go +++ /dev/null @@ -1,729 +0,0 @@ -package dns - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "net/http" -) - -// RecordSetsClient is the the DNS Management Client. -type RecordSetsClient struct { - BaseClient -} - -// NewRecordSetsClient creates an instance of the RecordSetsClient client. -func NewRecordSetsClient(subscriptionID string) RecordSetsClient { - return NewRecordSetsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRecordSetsClientWithBaseURI creates an instance of the RecordSetsClient client. -func NewRecordSetsClientWithBaseURI(baseURI string, subscriptionID string) RecordSetsClient { - return RecordSetsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a record set within a DNS zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// relativeRecordSetName - the name of the record set, relative to the name of the zone. -// recordType - the type of DNS record in this record set. Record sets of type SOA can be updated but not -// created (they are created when the DNS zone is created). -// parameters - parameters supplied to the CreateOrUpdate operation. -// ifMatch - the etag of the record set. Omit this value to always overwrite the current record set. Specify -// the last-seen etag value to prevent accidentally overwritting any concurrent changes. -// ifNoneMatch - set to '*' to allow a new record set to be created, but to prevent updating an existing record -// set. Other values will be ignored. -func (client RecordSetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string, ifNoneMatch string) (result RecordSet, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RecordSetsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string, ifNoneMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-10-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.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", 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 RecordSetsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) CreateOrUpdateResponder(resp *http.Response) (result RecordSet, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a record set from a DNS zone. This operation cannot be undone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// relativeRecordSetName - the name of the record set, relative to the name of the zone. -// recordType - the type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are -// deleted when the DNS zone is deleted). -// ifMatch - the etag of the record set. Omit this value to always delete the current record set. Specify the -// last-seen etag value to prevent accidentally deleting any concurrent changes. -func (client RecordSetsClient) Delete(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, ifMatch string) (result autorest.Response, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Delete", resp, "Failure responding to request") - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RecordSetsClient) DeletePreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-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.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", pathParameters), - 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)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a record set. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// relativeRecordSetName - the name of the record set, relative to the name of the zone. -// recordType - the type of DNS record in this record set. -func (client RecordSetsClient) Get(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType) (result RecordSet, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client RecordSetsClient) GetPreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-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.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", 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 RecordSetsClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) GetResponder(resp *http.Response) (result RecordSet, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListAllByDNSZone lists all record sets in a DNS zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// top - the maximum number of record sets to return. If not specified, returns up to 100 record sets. -// recordSetNameSuffix - the suffix label of the record set name that has to be used to filter the record set -// enumerations. If this parameter is specified, Enumeration will return only records that end with -// . -func (client RecordSetsClient) ListAllByDNSZone(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordSetNameSuffix string) (result RecordSetListResultPage, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "ListAllByDNSZone", err.Error()) - } - - result.fn = client.listAllByDNSZoneNextResults - req, err := client.ListAllByDNSZonePreparer(ctx, resourceGroupName, zoneName, top, recordSetNameSuffix) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListAllByDNSZone", nil, "Failure preparing request") - return - } - - resp, err := client.ListAllByDNSZoneSender(req) - if err != nil { - result.rslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListAllByDNSZone", resp, "Failure sending request") - return - } - - result.rslr, err = client.ListAllByDNSZoneResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListAllByDNSZone", resp, "Failure responding to request") - } - - return -} - -// ListAllByDNSZonePreparer prepares the ListAllByDNSZone request. -func (client RecordSetsClient) ListAllByDNSZonePreparer(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordSetNameSuffix string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(recordSetNameSuffix) > 0 { - queryParameters["$recordsetnamesuffix"] = autorest.Encode("query", recordSetNameSuffix) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/all", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListAllByDNSZoneSender sends the ListAllByDNSZone request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) ListAllByDNSZoneSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListAllByDNSZoneResponder handles the response to the ListAllByDNSZone request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) ListAllByDNSZoneResponder(resp *http.Response) (result RecordSetListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listAllByDNSZoneNextResults retrieves the next set of results, if any. -func (client RecordSetsClient) listAllByDNSZoneNextResults(lastResults RecordSetListResult) (result RecordSetListResult, err error) { - req, err := lastResults.recordSetListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listAllByDNSZoneNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListAllByDNSZoneSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listAllByDNSZoneNextResults", resp, "Failure sending next results request") - } - result, err = client.ListAllByDNSZoneResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listAllByDNSZoneNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListAllByDNSZoneComplete enumerates all values, automatically crossing page boundaries as required. -func (client RecordSetsClient) ListAllByDNSZoneComplete(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordSetNameSuffix string) (result RecordSetListResultIterator, err error) { - result.page, err = client.ListAllByDNSZone(ctx, resourceGroupName, zoneName, top, recordSetNameSuffix) - return -} - -// ListByDNSZone lists all record sets in a DNS zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// top - the maximum number of record sets to return. If not specified, returns up to 100 record sets. -// recordsetnamesuffix - the suffix label of the record set name that has to be used to filter the record set -// enumerations. If this parameter is specified, Enumeration will return only records that end with -// . -func (client RecordSetsClient) ListByDNSZone(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordsetnamesuffix string) (result RecordSetListResultPage, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "ListByDNSZone", err.Error()) - } - - result.fn = client.listByDNSZoneNextResults - req, err := client.ListByDNSZonePreparer(ctx, resourceGroupName, zoneName, top, recordsetnamesuffix) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByDNSZone", nil, "Failure preparing request") - return - } - - resp, err := client.ListByDNSZoneSender(req) - if err != nil { - result.rslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByDNSZone", resp, "Failure sending request") - return - } - - result.rslr, err = client.ListByDNSZoneResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByDNSZone", resp, "Failure responding to request") - } - - return -} - -// ListByDNSZonePreparer prepares the ListByDNSZone request. -func (client RecordSetsClient) ListByDNSZonePreparer(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordsetnamesuffix string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(recordsetnamesuffix) > 0 { - queryParameters["$recordsetnamesuffix"] = autorest.Encode("query", recordsetnamesuffix) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByDNSZoneSender sends the ListByDNSZone request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) ListByDNSZoneSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListByDNSZoneResponder handles the response to the ListByDNSZone request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) ListByDNSZoneResponder(resp *http.Response) (result RecordSetListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByDNSZoneNextResults retrieves the next set of results, if any. -func (client RecordSetsClient) listByDNSZoneNextResults(lastResults RecordSetListResult) (result RecordSetListResult, err error) { - req, err := lastResults.recordSetListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByDNSZoneNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByDNSZoneSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByDNSZoneNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByDNSZoneResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByDNSZoneNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByDNSZoneComplete enumerates all values, automatically crossing page boundaries as required. -func (client RecordSetsClient) ListByDNSZoneComplete(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordsetnamesuffix string) (result RecordSetListResultIterator, err error) { - result.page, err = client.ListByDNSZone(ctx, resourceGroupName, zoneName, top, recordsetnamesuffix) - return -} - -// ListByType lists the record sets of a specified type in a DNS zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// recordType - the type of record sets to enumerate. -// top - the maximum number of record sets to return. If not specified, returns up to 100 record sets. -// recordsetnamesuffix - the suffix label of the record set name that has to be used to filter the record set -// enumerations. If this parameter is specified, Enumeration will return only records that end with -// . -func (client RecordSetsClient) ListByType(ctx context.Context, resourceGroupName string, zoneName string, recordType RecordType, top *int32, recordsetnamesuffix string) (result RecordSetListResultPage, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "ListByType", err.Error()) - } - - result.fn = client.listByTypeNextResults - req, err := client.ListByTypePreparer(ctx, resourceGroupName, zoneName, recordType, top, recordsetnamesuffix) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByType", nil, "Failure preparing request") - return - } - - resp, err := client.ListByTypeSender(req) - if err != nil { - result.rslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByType", resp, "Failure sending request") - return - } - - result.rslr, err = client.ListByTypeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByType", resp, "Failure responding to request") - } - - return -} - -// ListByTypePreparer prepares the ListByType request. -func (client RecordSetsClient) ListByTypePreparer(ctx context.Context, resourceGroupName string, zoneName string, recordType RecordType, top *int32, recordsetnamesuffix string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(recordsetnamesuffix) > 0 { - queryParameters["$recordsetnamesuffix"] = autorest.Encode("query", recordsetnamesuffix) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByTypeSender sends the ListByType request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) ListByTypeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListByTypeResponder handles the response to the ListByType request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) ListByTypeResponder(resp *http.Response) (result RecordSetListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByTypeNextResults retrieves the next set of results, if any. -func (client RecordSetsClient) listByTypeNextResults(lastResults RecordSetListResult) (result RecordSetListResult, err error) { - req, err := lastResults.recordSetListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByTypeNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByTypeSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByTypeNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByTypeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByTypeNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByTypeComplete enumerates all values, automatically crossing page boundaries as required. -func (client RecordSetsClient) ListByTypeComplete(ctx context.Context, resourceGroupName string, zoneName string, recordType RecordType, top *int32, recordsetnamesuffix string) (result RecordSetListResultIterator, err error) { - result.page, err = client.ListByType(ctx, resourceGroupName, zoneName, recordType, top, recordsetnamesuffix) - return -} - -// Update updates a record set within a DNS zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// relativeRecordSetName - the name of the record set, relative to the name of the zone. -// recordType - the type of DNS record in this record set. -// parameters - parameters supplied to the Update operation. -// ifMatch - the etag of the record set. Omit this value to always overwrite the current record set. Specify -// the last-seen etag value to prevent accidentally overwritting concurrent changes. -func (client RecordSetsClient) Update(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string) (result RecordSet, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.RecordSetsClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Update", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Update", resp, "Failure sending request") - return - } - - result, err = client.UpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Update", resp, "Failure responding to request") - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client RecordSetsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-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.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", 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 RecordSetsClient) UpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) UpdateResponder(resp *http.Response) (result RecordSet, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/zones.go b/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/zones.go deleted file mode 100644 index 45ff5fc8078fa..0000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/zones.go +++ /dev/null @@ -1,575 +0,0 @@ -package dns - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "net/http" -) - -// ZonesClient is the the DNS Management Client. -type ZonesClient struct { - BaseClient -} - -// NewZonesClient creates an instance of the ZonesClient client. -func NewZonesClient(subscriptionID string) ZonesClient { - return NewZonesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewZonesClientWithBaseURI creates an instance of the ZonesClient client. -func NewZonesClientWithBaseURI(baseURI string, subscriptionID string) ZonesClient { - return ZonesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a DNS zone. Does not modify DNS records within the zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// parameters - parameters supplied to the CreateOrUpdate operation. -// ifMatch - the etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the -// last-seen etag value to prevent accidentally overwritting any concurrent changes. -// ifNoneMatch - set to '*' to allow a new DNS zone to be created, but to prevent updating an existing zone. -// Other values will be ignored. -func (client ZonesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, zoneName string, parameters Zone, ifMatch string, ifNoneMatch string) (result Zone, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.ZonesClient", "CreateOrUpdate", err.Error()) - } - - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, zoneName, parameters, ifMatch, ifNoneMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ZonesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, zoneName string, parameters Zone, ifMatch string, ifNoneMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-10-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.Network/dnsZones/{zoneName}", 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 ZonesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ZonesClient) CreateOrUpdateResponder(resp *http.Response) (result Zone, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be -// undone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// ifMatch - the etag of the DNS zone. Omit this value to always delete the current zone. Specify the last-seen -// etag value to prevent accidentally deleting any concurrent changes. -func (client ZonesClient) Delete(ctx context.Context, resourceGroupName string, zoneName string, ifMatch string) (result ZonesDeleteFuture, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.ZonesClient", "Delete", err.Error()) - } - - req, err := client.DeletePreparer(ctx, resourceGroupName, zoneName, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ZonesClient) DeletePreparer(ctx context.Context, resourceGroupName string, zoneName string, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-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.Network/dnsZones/{zoneName}", pathParameters), - 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)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ZonesClient) DeleteSender(req *http.Request) (future ZonesDeleteFuture, err error) { - var resp *http.Response - resp, err = autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) - if err != nil { - return - } - err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) - if err != nil { - return - } - future.Future, err = azure.NewFutureFromResponse(resp) - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ZonesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a DNS zone. Retrieves the zone properties, but not the record sets within the zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -func (client ZonesClient) Get(ctx context.Context, resourceGroupName string, zoneName string) (result Zone, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.ZonesClient", "Get", err.Error()) - } - - req, err := client.GetPreparer(ctx, resourceGroupName, zoneName) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client ZonesClient) GetPreparer(ctx context.Context, resourceGroupName string, zoneName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-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.Network/dnsZones/{zoneName}", 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 ZonesClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ZonesClient) GetResponder(resp *http.Response) (result Zone, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists the DNS zones in all resource groups in a subscription. -// Parameters: -// top - the maximum number of DNS zones to return. If not specified, returns up to 100 zones. -func (client ZonesClient) List(ctx context.Context, top *int32) (result ZoneListResultPage, err error) { - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, top) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.zlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "List", resp, "Failure sending request") - return - } - - result.zlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "List", resp, "Failure responding to request") - } - - return -} - -// ListPreparer prepares the List request. -func (client ZonesClient) ListPreparer(ctx context.Context, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-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.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones", 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 ZonesClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ZonesClient) ListResponder(resp *http.Response) (result ZoneListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ZonesClient) listNextResults(lastResults ZoneListResult) (result ZoneListResult, err error) { - req, err := lastResults.zoneListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.ZonesClient", "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, "dns.ZonesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ZonesClient) ListComplete(ctx context.Context, top *int32) (result ZoneListResultIterator, err error) { - result.page, err = client.List(ctx, top) - return -} - -// ListByResourceGroup lists the DNS zones within a resource group. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// top - the maximum number of record sets to return. If not specified, returns up to 100 record sets. -func (client ZonesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, top *int32) (result ZoneListResultPage, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.ZonesClient", "ListByResourceGroup", err.Error()) - } - - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, top) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.zlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.zlr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "ListByResourceGroup", resp, "Failure responding to request") - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ZonesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-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.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones", 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 ZonesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ZonesClient) ListByResourceGroupResponder(resp *http.Response) (result ZoneListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client ZonesClient) listByResourceGroupNextResults(lastResults ZoneListResult) (result ZoneListResult, err error) { - req, err := lastResults.zoneListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.ZonesClient", "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, "dns.ZonesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ZonesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, top *int32) (result ZoneListResultIterator, err error) { - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName, top) - return -} - -// Update updates a DNS zone. Does not modify DNS records within the zone. -// Parameters: -// resourceGroupName - the name of the resource group. The name is case insensitive. -// zoneName - the name of the DNS zone (without a terminating dot). -// parameters - parameters supplied to the Update operation. -// ifMatch - the etag of the DNS zone. Omit this value to always overwrite the current zone. Specify the -// last-seen etag value to prevent accidentally overwritting any concurrent changes. -func (client ZonesClient) Update(ctx context.Context, resourceGroupName string, zoneName string, parameters ZoneUpdate, ifMatch string) (result Zone, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: resourceGroupName, - Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, - {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, - {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("dns.ZonesClient", "Update", err.Error()) - } - - req, err := client.UpdatePreparer(ctx, resourceGroupName, zoneName, parameters, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Update", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Update", resp, "Failure sending request") - return - } - - result, err = client.UpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Update", resp, "Failure responding to request") - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client ZonesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, zoneName string, parameters ZoneUpdate, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-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.Network/dnsZones/{zoneName}", 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 ZonesClient) UpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client ZonesClient) UpdateResponder(resp *http.Response) (result Zone, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/certificates.go b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/certificates.go similarity index 99% rename from vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/certificates.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/certificates.go index 8939377627d6a..9b05fe39655b1 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/certificates.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/certificates.go @@ -85,7 +85,7 @@ func (client CertificatesClient) CreateOrUpdatePreparer(ctx context.Context, res "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -167,7 +167,7 @@ func (client CertificatesClient) DeletePreparer(ctx context.Context, resourceGro "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -244,7 +244,7 @@ func (client CertificatesClient) GenerateVerificationCodePreparer(ctx context.Co "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -320,7 +320,7 @@ func (client CertificatesClient) GetPreparer(ctx context.Context, resourceGroupN "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -387,7 +387,7 @@ func (client CertificatesClient) ListByIotHubPreparer(ctx context.Context, resou "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -465,7 +465,7 @@ func (client CertificatesClient) VerifyPreparer(ctx context.Context, resourceGro "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/client.go similarity index 98% rename from vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/client.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/client.go index e57aac2e56b1e..cbe7e7e40a2f4 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/client.go @@ -1,4 +1,4 @@ -// Package devices implements the Azure ARM Devices service API version 2017-07-01. +// Package devices implements the Azure ARM Devices service API version 2018-04-01. // // Use this API to manage the IoT hubs in your Azure subscription. package devices diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/iothubresource.go b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/iothubresource.go similarity index 81% rename from vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/iothubresource.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/iothubresource.go index 45879941de4e0..3c5a515b96b99 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/iothubresource.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/iothubresource.go @@ -78,7 +78,7 @@ func (client IotHubResourceClient) CheckNameAvailabilityPreparer(ctx context.Con "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -151,7 +151,7 @@ func (client IotHubResourceClient) CreateEventHubConsumerGroupPreparer(ctx conte "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -196,34 +196,31 @@ func (client IotHubResourceClient) CreateEventHubConsumerGroupResponder(resp *ht func (client IotHubResourceClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, resourceName string, iotHubDescription IotHubDescription, ifMatch string) (result IotHubResourceCreateOrUpdateFuture, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: iotHubDescription, - Constraints: []validation.Constraint{{Target: "iotHubDescription.Subscriptionid", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "iotHubDescription.Resourcegroup", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "iotHubDescription.Properties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute.Source", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.MaxItems, Rule: 1, Chain: nil}, - {Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.MinItems, Rule: 1, Chain: nil}, - }}, - {Target: "iotHubDescription.Properties.Routing.FallbackRoute.IsEnabled", Name: validation.Null, Rule: true, Chain: nil}, - }}, - }}, - {Target: "iotHubDescription.Properties.CloudToDevice", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: int64(100), Chain: nil}, - {Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + Constraints: []validation.Constraint{{Target: "iotHubDescription.Properties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute.Source", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.MaxItems, Rule: 1, Chain: nil}, + {Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.MinItems, Rule: 1, Chain: nil}, }}, - {Target: "iotHubDescription.Properties.CloudToDevice.Feedback", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: int64(100), Chain: nil}, - {Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, - }}, - }}, - }}, + {Target: "iotHubDescription.Properties.Routing.FallbackRoute.IsEnabled", Name: validation.Null, Rule: true, Chain: nil}, + }}, }}, - {Target: "iotHubDescription.Sku", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "iotHubDescription.Sku.Capacity", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + {Target: "iotHubDescription.Properties.CloudToDevice", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: int64(100), Chain: nil}, + {Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}, + {Target: "iotHubDescription.Properties.CloudToDevice.Feedback", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: int64(100), Chain: nil}, + {Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}, + }}, + }}, + }}, + {Target: "iotHubDescription.Sku", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewError("devices.IotHubResourceClient", "CreateOrUpdate", err.Error()) } @@ -250,7 +247,7 @@ func (client IotHubResourceClient) CreateOrUpdatePreparer(ctx context.Context, r "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -327,7 +324,7 @@ func (client IotHubResourceClient) DeletePreparer(ctx context.Context, resourceG "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -408,7 +405,7 @@ func (client IotHubResourceClient) DeleteEventHubConsumerGroupPreparer(ctx conte "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -484,7 +481,7 @@ func (client IotHubResourceClient) ExportDevicesPreparer(ctx context.Context, re "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -553,7 +550,7 @@ func (client IotHubResourceClient) GetPreparer(ctx context.Context, resourceGrou "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -586,6 +583,98 @@ func (client IotHubResourceClient) GetResponder(resp *http.Response) (result Iot return } +// GetEndpointHealth get the health for routing endpoints. +func (client IotHubResourceClient) GetEndpointHealth(ctx context.Context, resourceGroupName string, iotHubName string) (result EndpointHealthDataListResultPage, err error) { + result.fn = client.getEndpointHealthNextResults + req, err := client.GetEndpointHealthPreparer(ctx, resourceGroupName, iotHubName) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetEndpointHealth", nil, "Failure preparing request") + return + } + + resp, err := client.GetEndpointHealthSender(req) + if err != nil { + result.ehdlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetEndpointHealth", resp, "Failure sending request") + return + } + + result.ehdlr, err = client.GetEndpointHealthResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "GetEndpointHealth", resp, "Failure responding to request") + } + + return +} + +// GetEndpointHealthPreparer prepares the GetEndpointHealth request. +func (client IotHubResourceClient) GetEndpointHealthPreparer(ctx context.Context, resourceGroupName string, iotHubName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "iotHubName": autorest.Encode("path", iotHubName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{iotHubName}/routingEndpointsHealth", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetEndpointHealthSender sends the GetEndpointHealth request. The method will close the +// http.Response Body if it receives an error. +func (client IotHubResourceClient) GetEndpointHealthSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetEndpointHealthResponder handles the response to the GetEndpointHealth request. The method always +// closes the http.Response Body. +func (client IotHubResourceClient) GetEndpointHealthResponder(resp *http.Response) (result EndpointHealthDataListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// getEndpointHealthNextResults retrieves the next set of results, if any. +func (client IotHubResourceClient) getEndpointHealthNextResults(lastResults EndpointHealthDataListResult) (result EndpointHealthDataListResult, err error) { + req, err := lastResults.endpointHealthDataListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "getEndpointHealthNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.GetEndpointHealthSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "getEndpointHealthNextResults", resp, "Failure sending next results request") + } + result, err = client.GetEndpointHealthResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "getEndpointHealthNextResults", resp, "Failure responding to next results request") + } + return +} + +// GetEndpointHealthComplete enumerates all values, automatically crossing page boundaries as required. +func (client IotHubResourceClient) GetEndpointHealthComplete(ctx context.Context, resourceGroupName string, iotHubName string) (result EndpointHealthDataListResultIterator, err error) { + result.page, err = client.GetEndpointHealth(ctx, resourceGroupName, iotHubName) + return +} + // GetEventHubConsumerGroup get a consumer group from the Event Hub-compatible device-to-cloud endpoint for an IoT hub. // Parameters: // resourceGroupName - the name of the resource group that contains the IoT hub. @@ -624,7 +713,7 @@ func (client IotHubResourceClient) GetEventHubConsumerGroupPreparer(ctx context. "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -694,7 +783,7 @@ func (client IotHubResourceClient) GetJobPreparer(ctx context.Context, resourceG "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -764,7 +853,7 @@ func (client IotHubResourceClient) GetKeysForKeyNamePreparer(ctx context.Context "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -832,7 +921,7 @@ func (client IotHubResourceClient) GetQuotaMetricsPreparer(ctx context.Context, "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -926,7 +1015,7 @@ func (client IotHubResourceClient) GetStatsPreparer(ctx context.Context, resourc "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -994,7 +1083,7 @@ func (client IotHubResourceClient) GetValidSkusPreparer(ctx context.Context, res "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1098,7 +1187,7 @@ func (client IotHubResourceClient) ImportDevicesPreparer(ctx context.Context, re "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1166,7 +1255,7 @@ func (client IotHubResourceClient) ListByResourceGroupPreparer(ctx context.Conte "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1256,7 +1345,7 @@ func (client IotHubResourceClient) ListBySubscriptionPreparer(ctx context.Contex "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1354,7 +1443,7 @@ func (client IotHubResourceClient) ListEventHubConsumerGroupsPreparer(ctx contex "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1450,7 +1539,7 @@ func (client IotHubResourceClient) ListJobsPreparer(ctx context.Context, resourc "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1546,7 +1635,7 @@ func (client IotHubResourceClient) ListKeysPreparer(ctx context.Context, resourc "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1605,3 +1694,231 @@ func (client IotHubResourceClient) ListKeysComplete(ctx context.Context, resourc result.page, err = client.ListKeys(ctx, resourceGroupName, resourceName) return } + +// TestAllRoutes test all routes configured in this Iot Hub +// Parameters: +// input - input for testing all routes +// iotHubName - iotHub to be tested +// resourceGroupName - resource group which Iot Hub belongs to +func (client IotHubResourceClient) TestAllRoutes(ctx context.Context, input TestAllRoutesInput, iotHubName string, resourceGroupName string) (result TestAllRoutesResult, err error) { + req, err := client.TestAllRoutesPreparer(ctx, input, iotHubName, resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "TestAllRoutes", nil, "Failure preparing request") + return + } + + resp, err := client.TestAllRoutesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "TestAllRoutes", resp, "Failure sending request") + return + } + + result, err = client.TestAllRoutesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "TestAllRoutes", resp, "Failure responding to request") + } + + return +} + +// TestAllRoutesPreparer prepares the TestAllRoutes request. +func (client IotHubResourceClient) TestAllRoutesPreparer(ctx context.Context, input TestAllRoutesInput, iotHubName string, resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "iotHubName": autorest.Encode("path", iotHubName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{iotHubName}/routing/routes/$testall", pathParameters), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// TestAllRoutesSender sends the TestAllRoutes request. The method will close the +// http.Response Body if it receives an error. +func (client IotHubResourceClient) TestAllRoutesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// TestAllRoutesResponder handles the response to the TestAllRoutes request. The method always +// closes the http.Response Body. +func (client IotHubResourceClient) TestAllRoutesResponder(resp *http.Response) (result TestAllRoutesResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// TestRoute test the new route for this Iot Hub +// Parameters: +// input - route that needs to be tested +// iotHubName - iotHub to be tested +// resourceGroupName - resource group which Iot Hub belongs to +func (client IotHubResourceClient) TestRoute(ctx context.Context, input TestRouteInput, iotHubName string, resourceGroupName string) (result TestRouteResult, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: input, + Constraints: []validation.Constraint{{Target: "input.Route", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "input.Route.Name", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "input.Route.Name", Name: validation.Pattern, Rule: `^[A-Za-z0-9-._]{1,64}$`, Chain: nil}}}, + {Target: "input.Route.EndpointNames", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "input.Route.EndpointNames", Name: validation.MaxItems, Rule: 1, Chain: nil}, + {Target: "input.Route.EndpointNames", Name: validation.MinItems, Rule: 1, Chain: nil}, + }}, + {Target: "input.Route.IsEnabled", Name: validation.Null, Rule: true, Chain: nil}, + }}}}}); err != nil { + return result, validation.NewError("devices.IotHubResourceClient", "TestRoute", err.Error()) + } + + req, err := client.TestRoutePreparer(ctx, input, iotHubName, resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "TestRoute", nil, "Failure preparing request") + return + } + + resp, err := client.TestRouteSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "TestRoute", resp, "Failure sending request") + return + } + + result, err = client.TestRouteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "TestRoute", resp, "Failure responding to request") + } + + return +} + +// TestRoutePreparer prepares the TestRoute request. +func (client IotHubResourceClient) TestRoutePreparer(ctx context.Context, input TestRouteInput, iotHubName string, resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "iotHubName": autorest.Encode("path", iotHubName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{iotHubName}/routing/routes/$testnew", pathParameters), + autorest.WithJSON(input), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// TestRouteSender sends the TestRoute request. The method will close the +// http.Response Body if it receives an error. +func (client IotHubResourceClient) TestRouteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// TestRouteResponder handles the response to the TestRoute request. The method always +// closes the http.Response Body. +func (client IotHubResourceClient) TestRouteResponder(resp *http.Response) (result TestRouteResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update update an existing IoT Hub tags. to update other fields use the CreateOrUpdate method +// Parameters: +// resourceGroupName - resource group identifier. +// resourceName - name of iot hub to update. +// iotHubTags - updated tag information to set into the iot hub instance. +func (client IotHubResourceClient) Update(ctx context.Context, resourceGroupName string, resourceName string, iotHubTags TagsResource) (result IotHubResourceUpdateFuture, err error) { + req, err := client.UpdatePreparer(ctx, resourceGroupName, resourceName, iotHubTags) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubResourceClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client IotHubResourceClient) UpdatePreparer(ctx context.Context, resourceGroupName string, resourceName string, iotHubTags TagsResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}", pathParameters), + autorest.WithJSON(iotHubTags), + 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 IotHubResourceClient) UpdateSender(req *http.Request) (future IotHubResourceUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client IotHubResourceClient) UpdateResponder(resp *http.Response) (result IotHubDescription, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/models.go similarity index 80% rename from vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/models.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/models.go index 08a8d037aa8bb..957f00ba0ec2f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/models.go @@ -82,6 +82,25 @@ func PossibleCapabilitiesValues() []Capabilities { return []Capabilities{DeviceManagement, None} } +// EndpointHealthStatus enumerates the values for endpoint health status. +type EndpointHealthStatus string + +const ( + // Dead ... + Dead EndpointHealthStatus = "dead" + // Healthy ... + Healthy EndpointHealthStatus = "healthy" + // Unhealthy ... + Unhealthy EndpointHealthStatus = "unhealthy" + // Unknown ... + Unknown EndpointHealthStatus = "unknown" +) + +// PossibleEndpointHealthStatusValues returns an array of possible values for the EndpointHealthStatus const type. +func PossibleEndpointHealthStatusValues() []EndpointHealthStatus { + return []EndpointHealthStatus{Dead, Healthy, Unhealthy, Unknown} +} + // IotHubNameUnavailabilityReason enumerates the values for iot hub name unavailability reason. type IotHubNameUnavailabilityReason string @@ -118,6 +137,12 @@ func PossibleIotHubScaleTypeValues() []IotHubScaleType { type IotHubSku string const ( + // B1 ... + B1 IotHubSku = "B1" + // B2 ... + B2 IotHubSku = "B2" + // B3 ... + B3 IotHubSku = "B3" // F1 ... F1 IotHubSku = "F1" // S1 ... @@ -130,13 +155,15 @@ const ( // PossibleIotHubSkuValues returns an array of possible values for the IotHubSku const type. func PossibleIotHubSkuValues() []IotHubSku { - return []IotHubSku{F1, S1, S2, S3} + return []IotHubSku{B1, B2, B3, F1, S1, S2, S3} } // IotHubSkuTier enumerates the values for iot hub sku tier. type IotHubSkuTier string const ( + // Basic ... + Basic IotHubSkuTier = "Basic" // Free ... Free IotHubSkuTier = "Free" // Standard ... @@ -145,7 +172,7 @@ const ( // PossibleIotHubSkuTierValues returns an array of possible values for the IotHubSkuTier const type. func PossibleIotHubSkuTierValues() []IotHubSkuTier { - return []IotHubSkuTier{Free, Standard} + return []IotHubSkuTier{Basic, Free, Standard} } // IPFilterActionType enumerates the values for ip filter action type. @@ -167,23 +194,23 @@ func PossibleIPFilterActionTypeValues() []IPFilterActionType { type JobStatus string const ( - // Cancelled ... - Cancelled JobStatus = "cancelled" - // Completed ... - Completed JobStatus = "completed" - // Enqueued ... - Enqueued JobStatus = "enqueued" - // Failed ... - Failed JobStatus = "failed" - // Running ... - Running JobStatus = "running" - // Unknown ... - Unknown JobStatus = "unknown" + // JobStatusCancelled ... + JobStatusCancelled JobStatus = "cancelled" + // JobStatusCompleted ... + JobStatusCompleted JobStatus = "completed" + // JobStatusEnqueued ... + JobStatusEnqueued JobStatus = "enqueued" + // JobStatusFailed ... + JobStatusFailed JobStatus = "failed" + // JobStatusRunning ... + JobStatusRunning JobStatus = "running" + // JobStatusUnknown ... + JobStatusUnknown JobStatus = "unknown" ) // PossibleJobStatusValues returns an array of possible values for the JobStatus const type. func PossibleJobStatusValues() []JobStatus { - return []JobStatus{Cancelled, Completed, Enqueued, Failed, Running, Unknown} + return []JobStatus{JobStatusCancelled, JobStatusCompleted, JobStatusEnqueued, JobStatusFailed, JobStatusRunning, JobStatusUnknown} } // JobType enumerates the values for job type. @@ -236,23 +263,57 @@ func PossibleOperationMonitoringLevelValues() []OperationMonitoringLevel { return []OperationMonitoringLevel{OperationMonitoringLevelError, OperationMonitoringLevelErrorInformation, OperationMonitoringLevelInformation, OperationMonitoringLevelNone} } +// RouteErrorSeverity enumerates the values for route error severity. +type RouteErrorSeverity string + +const ( + // Error ... + Error RouteErrorSeverity = "error" + // Warning ... + Warning RouteErrorSeverity = "warning" +) + +// PossibleRouteErrorSeverityValues returns an array of possible values for the RouteErrorSeverity const type. +func PossibleRouteErrorSeverityValues() []RouteErrorSeverity { + return []RouteErrorSeverity{Error, Warning} +} + // RoutingSource enumerates the values for routing source. type RoutingSource string const ( - // DeviceJobLifecycleEvents ... - DeviceJobLifecycleEvents RoutingSource = "DeviceJobLifecycleEvents" - // DeviceLifecycleEvents ... - DeviceLifecycleEvents RoutingSource = "DeviceLifecycleEvents" - // DeviceMessages ... - DeviceMessages RoutingSource = "DeviceMessages" - // TwinChangeEvents ... - TwinChangeEvents RoutingSource = "TwinChangeEvents" + // RoutingSourceDeviceJobLifecycleEvents ... + RoutingSourceDeviceJobLifecycleEvents RoutingSource = "DeviceJobLifecycleEvents" + // RoutingSourceDeviceLifecycleEvents ... + RoutingSourceDeviceLifecycleEvents RoutingSource = "DeviceLifecycleEvents" + // RoutingSourceDeviceMessages ... + RoutingSourceDeviceMessages RoutingSource = "DeviceMessages" + // RoutingSourceInvalid ... + RoutingSourceInvalid RoutingSource = "Invalid" + // RoutingSourceTwinChangeEvents ... + RoutingSourceTwinChangeEvents RoutingSource = "TwinChangeEvents" ) // PossibleRoutingSourceValues returns an array of possible values for the RoutingSource const type. func PossibleRoutingSourceValues() []RoutingSource { - return []RoutingSource{DeviceJobLifecycleEvents, DeviceLifecycleEvents, DeviceMessages, TwinChangeEvents} + return []RoutingSource{RoutingSourceDeviceJobLifecycleEvents, RoutingSourceDeviceLifecycleEvents, RoutingSourceDeviceMessages, RoutingSourceInvalid, RoutingSourceTwinChangeEvents} +} + +// TestResultStatus enumerates the values for test result status. +type TestResultStatus string + +const ( + // False ... + False TestResultStatus = "false" + // True ... + True TestResultStatus = "true" + // Undefined ... + Undefined TestResultStatus = "undefined" +) + +// PossibleTestResultStatusValues returns an array of possible values for the TestResultStatus const type. +func PossibleTestResultStatusValues() []TestResultStatus { + return []TestResultStatus{False, True, Undefined} } // CertificateBodyDescription the JSON-serialized X509 Certificate. @@ -296,6 +357,8 @@ type CertificateProperties struct { Created *date.TimeRFC1123 `json:"created,omitempty"` // Updated - The certificate's last update date and time. Updated *date.TimeRFC1123 `json:"updated,omitempty"` + // Certificate - The certificate content + Certificate *string `json:"certificate,omitempty"` } // CertificatePropertiesWithNonce the description of an X509 CA Certificate including the challenge nonce issued @@ -315,6 +378,8 @@ type CertificatePropertiesWithNonce struct { Updated *date.TimeRFC1123 `json:"updated,omitempty"` // VerificationCode - The certificate's verification code that will be used for proof of possession. VerificationCode *string `json:"verificationCode,omitempty"` + // Certificate - The certificate content + Certificate *string `json:"certificate,omitempty"` } // CertificateVerificationDescription the JSON-serialized leaf certificate @@ -346,34 +411,148 @@ type CloudToDeviceProperties struct { Feedback *FeedbackProperties `json:"feedback,omitempty"` } +// EndpointHealthData the health data for an endpoint +type EndpointHealthData struct { + // EndpointID - Id of the endpoint + EndpointID *string `json:"endpointId,omitempty"` + // HealthStatus - Health status. Possible values include: 'Unknown', 'Healthy', 'Unhealthy', 'Dead' + HealthStatus EndpointHealthStatus `json:"healthStatus,omitempty"` +} + +// EndpointHealthDataListResult the JSON-serialized array of EndpointHealthData objects with a next link. +type EndpointHealthDataListResult struct { + autorest.Response `json:"-"` + // Value - JSON-serialized array of Endpoint health data + Value *[]EndpointHealthData `json:"value,omitempty"` + // NextLink - Link to more results + NextLink *string `json:"nextLink,omitempty"` +} + +// EndpointHealthDataListResultIterator provides access to a complete listing of EndpointHealthData values. +type EndpointHealthDataListResultIterator struct { + i int + page EndpointHealthDataListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *EndpointHealthDataListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter EndpointHealthDataListResultIterator) 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 EndpointHealthDataListResultIterator) Response() EndpointHealthDataListResult { + 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 EndpointHealthDataListResultIterator) Value() EndpointHealthData { + if !iter.page.NotDone() { + return EndpointHealthData{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (ehdlr EndpointHealthDataListResult) IsEmpty() bool { + return ehdlr.Value == nil || len(*ehdlr.Value) == 0 +} + +// endpointHealthDataListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (ehdlr EndpointHealthDataListResult) endpointHealthDataListResultPreparer() (*http.Request, error) { + if ehdlr.NextLink == nil || len(to.String(ehdlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(ehdlr.NextLink))) +} + +// EndpointHealthDataListResultPage contains a page of EndpointHealthData values. +type EndpointHealthDataListResultPage struct { + fn func(EndpointHealthDataListResult) (EndpointHealthDataListResult, error) + ehdlr EndpointHealthDataListResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *EndpointHealthDataListResultPage) Next() error { + next, err := page.fn(page.ehdlr) + if err != nil { + return err + } + page.ehdlr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page EndpointHealthDataListResultPage) NotDone() bool { + return !page.ehdlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page EndpointHealthDataListResultPage) Response() EndpointHealthDataListResult { + return page.ehdlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page EndpointHealthDataListResultPage) Values() []EndpointHealthData { + if page.ehdlr.IsEmpty() { + return nil + } + return *page.ehdlr.Value +} + // ErrorDetails error details. type ErrorDetails struct { // Code - The error code. - Code *string `json:"Code,omitempty"` + Code *string `json:"code,omitempty"` // HTTPStatusCode - The HTTP status code. - HTTPStatusCode *string `json:"HttpStatusCode,omitempty"` + HTTPStatusCode *string `json:"httpStatusCode,omitempty"` // Message - The error message. - Message *string `json:"Message,omitempty"` + Message *string `json:"message,omitempty"` // Details - The error details. - Details *string `json:"Details,omitempty"` + Details *string `json:"details,omitempty"` } // EventHubConsumerGroupInfo the properties of the EventHubConsumerGroupInfo object. type EventHubConsumerGroupInfo struct { autorest.Response `json:"-"` - // Tags - The tags. - Tags map[string]*string `json:"tags"` + // Properties - The tags. + Properties map[string]*string `json:"properties"` // ID - The Event Hub-compatible consumer group identifier. ID *string `json:"id,omitempty"` // Name - The Event Hub-compatible consumer group name. Name *string `json:"name,omitempty"` + // Type - the resource type. + Type *string `json:"type,omitempty"` + // Etag - The etag. + Etag *string `json:"etag,omitempty"` } // MarshalJSON is the custom marshaler for EventHubConsumerGroupInfo. func (ehcgi EventHubConsumerGroupInfo) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) - if ehcgi.Tags != nil { - objectMap["tags"] = ehcgi.Tags + if ehcgi.Properties != nil { + objectMap["properties"] = ehcgi.Properties } if ehcgi.ID != nil { objectMap["id"] = ehcgi.ID @@ -381,6 +560,12 @@ func (ehcgi EventHubConsumerGroupInfo) MarshalJSON() ([]byte, error) { if ehcgi.Name != nil { objectMap["name"] = ehcgi.Name } + if ehcgi.Type != nil { + objectMap["type"] = ehcgi.Type + } + if ehcgi.Etag != nil { + objectMap["etag"] = ehcgi.Etag + } return json.Marshal(objectMap) } @@ -388,13 +573,14 @@ func (ehcgi EventHubConsumerGroupInfo) MarshalJSON() ([]byte, error) { // next link. type EventHubConsumerGroupsListResult struct { autorest.Response `json:"-"` - // Value - The array of Event Hub-compatible consumer group names. - Value *[]string `json:"value,omitempty"` + // Value - List of consumer groups objects + Value *[]EventHubConsumerGroupInfo `json:"value,omitempty"` // NextLink - The next link. NextLink *string `json:"nextLink,omitempty"` } -// EventHubConsumerGroupsListResultIterator provides access to a complete listing of string values. +// EventHubConsumerGroupsListResultIterator provides access to a complete listing of EventHubConsumerGroupInfo +// values. type EventHubConsumerGroupsListResultIterator struct { i int page EventHubConsumerGroupsListResultPage @@ -428,9 +614,9 @@ func (iter EventHubConsumerGroupsListResultIterator) Response() EventHubConsumer // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. -func (iter EventHubConsumerGroupsListResultIterator) Value() string { +func (iter EventHubConsumerGroupsListResultIterator) Value() EventHubConsumerGroupInfo { if !iter.page.NotDone() { - return "" + return EventHubConsumerGroupInfo{} } return iter.page.Values()[iter.i] } @@ -452,7 +638,7 @@ func (ehcglr EventHubConsumerGroupsListResult) eventHubConsumerGroupsListResultP autorest.WithBaseURL(to.String(ehcglr.NextLink))) } -// EventHubConsumerGroupsListResultPage contains a page of string values. +// EventHubConsumerGroupsListResultPage contains a page of EventHubConsumerGroupInfo values. type EventHubConsumerGroupsListResultPage struct { fn func(EventHubConsumerGroupsListResult) (EventHubConsumerGroupsListResult, error) ehcglr EventHubConsumerGroupsListResult @@ -480,7 +666,7 @@ func (page EventHubConsumerGroupsListResultPage) Response() EventHubConsumerGrou } // Values returns the slice of values for the current page or nil if there are no values. -func (page EventHubConsumerGroupsListResultPage) Values() []string { +func (page EventHubConsumerGroupsListResultPage) Values() []EventHubConsumerGroupInfo { if page.ehcglr.IsEmpty() { return nil } @@ -504,14 +690,16 @@ type EventHubProperties struct { // ExportDevicesRequest use to provide parameters when requesting an export of all devices in the IoT hub. type ExportDevicesRequest struct { // ExportBlobContainerURI - The export blob container URI. - ExportBlobContainerURI *string `json:"ExportBlobContainerUri,omitempty"` + ExportBlobContainerURI *string `json:"exportBlobContainerUri,omitempty"` // ExcludeKeys - The value indicating whether keys should be excluded during export. - ExcludeKeys *bool `json:"ExcludeKeys,omitempty"` + ExcludeKeys *bool `json:"excludeKeys,omitempty"` } // FallbackRouteProperties the properties of the fallback route. IoT Hub uses these properties when it routes // messages to the fallback endpoint. type FallbackRouteProperties struct { + // Name - The name of the route. The name can only include alphanumeric characters, periods, underscores, hyphens, has a maximum length of 64 characters, and must be unique. + Name *string `json:"name,omitempty"` // Source - The source to which the routing rule is to be applied to. For example, DeviceMessages Source *string `json:"source,omitempty"` // Condition - The condition which is evaluated in order to apply the fallback route. If the condition is not provided it will evaluate to true by default. For grammar, See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language @@ -535,9 +723,9 @@ type FeedbackProperties struct { // ImportDevicesRequest use to provide parameters when requesting an import of all devices in the hub. type ImportDevicesRequest struct { // InputBlobContainerURI - The input blob container URI. - InputBlobContainerURI *string `json:"InputBlobContainerUri,omitempty"` + InputBlobContainerURI *string `json:"inputBlobContainerUri,omitempty"` // OutputBlobContainerURI - The output blob container URI. - OutputBlobContainerURI *string `json:"OutputBlobContainerUri,omitempty"` + OutputBlobContainerURI *string `json:"outputBlobContainerUri,omitempty"` } // IotHubCapacity ioT Hub capacity information. @@ -555,14 +743,12 @@ type IotHubCapacity struct { // IotHubDescription the description of the IoT hub. type IotHubDescription struct { autorest.Response `json:"-"` - // Subscriptionid - The subscription identifier. - Subscriptionid *string `json:"subscriptionid,omitempty"` - // Resourcegroup - The name of the resource group that contains the IoT hub. A resource group name uniquely identifies the resource group within the subscription. - Resourcegroup *string `json:"resourcegroup,omitempty"` // Etag - The Etag field is *not* required. If it is provided in the response body, it must also be provided as a header per the normal ETag convention. - Etag *string `json:"etag,omitempty"` + Etag *string `json:"etag,omitempty"` + // Properties - IotHub properties Properties *IotHubProperties `json:"properties,omitempty"` - Sku *IotHubSkuInfo `json:"sku,omitempty"` + // Sku - IotHub SKU info + Sku *IotHubSkuInfo `json:"sku,omitempty"` // ID - The resource identifier. ID *string `json:"id,omitempty"` // Name - The resource name. @@ -578,12 +764,6 @@ type IotHubDescription struct { // MarshalJSON is the custom marshaler for IotHubDescription. func (ihd IotHubDescription) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) - if ihd.Subscriptionid != nil { - objectMap["subscriptionid"] = ihd.Subscriptionid - } - if ihd.Resourcegroup != nil { - objectMap["resourcegroup"] = ihd.Resourcegroup - } if ihd.Etag != nil { objectMap["etag"] = ihd.Etag } @@ -732,6 +912,8 @@ type IotHubProperties struct { IPFilterRules *[]IPFilterRule `json:"ipFilterRules,omitempty"` // ProvisioningState - The provisioning state. ProvisioningState *string `json:"provisioningState,omitempty"` + // State - Thehub state state. + State *string `json:"state,omitempty"` // HostName - The name of the host. HostName *string `json:"hostName,omitempty"` // EventHubEndpoints - The Event Hub-compatible endpoint properties. The possible keys to this dictionary are events and operationsMonitoringEvents. Both of these keys have to be present in the dictionary while making create or update calls for the IoT hub. @@ -763,6 +945,9 @@ func (ihp IotHubProperties) MarshalJSON() ([]byte, error) { if ihp.ProvisioningState != nil { objectMap["provisioningState"] = ihp.ProvisioningState } + if ihp.State != nil { + objectMap["state"] = ihp.State + } if ihp.HostName != nil { objectMap["hostName"] = ihp.HostName } @@ -799,11 +984,11 @@ func (ihp IotHubProperties) MarshalJSON() ([]byte, error) { // IotHubQuotaMetricInfo quota metrics properties. type IotHubQuotaMetricInfo struct { // Name - The name of the quota metric. - Name *string `json:"Name,omitempty"` + Name *string `json:"name,omitempty"` // CurrentValue - The current value for the quota metric. - CurrentValue *int64 `json:"CurrentValue,omitempty"` + CurrentValue *int64 `json:"currentValue,omitempty"` // MaxValue - The maximum value of the quota metric. - MaxValue *int64 `json:"MaxValue,omitempty"` + MaxValue *int64 `json:"maxValue,omitempty"` } // IotHubQuotaMetricInfoListResult the JSON-serialized array of IotHubQuotaMetricInfo objects with a next link. @@ -965,12 +1150,42 @@ func (future *IotHubResourceDeleteFuture) Result(client IotHubResourceClient) (s return } +// IotHubResourceUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type IotHubResourceUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *IotHubResourceUpdateFuture) Result(client IotHubResourceClient) (ihd IotHubDescription, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubResourceUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("devices.IotHubResourceUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if ihd.Response.Response, err = future.GetResult(sender); err == nil && ihd.Response.Response.StatusCode != http.StatusNoContent { + ihd, err = client.UpdateResponder(ihd.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.IotHubResourceUpdateFuture", "Result", ihd.Response.Response, "Failure responding to request") + } + } + return +} + // IotHubSkuDescription SKU properties. type IotHubSkuDescription struct { // ResourceType - The type of the resource. - ResourceType *string `json:"resourceType,omitempty"` - Sku *IotHubSkuInfo `json:"sku,omitempty"` - Capacity *IotHubCapacity `json:"capacity,omitempty"` + ResourceType *string `json:"resourceType,omitempty"` + // Sku - The type of the resource. + Sku *IotHubSkuInfo `json:"sku,omitempty"` + // Capacity - IotHub capacity + Capacity *IotHubCapacity `json:"capacity,omitempty"` } // IotHubSkuDescriptionListResult the JSON-serialized array of IotHubSkuDescription objects with a next link. @@ -1077,9 +1292,9 @@ func (page IotHubSkuDescriptionListResultPage) Values() []IotHubSkuDescription { // IotHubSkuInfo information about the SKU of the IoT hub. type IotHubSkuInfo struct { - // Name - The name of the SKU. Possible values include: 'F1', 'S1', 'S2', 'S3' + // Name - The name of the SKU. Possible values include: 'F1', 'S1', 'S2', 'S3', 'B1', 'B2', 'B3' Name IotHubSku `json:"name,omitempty"` - // Tier - The billing tier for the IoT hub. Possible values include: 'Free', 'Standard' + // Tier - The billing tier for the IoT hub. Possible values include: 'Free', 'Standard', 'Basic' Tier IotHubSkuTier `json:"tier,omitempty"` // Capacity - The number of provisioned IoT Hub units. See: https://docs.microsoft.com/azure/azure-subscription-service-limits#iot-hub-limits. Capacity *int64 `json:"capacity,omitempty"` @@ -1106,7 +1321,7 @@ type JobResponse struct { EndTimeUtc *date.TimeRFC1123 `json:"endTimeUtc,omitempty"` // Type - The type of the job. Possible values include: 'JobTypeUnknown', 'JobTypeExport', 'JobTypeImport', 'JobTypeBackup', 'JobTypeReadDeviceProperties', 'JobTypeWriteDeviceProperties', 'JobTypeUpdateDeviceConfiguration', 'JobTypeRebootDevice', 'JobTypeFactoryResetDevice', 'JobTypeFirmwareUpdate' Type JobType `json:"type,omitempty"` - // Status - The status of the job. Possible values include: 'Unknown', 'Enqueued', 'Running', 'Completed', 'Failed', 'Cancelled' + // Status - The status of the job. Possible values include: 'JobStatusUnknown', 'JobStatusEnqueued', 'JobStatusRunning', 'JobStatusCompleted', 'JobStatusFailed', 'JobStatusCancelled' Status JobStatus `json:"status,omitempty"` // FailureReason - If status == failed, this string containing the reason for the failure. FailureReason *string `json:"failureReason,omitempty"` @@ -1218,6 +1433,12 @@ func (page JobResponseListResultPage) Values() []JobResponse { return *page.jrlr.Value } +// MatchedRoute routes that matched +type MatchedRoute struct { + // Properties - Properties of routes that matched + Properties *RouteProperties `json:"properties,omitempty"` +} + // MessagingEndpointProperties the properties of the messaging endpoints used by this IoT hub. type MessagingEndpointProperties struct { // LockDurationAsIso8601 - The lock duration. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-file-upload. @@ -1228,6 +1449,14 @@ type MessagingEndpointProperties struct { MaxDeliveryCount *int32 `json:"maxDeliveryCount,omitempty"` } +// Name name of Iot Hub type +type Name struct { + // Value - IotHub type + Value *string `json:"value,omitempty"` + // LocalizedValue - Localized value of name + LocalizedValue *string `json:"localizedValue,omitempty"` +} + // Operation ioT Hub REST API operation type Operation struct { // Name - Operation name: {provider}/{resource}/{read | write | action | delete} @@ -1249,7 +1478,7 @@ type OperationDisplay struct { // OperationInputs input values. type OperationInputs struct { // Name - The name of the IoT hub to check. - Name *string `json:"Name,omitempty"` + Name *string `json:"name,omitempty"` } // OperationListResult result of the request to list IoT Hub operations. It contains a list of operations and a URL @@ -1417,11 +1646,37 @@ func (r Resource) MarshalJSON() ([]byte, error) { return json.Marshal(objectMap) } +// RouteCompilationError compilation error when evaluating route +type RouteCompilationError struct { + // Message - Route error message + Message *string `json:"message,omitempty"` + // Severity - Severity of the route error. Possible values include: 'Error', 'Warning' + Severity RouteErrorSeverity `json:"severity,omitempty"` + // Location - Location where the route error happened + Location *RouteErrorRange `json:"location,omitempty"` +} + +// RouteErrorPosition position where the route error happened +type RouteErrorPosition struct { + // Line - Line where the route error happened + Line *int32 `json:"line,omitempty"` + // Column - Column where the route error happened + Column *int32 `json:"column,omitempty"` +} + +// RouteErrorRange range of route errors +type RouteErrorRange struct { + // Start - Start where the route error happened + Start *RouteErrorPosition `json:"start,omitempty"` + // End - End where the route error happened + End *RouteErrorPosition `json:"end,omitempty"` +} + // RouteProperties the properties of a routing rule that your IoT hub uses to route messages to endpoints. type RouteProperties struct { // Name - The name of the route. The name can only include alphanumeric characters, periods, underscores, hyphens, has a maximum length of 64 characters, and must be unique. Name *string `json:"name,omitempty"` - // Source - The source that the routing rule is to be applied to, such as DeviceMessages. Possible values include: 'DeviceMessages', 'TwinChangeEvents', 'DeviceLifecycleEvents', 'DeviceJobLifecycleEvents' + // Source - The source that the routing rule is to be applied to, such as DeviceMessages. Possible values include: 'RoutingSourceInvalid', 'RoutingSourceDeviceMessages', 'RoutingSourceTwinChangeEvents', 'RoutingSourceDeviceLifecycleEvents', 'RoutingSourceDeviceJobLifecycleEvents' Source RoutingSource `json:"source,omitempty"` // Condition - The condition that is evaluated to apply the routing rule. If no condition is provided, it evaluates to true by default. For grammar, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language Condition *string `json:"condition,omitempty"` @@ -1457,6 +1712,31 @@ type RoutingEventHubProperties struct { ResourceGroup *string `json:"resourceGroup,omitempty"` } +// RoutingMessage routing message +type RoutingMessage struct { + // Body - Body of routing message + Body *string `json:"body,omitempty"` + // AppProperties - App properties + AppProperties map[string]*string `json:"appProperties"` + // SystemProperties - System properties + SystemProperties map[string]*string `json:"systemProperties"` +} + +// MarshalJSON is the custom marshaler for RoutingMessage. +func (rm RoutingMessage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if rm.Body != nil { + objectMap["body"] = rm.Body + } + if rm.AppProperties != nil { + objectMap["appProperties"] = rm.AppProperties + } + if rm.SystemProperties != nil { + objectMap["systemProperties"] = rm.SystemProperties + } + return json.Marshal(objectMap) +} + // RoutingProperties the routing related properties of the IoT hub. See: // https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging type RoutingProperties struct { @@ -1645,3 +1925,80 @@ type StorageEndpointProperties struct { // ContainerName - The name of the root container where you upload files. The container need not exist but should be creatable using the connectionString specified. ContainerName *string `json:"containerName,omitempty"` } + +// TagsResource a container holding only the Tags for a resource, allowing the user to update the tags on an IoT +// Hub instance. +type TagsResource struct { + // Tags - Resource tags + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for TagsResource. +func (tr TagsResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if tr.Tags != nil { + objectMap["tags"] = tr.Tags + } + return json.Marshal(objectMap) +} + +// TestAllRoutesInput input for testing all routes +type TestAllRoutesInput struct { + // RoutingSource - Routing source. Possible values include: 'RoutingSourceInvalid', 'RoutingSourceDeviceMessages', 'RoutingSourceTwinChangeEvents', 'RoutingSourceDeviceLifecycleEvents', 'RoutingSourceDeviceJobLifecycleEvents' + RoutingSource RoutingSource `json:"routingSource,omitempty"` + // Message - Routing message + Message *RoutingMessage `json:"message,omitempty"` +} + +// TestAllRoutesResult result of testing all routes +type TestAllRoutesResult struct { + autorest.Response `json:"-"` + // Routes - JSON-serialized array of matched routes + Routes *[]MatchedRoute `json:"routes,omitempty"` +} + +// TestRouteInput input for testing route +type TestRouteInput struct { + // Message - Routing message + Message *RoutingMessage `json:"message,omitempty"` + // Route - Route properties + Route *RouteProperties `json:"route,omitempty"` +} + +// TestRouteResult result of testing one route +type TestRouteResult struct { + autorest.Response `json:"-"` + // Result - Result of testing route. Possible values include: 'Undefined', 'False', 'True' + Result TestResultStatus `json:"result,omitempty"` + // Details - Detailed result of testing route + Details *TestRouteResultDetails `json:"details,omitempty"` +} + +// TestRouteResultDetails detailed result of testing a route +type TestRouteResultDetails struct { + // CompilationErrors - JSON-serialized list of route compilation errors + CompilationErrors *[]RouteCompilationError `json:"compilationErrors,omitempty"` +} + +// UserSubscriptionQuota user subscription quota response +type UserSubscriptionQuota struct { + // ID - IotHub type id + ID *string `json:"id,omitempty"` + // Type - Response type + Type *string `json:"type,omitempty"` + // Unit - Unit of IotHub type + Unit *string `json:"unit,omitempty"` + // CurrentValue - Current number of IotHub type + CurrentValue *int32 `json:"currentValue,omitempty"` + // Limit - Numerical limit on IotHub type + Limit *int32 `json:"limit,omitempty"` + // Name - IotHub type + Name *Name `json:"name,omitempty"` +} + +// UserSubscriptionQuotaListResult json-serialized array of User subscription quota response +type UserSubscriptionQuotaListResult struct { + autorest.Response `json:"-"` + Value *[]UserSubscriptionQuota `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/operations.go similarity index 99% rename from vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/operations.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/operations.go index 6419b6e4a385a..01395bf228a53 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/operations.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/operations.go @@ -65,7 +65,7 @@ func (client OperationsClient) List(ctx context.Context) (result OperationListRe // ListPreparer prepares the List request. func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { - const APIVersion = "2017-07-01" + const APIVersion = "2018-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/resourceprovidercommon.go b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/resourceprovidercommon.go new file mode 100644 index 0000000000000..a80dd0c0413be --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/resourceprovidercommon.go @@ -0,0 +1,102 @@ +package devices + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ResourceProviderCommonClient is the use this API to manage the IoT hubs in your Azure subscription. +type ResourceProviderCommonClient struct { + BaseClient +} + +// NewResourceProviderCommonClient creates an instance of the ResourceProviderCommonClient client. +func NewResourceProviderCommonClient(subscriptionID string) ResourceProviderCommonClient { + return NewResourceProviderCommonClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewResourceProviderCommonClientWithBaseURI creates an instance of the ResourceProviderCommonClient client. +func NewResourceProviderCommonClientWithBaseURI(baseURI string, subscriptionID string) ResourceProviderCommonClient { + return ResourceProviderCommonClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// GetSubscriptionQuota get the number of free and paid iot hubs in the subscription +func (client ResourceProviderCommonClient) GetSubscriptionQuota(ctx context.Context) (result UserSubscriptionQuotaListResult, err error) { + req, err := client.GetSubscriptionQuotaPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.ResourceProviderCommonClient", "GetSubscriptionQuota", nil, "Failure preparing request") + return + } + + resp, err := client.GetSubscriptionQuotaSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "devices.ResourceProviderCommonClient", "GetSubscriptionQuota", resp, "Failure sending request") + return + } + + result, err = client.GetSubscriptionQuotaResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "devices.ResourceProviderCommonClient", "GetSubscriptionQuota", resp, "Failure responding to request") + } + + return +} + +// GetSubscriptionQuotaPreparer prepares the GetSubscriptionQuota request. +func (client ResourceProviderCommonClient) GetSubscriptionQuotaPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Devices/usages", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSubscriptionQuotaSender sends the GetSubscriptionQuota request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceProviderCommonClient) GetSubscriptionQuotaSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetSubscriptionQuotaResponder handles the response to the GetSubscriptionQuota request. The method always +// closes the http.Response Body. +func (client ResourceProviderCommonClient) GetSubscriptionQuotaResponder(resp *http.Response) (result UserSubscriptionQuotaListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/version.go similarity index 94% rename from vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/version.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/version.go index d03b1f2e8ac9e..31c3eebda3bcf 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices/version.go @@ -21,7 +21,7 @@ import "github.com/Azure/azure-sdk-for-go/version" // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return "Azure-SDK-For-Go/" + version.Number + " devices/2017-07-01" + return "Azure-SDK-For-Go/" + version.Number + " devices/2018-04-01" } // Version returns the semantic version (see http://semver.org) of the client. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/applications.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/applications.go new file mode 100644 index 0000000000000..b7bb79b05103c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/applications.go @@ -0,0 +1,402 @@ +package servicefabric + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ApplicationsClient is the service Fabric Management Client +type ApplicationsClient struct { + BaseClient +} + +// NewApplicationsClient creates an instance of the ApplicationsClient client. +func NewApplicationsClient(subscriptionID string) ApplicationsClient { + return NewApplicationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewApplicationsClientWithBaseURI creates an instance of the ApplicationsClient client. +func NewApplicationsClientWithBaseURI(baseURI string, subscriptionID string) ApplicationsClient { + return ApplicationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Create create or update a Service Fabric application resource with the specified name. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationName - the name of the application resource. +// parameters - the application resource. +func (client ApplicationsClient) Create(ctx context.Context, resourceGroupName string, clusterName string, applicationName string, parameters ApplicationResource) (result ApplicationsCreateFuture, err error) { + req, err := client.CreatePreparer(ctx, resourceGroupName, clusterName, applicationName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsClient", "Create", nil, "Failure preparing request") + return + } + + result, err = client.CreateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsClient", "Create", result.Response(), "Failure sending request") + return + } + + return +} + +// CreatePreparer prepares the Create request. +func (client ApplicationsClient) CreatePreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationName string, parameters ApplicationResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationName": autorest.Encode("path", applicationName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applications/{applicationName}", pathParameters), + autorest.WithJSON(parameters), + 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 ApplicationsClient) CreateSender(req *http.Request) (future ApplicationsCreateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) CreateResponder(resp *http.Response) (result ApplicationResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete a Service Fabric application resource with the specified name. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationName - the name of the application resource. +func (client ApplicationsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, applicationName string) (result ApplicationsDeleteFuture, err error) { + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, applicationName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ApplicationsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationName": autorest.Encode("path", applicationName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applications/{applicationName}", 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 ApplicationsClient) DeleteSender(req *http.Request) (future ApplicationsDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get a Service Fabric application resource created or in the process of being created in the Service Fabric +// cluster resource. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationName - the name of the application resource. +func (client ApplicationsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, applicationName string) (result ApplicationResource, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, applicationName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ApplicationsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationName": autorest.Encode("path", applicationName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applications/{applicationName}", 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 ApplicationsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) GetResponder(resp *http.Response) (result ApplicationResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets all application resources created or in the process of being created in the Service Fabric cluster +// resource. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +func (client ApplicationsClient) List(ctx context.Context, resourceGroupName string, clusterName string) (result ApplicationResourceList, err error) { + req, err := client.ListPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ApplicationsClient) 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 = "2017-07-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.ServiceFabric/clusters/{clusterName}/applications", 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 ApplicationsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) ListResponder(resp *http.Response) (result ApplicationResourceList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update update a Service Fabric application resource with the specified name. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationName - the name of the application resource. +// parameters - the application resource for patch operations. +func (client ApplicationsClient) Update(ctx context.Context, resourceGroupName string, clusterName string, applicationName string, parameters ApplicationResourceUpdate) (result ApplicationsUpdateFuture, err error) { + req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, applicationName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client ApplicationsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationName string, parameters ApplicationResourceUpdate) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationName": autorest.Encode("path", applicationName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applications/{applicationName}", 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 ApplicationsClient) UpdateSender(req *http.Request) (future ApplicationsUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client ApplicationsClient) UpdateResponder(resp *http.Response) (result ApplicationResourceUpdate, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + 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/servicefabric/mgmt/2018-02-01/servicefabric/applicationtypes.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/applicationtypes.go new file mode 100644 index 0000000000000..a552ffd62d44f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/applicationtypes.go @@ -0,0 +1,322 @@ +package servicefabric + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ApplicationTypesClient is the service Fabric Management Client +type ApplicationTypesClient struct { + BaseClient +} + +// NewApplicationTypesClient creates an instance of the ApplicationTypesClient client. +func NewApplicationTypesClient(subscriptionID string) ApplicationTypesClient { + return NewApplicationTypesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewApplicationTypesClientWithBaseURI creates an instance of the ApplicationTypesClient client. +func NewApplicationTypesClientWithBaseURI(baseURI string, subscriptionID string) ApplicationTypesClient { + return ApplicationTypesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Create create or update a Service Fabric application type name resource with the specified name. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationTypeName - the name of the application type name resource. +// parameters - the application type name resource. +func (client ApplicationTypesClient) Create(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string, parameters ApplicationTypeResource) (result ApplicationTypeResource, err error) { + req, err := client.CreatePreparer(ctx, resourceGroupName, clusterName, applicationTypeName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypesClient", "Create", nil, "Failure preparing request") + return + } + + resp, err := client.CreateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypesClient", "Create", resp, "Failure sending request") + return + } + + result, err = client.CreateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypesClient", "Create", resp, "Failure responding to request") + } + + return +} + +// CreatePreparer prepares the Create request. +func (client ApplicationTypesClient) CreatePreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string, parameters ApplicationTypeResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationTypeName": autorest.Encode("path", applicationTypeName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}", pathParameters), + autorest.WithJSON(parameters), + 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 ApplicationTypesClient) CreateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client ApplicationTypesClient) CreateResponder(resp *http.Response) (result ApplicationTypeResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete a Service Fabric application type name resource with the specified name. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationTypeName - the name of the application type name resource. +func (client ApplicationTypesClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string) (result ApplicationTypesDeleteFuture, err error) { + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, applicationTypeName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ApplicationTypesClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationTypeName": autorest.Encode("path", applicationTypeName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}", 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 ApplicationTypesClient) DeleteSender(req *http.Request) (future ApplicationTypesDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ApplicationTypesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get a Service Fabric application type name resource created or in the process of being created in the Service +// Fabric cluster resource. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationTypeName - the name of the application type name resource. +func (client ApplicationTypesClient) Get(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string) (result ApplicationTypeResource, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, applicationTypeName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ApplicationTypesClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationTypeName": autorest.Encode("path", applicationTypeName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}", 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 ApplicationTypesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ApplicationTypesClient) GetResponder(resp *http.Response) (result ApplicationTypeResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets all application type name resources created or in the process of being created in the Service Fabric +// cluster resource. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +func (client ApplicationTypesClient) List(ctx context.Context, resourceGroupName string, clusterName string) (result ApplicationTypeResourceList, err error) { + req, err := client.ListPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypesClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ApplicationTypesClient) 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 = "2017-07-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.ServiceFabric/clusters/{clusterName}/applicationTypes", 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 ApplicationTypesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ApplicationTypesClient) ListResponder(resp *http.Response) (result ApplicationTypeResourceList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/applicationtypeversions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/applicationtypeversions.go new file mode 100644 index 0000000000000..ea1b415805fa4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/applicationtypeversions.go @@ -0,0 +1,342 @@ +package servicefabric + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// ApplicationTypeVersionsClient is the service Fabric Management Client +type ApplicationTypeVersionsClient struct { + BaseClient +} + +// NewApplicationTypeVersionsClient creates an instance of the ApplicationTypeVersionsClient client. +func NewApplicationTypeVersionsClient(subscriptionID string) ApplicationTypeVersionsClient { + return NewApplicationTypeVersionsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewApplicationTypeVersionsClientWithBaseURI creates an instance of the ApplicationTypeVersionsClient client. +func NewApplicationTypeVersionsClientWithBaseURI(baseURI string, subscriptionID string) ApplicationTypeVersionsClient { + return ApplicationTypeVersionsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Create create or update a Service Fabric application type version resource with the specified name. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationTypeName - the name of the application type name resource. +// version - the application type version. +// parameters - the application type version resource. +func (client ApplicationTypeVersionsClient) Create(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string, version string, parameters ApplicationTypeVersionResource) (result ApplicationTypeVersionsCreateFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.ApplicationTypeVersionResourceProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ApplicationTypeVersionResourceProperties.AppPackageURL", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("servicefabric.ApplicationTypeVersionsClient", "Create", err.Error()) + } + + req, err := client.CreatePreparer(ctx, resourceGroupName, clusterName, applicationTypeName, version, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypeVersionsClient", "Create", nil, "Failure preparing request") + return + } + + result, err = client.CreateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypeVersionsClient", "Create", result.Response(), "Failure sending request") + return + } + + return +} + +// CreatePreparer prepares the Create request. +func (client ApplicationTypeVersionsClient) CreatePreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string, version string, parameters ApplicationTypeVersionResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationTypeName": autorest.Encode("path", applicationTypeName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "version": autorest.Encode("path", version), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}/versions/{version}", pathParameters), + autorest.WithJSON(parameters), + 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 ApplicationTypeVersionsClient) CreateSender(req *http.Request) (future ApplicationTypeVersionsCreateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client ApplicationTypeVersionsClient) CreateResponder(resp *http.Response) (result ApplicationTypeVersionResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete a Service Fabric application type version resource with the specified name. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationTypeName - the name of the application type name resource. +// version - the application type version. +func (client ApplicationTypeVersionsClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string, version string) (result ApplicationTypeVersionsDeleteFuture, err error) { + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, applicationTypeName, version) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypeVersionsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypeVersionsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ApplicationTypeVersionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string, version string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationTypeName": autorest.Encode("path", applicationTypeName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "version": autorest.Encode("path", version), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}/versions/{version}", 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 ApplicationTypeVersionsClient) DeleteSender(req *http.Request) (future ApplicationTypeVersionsDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ApplicationTypeVersionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get a Service Fabric application type version resource created or in the process of being created in the Service +// Fabric application type name resource. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationTypeName - the name of the application type name resource. +// version - the application type version. +func (client ApplicationTypeVersionsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string, version string) (result ApplicationTypeVersionResource, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, applicationTypeName, version) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypeVersionsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypeVersionsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypeVersionsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ApplicationTypeVersionsClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string, version string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationTypeName": autorest.Encode("path", applicationTypeName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "version": autorest.Encode("path", version), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}/versions/{version}", 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 ApplicationTypeVersionsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ApplicationTypeVersionsClient) GetResponder(resp *http.Response) (result ApplicationTypeVersionResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets all application type version resources created or in the process of being created in the Service Fabric +// application type name resource. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationTypeName - the name of the application type name resource. +func (client ApplicationTypeVersionsClient) List(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string) (result ApplicationTypeVersionResourceList, err error) { + req, err := client.ListPreparer(ctx, resourceGroupName, clusterName, applicationTypeName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypeVersionsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypeVersionsClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypeVersionsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ApplicationTypeVersionsClient) ListPreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationTypeName": autorest.Encode("path", applicationTypeName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}/versions", 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 ApplicationTypeVersionsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ApplicationTypeVersionsClient) ListResponder(resp *http.Response) (result ApplicationTypeVersionResourceList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/client.go similarity index 84% rename from vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/client.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/client.go index 4dfa42b84d6f7..5d0f53e073fc6 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/client.go @@ -1,7 +1,7 @@ -// Package dns implements the Azure ARM Dns service API version 2016-04-01. +// Package servicefabric implements the Azure ARM Servicefabric service API version . // -// The DNS Management Client. -package dns +// Service Fabric Management Client +package servicefabric // Copyright (c) Microsoft and contributors. All rights reserved. // @@ -25,11 +25,11 @@ import ( ) const ( - // DefaultBaseURI is the default URI used for the service Dns + // DefaultBaseURI is the default URI used for the service Servicefabric DefaultBaseURI = "https://management.azure.com" ) -// BaseClient is the base client for Dns. +// BaseClient is the base client for Servicefabric. type BaseClient struct { autorest.Client BaseURI string diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/clusters.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/clusters.go new file mode 100644 index 0000000000000..9b0d6c108feb3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/clusters.go @@ -0,0 +1,504 @@ +package servicefabric + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// ClustersClient is the service Fabric Management Client +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. +func NewClustersClientWithBaseURI(baseURI string, subscriptionID string) ClustersClient { + return ClustersClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Create create or update a Service Fabric cluster resource with the specified name. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// parameters - the cluster resource. +func (client ClustersClient) Create(ctx context.Context, resourceGroupName string, clusterName string, parameters Cluster) (result ClustersCreateFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.ClusterProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.Certificate", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.Certificate.Thumbprint", Name: validation.Null, Rule: true, Chain: nil}}}, + {Target: "parameters.ClusterProperties.DiagnosticsStorageAccountConfig", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.DiagnosticsStorageAccountConfig.StorageAccountName", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.DiagnosticsStorageAccountConfig.ProtectedAccountKeyName", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.DiagnosticsStorageAccountConfig.BlobEndpoint", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.DiagnosticsStorageAccountConfig.QueueEndpoint", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.DiagnosticsStorageAccountConfig.TableEndpoint", Name: validation.Null, Rule: true, Chain: nil}, + }}, + {Target: "parameters.ClusterProperties.ManagementEndpoint", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.NodeTypes", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.ReverseProxyCertificate", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.ReverseProxyCertificate.Thumbprint", Name: validation.Null, Rule: true, Chain: nil}}}, + {Target: "parameters.ClusterProperties.UpgradeDescription", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.UpgradeDescription.UpgradeReplicaSetCheckTimeout", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.UpgradeDescription.HealthCheckWaitDuration", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.UpgradeDescription.HealthCheckStableDuration", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.UpgradeDescription.HealthCheckRetryTimeout", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.UpgradeDescription.UpgradeTimeout", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.UpgradeDescription.UpgradeDomainTimeout", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ClusterProperties.UpgradeDescription.HealthPolicy", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.UpgradeDescription.HealthPolicy.MaxPercentUnhealthyNodes", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.UpgradeDescription.HealthPolicy.MaxPercentUnhealthyNodes", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "parameters.ClusterProperties.UpgradeDescription.HealthPolicy.MaxPercentUnhealthyNodes", Name: validation.InclusiveMinimum, Rule: 0, Chain: nil}, + }}, + {Target: "parameters.ClusterProperties.UpgradeDescription.HealthPolicy.MaxPercentUnhealthyApplications", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.UpgradeDescription.HealthPolicy.MaxPercentUnhealthyApplications", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "parameters.ClusterProperties.UpgradeDescription.HealthPolicy.MaxPercentUnhealthyApplications", Name: validation.InclusiveMinimum, Rule: 0, Chain: nil}, + }}, + }}, + {Target: "parameters.ClusterProperties.UpgradeDescription.DeltaHealthPolicy", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.UpgradeDescription.DeltaHealthPolicy.MaxPercentDeltaUnhealthyNodes", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.UpgradeDescription.DeltaHealthPolicy.MaxPercentDeltaUnhealthyNodes", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "parameters.ClusterProperties.UpgradeDescription.DeltaHealthPolicy.MaxPercentDeltaUnhealthyNodes", Name: validation.InclusiveMinimum, Rule: 0, Chain: nil}, + }}, + {Target: "parameters.ClusterProperties.UpgradeDescription.DeltaHealthPolicy.MaxPercentUpgradeDomainDeltaUnhealthyNodes", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.UpgradeDescription.DeltaHealthPolicy.MaxPercentUpgradeDomainDeltaUnhealthyNodes", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "parameters.ClusterProperties.UpgradeDescription.DeltaHealthPolicy.MaxPercentUpgradeDomainDeltaUnhealthyNodes", Name: validation.InclusiveMinimum, Rule: 0, Chain: nil}, + }}, + {Target: "parameters.ClusterProperties.UpgradeDescription.DeltaHealthPolicy.MaxPercentDeltaUnhealthyApplications", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "parameters.ClusterProperties.UpgradeDescription.DeltaHealthPolicy.MaxPercentDeltaUnhealthyApplications", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "parameters.ClusterProperties.UpgradeDescription.DeltaHealthPolicy.MaxPercentDeltaUnhealthyApplications", Name: validation.InclusiveMinimum, Rule: 0, Chain: nil}, + }}, + }}, + }}, + }}}}}); err != nil { + return result, validation.NewError("servicefabric.ClustersClient", "Create", err.Error()) + } + + req, err := client.CreatePreparer(ctx, resourceGroupName, clusterName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClustersClient", "Create", nil, "Failure preparing request") + return + } + + result, err = client.CreateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClustersClient", "Create", result.Response(), "Failure sending request") + return + } + + return +} + +// CreatePreparer prepares the Create request. +func (client ClustersClient) CreatePreparer(ctx context.Context, resourceGroupName string, clusterName string, parameters Cluster) (*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 = "2018-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.ServiceFabric/clusters/{clusterName}", pathParameters), + autorest.WithJSON(parameters), + 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 ClustersClient) CreateSender(req *http.Request) (future ClustersCreateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client ClustersClient) CreateResponder(resp *http.Response) (result Cluster, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete a Service Fabric cluster resource with the specified name. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +func (client ClustersClient) Delete(ctx context.Context, resourceGroupName string, clusterName string) (result autorest.Response, err error) { + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClustersClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicefabric.ClustersClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClustersClient", "Delete", resp, "Failure responding to request") + } + + 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 = "2018-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.ServiceFabric/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) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ClustersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get a Service Fabric cluster resource created or in the process of being created in the specified resource +// group. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +func (client ClustersClient) Get(ctx context.Context, resourceGroupName string, clusterName string) (result Cluster, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.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, "servicefabric.ClustersClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClustersClient", "Get", resp, "Failure responding to request") + } + + 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 = "2018-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.ServiceFabric/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 autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ClustersClient) GetResponder(resp *http.Response) (result Cluster, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets all Service Fabric cluster resources created or in the process of being created in the subscription. +func (client ClustersClient) List(ctx context.Context) (result ClusterListResult, err error) { + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.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, "servicefabric.ClustersClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClustersClient", "List", resp, "Failure responding to request") + } + + 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 = "2018-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceFabric/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 autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ClustersClient) ListResponder(resp *http.Response) (result ClusterListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroup gets all Service Fabric cluster resources created or in the process of being created in the +// resource group. +// Parameters: +// resourceGroupName - the name of the resource group. +func (client ClustersClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ClusterListResult, err error) { + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.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, "servicefabric.ClustersClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClustersClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + 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 = "2018-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.ServiceFabric/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 autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client ClustersClient) ListByResourceGroupResponder(resp *http.Response) (result ClusterListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update update the configuration of a Service Fabric cluster resource with the specified name. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// parameters - the parameters which contains the property value and property name which used to update the +// cluster configuration. +func (client ClustersClient) Update(ctx context.Context, resourceGroupName string, clusterName string, parameters ClusterUpdateParameters) (result ClustersUpdateFuture, err error) { + req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClustersClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.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 ClusterUpdateParameters) (*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 = "2018-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.ServiceFabric/clusters/{clusterName}", 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 ClustersClient) UpdateSender(req *http.Request) (future ClustersUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + 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, + client.ByInspecting(), + 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/servicefabric/mgmt/2018-02-01/servicefabric/clusterversions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/clusterversions.go new file mode 100644 index 0000000000000..05c12964cdc0a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/clusterversions.go @@ -0,0 +1,308 @@ +package servicefabric + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ClusterVersionsClient is the service Fabric Management Client +type ClusterVersionsClient struct { + BaseClient +} + +// NewClusterVersionsClient creates an instance of the ClusterVersionsClient client. +func NewClusterVersionsClient(subscriptionID string) ClusterVersionsClient { + return NewClusterVersionsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewClusterVersionsClientWithBaseURI creates an instance of the ClusterVersionsClient client. +func NewClusterVersionsClientWithBaseURI(baseURI string, subscriptionID string) ClusterVersionsClient { + return ClusterVersionsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Get gets information about an available Service Fabric cluster code version. +// Parameters: +// location - the location for the cluster code versions. This is different from cluster location. +// clusterVersion - the cluster code version. +func (client ClusterVersionsClient) Get(ctx context.Context, location string, clusterVersion string) (result ClusterCodeVersionsListResult, err error) { + req, err := client.GetPreparer(ctx, location, clusterVersion) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClusterVersionsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicefabric.ClusterVersionsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClusterVersionsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ClusterVersionsClient) GetPreparer(ctx context.Context, location string, clusterVersion string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterVersion": autorest.Encode("path", clusterVersion), + "location": autorest.Encode("path", location), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceFabric/locations/{location}/clusterVersions/{clusterVersion}", 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 ClusterVersionsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ClusterVersionsClient) GetResponder(resp *http.Response) (result ClusterCodeVersionsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetByEnvironment gets information about an available Service Fabric cluster code version by environment. +// Parameters: +// location - the location for the cluster code versions. This is different from cluster location. +// environment - the operating system of the cluster. The default means all. +// clusterVersion - the cluster code version. +func (client ClusterVersionsClient) GetByEnvironment(ctx context.Context, location string, environment string, clusterVersion string) (result ClusterCodeVersionsListResult, err error) { + req, err := client.GetByEnvironmentPreparer(ctx, location, environment, clusterVersion) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClusterVersionsClient", "GetByEnvironment", nil, "Failure preparing request") + return + } + + resp, err := client.GetByEnvironmentSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicefabric.ClusterVersionsClient", "GetByEnvironment", resp, "Failure sending request") + return + } + + result, err = client.GetByEnvironmentResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClusterVersionsClient", "GetByEnvironment", resp, "Failure responding to request") + } + + return +} + +// GetByEnvironmentPreparer prepares the GetByEnvironment request. +func (client ClusterVersionsClient) GetByEnvironmentPreparer(ctx context.Context, location string, environment string, clusterVersion string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "clusterVersion": autorest.Encode("path", clusterVersion), + "environment": autorest.Encode("path", environment), + "location": autorest.Encode("path", location), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceFabric/locations/{location}/environments/{environment}/clusterVersions/{clusterVersion}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetByEnvironmentSender sends the GetByEnvironment request. The method will close the +// http.Response Body if it receives an error. +func (client ClusterVersionsClient) GetByEnvironmentSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetByEnvironmentResponder handles the response to the GetByEnvironment request. The method always +// closes the http.Response Body. +func (client ClusterVersionsClient) GetByEnvironmentResponder(resp *http.Response) (result ClusterCodeVersionsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets all available code versions for Service Fabric cluster resources by location. +// Parameters: +// location - the location for the cluster code versions. This is different from cluster location. +func (client ClusterVersionsClient) List(ctx context.Context, location string) (result ClusterCodeVersionsListResult, err error) { + req, err := client.ListPreparer(ctx, location) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClusterVersionsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicefabric.ClusterVersionsClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClusterVersionsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ClusterVersionsClient) 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 = "2018-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceFabric/locations/{location}/clusterVersions", 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 ClusterVersionsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ClusterVersionsClient) ListResponder(resp *http.Response) (result ClusterCodeVersionsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByEnvironment gets all available code versions for Service Fabric cluster resources by environment. +// Parameters: +// location - the location for the cluster code versions. This is different from cluster location. +// environment - the operating system of the cluster. The default means all. +func (client ClusterVersionsClient) ListByEnvironment(ctx context.Context, location string, environment string) (result ClusterCodeVersionsListResult, err error) { + req, err := client.ListByEnvironmentPreparer(ctx, location, environment) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClusterVersionsClient", "ListByEnvironment", nil, "Failure preparing request") + return + } + + resp, err := client.ListByEnvironmentSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicefabric.ClusterVersionsClient", "ListByEnvironment", resp, "Failure sending request") + return + } + + result, err = client.ListByEnvironmentResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClusterVersionsClient", "ListByEnvironment", resp, "Failure responding to request") + } + + return +} + +// ListByEnvironmentPreparer prepares the ListByEnvironment request. +func (client ClusterVersionsClient) ListByEnvironmentPreparer(ctx context.Context, location string, environment string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "environment": autorest.Encode("path", environment), + "location": autorest.Encode("path", location), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-02-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceFabric/locations/{location}/environments/{environment}/clusterVersions", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByEnvironmentSender sends the ListByEnvironment request. The method will close the +// http.Response Body if it receives an error. +func (client ClusterVersionsClient) ListByEnvironmentSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByEnvironmentResponder handles the response to the ListByEnvironment request. The method always +// closes the http.Response Body. +func (client ClusterVersionsClient) ListByEnvironmentResponder(resp *http.Response) (result ClusterCodeVersionsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/models.go new file mode 100644 index 0000000000000..1bef986368c89 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/models.go @@ -0,0 +1,3982 @@ +package servicefabric + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "encoding/json" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" + "net/http" +) + +// ClusterState enumerates the values for cluster state. +type ClusterState string + +const ( + // AutoScale ... + AutoScale ClusterState = "AutoScale" + // BaselineUpgrade ... + BaselineUpgrade ClusterState = "BaselineUpgrade" + // Deploying ... + Deploying ClusterState = "Deploying" + // EnforcingClusterVersion ... + EnforcingClusterVersion ClusterState = "EnforcingClusterVersion" + // Ready ... + Ready ClusterState = "Ready" + // UpdatingInfrastructure ... + UpdatingInfrastructure ClusterState = "UpdatingInfrastructure" + // UpdatingUserCertificate ... + UpdatingUserCertificate ClusterState = "UpdatingUserCertificate" + // UpdatingUserConfiguration ... + UpdatingUserConfiguration ClusterState = "UpdatingUserConfiguration" + // UpgradeServiceUnreachable ... + UpgradeServiceUnreachable ClusterState = "UpgradeServiceUnreachable" + // WaitingForNodes ... + WaitingForNodes ClusterState = "WaitingForNodes" +) + +// PossibleClusterStateValues returns an array of possible values for the ClusterState const type. +func PossibleClusterStateValues() []ClusterState { + return []ClusterState{AutoScale, BaselineUpgrade, Deploying, EnforcingClusterVersion, Ready, UpdatingInfrastructure, UpdatingUserCertificate, UpdatingUserConfiguration, UpgradeServiceUnreachable, WaitingForNodes} +} + +// DurabilityLevel enumerates the values for durability level. +type DurabilityLevel string + +const ( + // Bronze ... + Bronze DurabilityLevel = "Bronze" + // Gold ... + Gold DurabilityLevel = "Gold" + // Silver ... + Silver DurabilityLevel = "Silver" +) + +// PossibleDurabilityLevelValues returns an array of possible values for the DurabilityLevel const type. +func PossibleDurabilityLevelValues() []DurabilityLevel { + return []DurabilityLevel{Bronze, Gold, Silver} +} + +// Environment enumerates the values for environment. +type Environment string + +const ( + // Linux ... + Linux Environment = "Linux" + // Windows ... + Windows Environment = "Windows" +) + +// PossibleEnvironmentValues returns an array of possible values for the Environment const type. +func PossibleEnvironmentValues() []Environment { + return []Environment{Linux, Windows} +} + +// MoveCost enumerates the values for move cost. +type MoveCost string + +const ( + // High Specifies the move cost of the service as High. The value is 3. + High MoveCost = "High" + // Low Specifies the move cost of the service as Low. The value is 1. + Low MoveCost = "Low" + // Medium Specifies the move cost of the service as Medium. The value is 2. + Medium MoveCost = "Medium" + // Zero Zero move cost. This value is zero. + Zero MoveCost = "Zero" +) + +// PossibleMoveCostValues returns an array of possible values for the MoveCost const type. +func PossibleMoveCostValues() []MoveCost { + return []MoveCost{High, Low, Medium, Zero} +} + +// PartitionScheme enumerates the values for partition scheme. +type PartitionScheme string + +const ( + // Invalid Indicates the partition kind is invalid. All Service Fabric enumerations have the invalid type. + // The value is zero. + Invalid PartitionScheme = "Invalid" + // Named Indicates that the partition is based on string names, and is a NamedPartitionSchemeDescription + // object. The value is 3 + Named PartitionScheme = "Named" + // Singleton Indicates that the partition is based on string names, and is a + // SingletonPartitionSchemeDescription object, The value is 1. + Singleton PartitionScheme = "Singleton" + // UniformInt64Range Indicates that the partition is based on Int64 key ranges, and is a + // UniformInt64RangePartitionSchemeDescription object. The value is 2. + UniformInt64Range PartitionScheme = "UniformInt64Range" +) + +// PossiblePartitionSchemeValues returns an array of possible values for the PartitionScheme const type. +func PossiblePartitionSchemeValues() []PartitionScheme { + return []PartitionScheme{Invalid, Named, Singleton, UniformInt64Range} +} + +// PartitionSchemeBasicPartitionSchemeDescription enumerates the values for partition scheme basic partition +// scheme description. +type PartitionSchemeBasicPartitionSchemeDescription string + +const ( + // PartitionSchemeNamed ... + PartitionSchemeNamed PartitionSchemeBasicPartitionSchemeDescription = "Named" + // PartitionSchemePartitionSchemeDescription ... + PartitionSchemePartitionSchemeDescription PartitionSchemeBasicPartitionSchemeDescription = "PartitionSchemeDescription" + // PartitionSchemeSingleton ... + PartitionSchemeSingleton PartitionSchemeBasicPartitionSchemeDescription = "Singleton" + // PartitionSchemeUniformInt64Range ... + PartitionSchemeUniformInt64Range PartitionSchemeBasicPartitionSchemeDescription = "UniformInt64Range" +) + +// PossiblePartitionSchemeBasicPartitionSchemeDescriptionValues returns an array of possible values for the PartitionSchemeBasicPartitionSchemeDescription const type. +func PossiblePartitionSchemeBasicPartitionSchemeDescriptionValues() []PartitionSchemeBasicPartitionSchemeDescription { + return []PartitionSchemeBasicPartitionSchemeDescription{PartitionSchemeNamed, PartitionSchemePartitionSchemeDescription, PartitionSchemeSingleton, PartitionSchemeUniformInt64Range} +} + +// ProvisioningState enumerates the values for provisioning state. +type ProvisioningState string + +const ( + // Canceled ... + Canceled ProvisioningState = "Canceled" + // Failed ... + Failed ProvisioningState = "Failed" + // 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{Canceled, Failed, Succeeded, Updating} +} + +// ReliabilityLevel enumerates the values for reliability level. +type ReliabilityLevel string + +const ( + // ReliabilityLevelBronze ... + ReliabilityLevelBronze ReliabilityLevel = "Bronze" + // ReliabilityLevelGold ... + ReliabilityLevelGold ReliabilityLevel = "Gold" + // ReliabilityLevelNone ... + ReliabilityLevelNone ReliabilityLevel = "None" + // ReliabilityLevelPlatinum ... + ReliabilityLevelPlatinum ReliabilityLevel = "Platinum" + // ReliabilityLevelSilver ... + ReliabilityLevelSilver ReliabilityLevel = "Silver" +) + +// PossibleReliabilityLevelValues returns an array of possible values for the ReliabilityLevel const type. +func PossibleReliabilityLevelValues() []ReliabilityLevel { + return []ReliabilityLevel{ReliabilityLevelBronze, ReliabilityLevelGold, ReliabilityLevelNone, ReliabilityLevelPlatinum, ReliabilityLevelSilver} +} + +// ReliabilityLevel1 enumerates the values for reliability level 1. +type ReliabilityLevel1 string + +const ( + // ReliabilityLevel1Bronze ... + ReliabilityLevel1Bronze ReliabilityLevel1 = "Bronze" + // ReliabilityLevel1Gold ... + ReliabilityLevel1Gold ReliabilityLevel1 = "Gold" + // ReliabilityLevel1None ... + ReliabilityLevel1None ReliabilityLevel1 = "None" + // ReliabilityLevel1Platinum ... + ReliabilityLevel1Platinum ReliabilityLevel1 = "Platinum" + // ReliabilityLevel1Silver ... + ReliabilityLevel1Silver ReliabilityLevel1 = "Silver" +) + +// PossibleReliabilityLevel1Values returns an array of possible values for the ReliabilityLevel1 const type. +func PossibleReliabilityLevel1Values() []ReliabilityLevel1 { + return []ReliabilityLevel1{ReliabilityLevel1Bronze, ReliabilityLevel1Gold, ReliabilityLevel1None, ReliabilityLevel1Platinum, ReliabilityLevel1Silver} +} + +// ServiceCorrelationScheme enumerates the values for service correlation scheme. +type ServiceCorrelationScheme string + +const ( + // ServiceCorrelationSchemeAffinity Indicates that this service has an affinity relationship with another + // service. Provided for backwards compatibility, consider preferring the Aligned or NonAlignedAffinity + // options. The value is 1. + ServiceCorrelationSchemeAffinity ServiceCorrelationScheme = "Affinity" + // ServiceCorrelationSchemeAlignedAffinity Aligned affinity ensures that the primaries of the partitions of + // the affinitized services are collocated on the same nodes. This is the default and is the same as + // selecting the Affinity scheme. The value is 2. + ServiceCorrelationSchemeAlignedAffinity ServiceCorrelationScheme = "AlignedAffinity" + // ServiceCorrelationSchemeInvalid An invalid correlation scheme. Cannot be used. The value is zero. + ServiceCorrelationSchemeInvalid ServiceCorrelationScheme = "Invalid" + // ServiceCorrelationSchemeNonAlignedAffinity Non-Aligned affinity guarantees that all replicas of each + // service will be placed on the same nodes. Unlike Aligned Affinity, this does not guarantee that replicas + // of particular role will be collocated. The value is 3. + ServiceCorrelationSchemeNonAlignedAffinity ServiceCorrelationScheme = "NonAlignedAffinity" +) + +// PossibleServiceCorrelationSchemeValues returns an array of possible values for the ServiceCorrelationScheme const type. +func PossibleServiceCorrelationSchemeValues() []ServiceCorrelationScheme { + return []ServiceCorrelationScheme{ServiceCorrelationSchemeAffinity, ServiceCorrelationSchemeAlignedAffinity, ServiceCorrelationSchemeInvalid, ServiceCorrelationSchemeNonAlignedAffinity} +} + +// ServiceKind enumerates the values for service kind. +type ServiceKind string + +const ( + // ServiceKindInvalid Indicates the service kind is invalid. All Service Fabric enumerations have the + // invalid type. The value is zero. + ServiceKindInvalid ServiceKind = "Invalid" + // ServiceKindStateful Uses Service Fabric to make its state or part of its state highly available and + // reliable. The value is 2. + ServiceKindStateful ServiceKind = "Stateful" + // ServiceKindStateless Does not use Service Fabric to make its state highly available or reliable. The + // value is 1. + ServiceKindStateless ServiceKind = "Stateless" +) + +// PossibleServiceKindValues returns an array of possible values for the ServiceKind const type. +func PossibleServiceKindValues() []ServiceKind { + return []ServiceKind{ServiceKindInvalid, ServiceKindStateful, ServiceKindStateless} +} + +// ServiceKindBasicServiceResourceProperties enumerates the values for service kind basic service resource +// properties. +type ServiceKindBasicServiceResourceProperties string + +const ( + // ServiceKindServiceResourceProperties ... + ServiceKindServiceResourceProperties ServiceKindBasicServiceResourceProperties = "ServiceResourceProperties" + // ServiceKindStateful1 ... + ServiceKindStateful1 ServiceKindBasicServiceResourceProperties = "Stateful" + // ServiceKindStateless1 ... + ServiceKindStateless1 ServiceKindBasicServiceResourceProperties = "Stateless" +) + +// PossibleServiceKindBasicServiceResourcePropertiesValues returns an array of possible values for the ServiceKindBasicServiceResourceProperties const type. +func PossibleServiceKindBasicServiceResourcePropertiesValues() []ServiceKindBasicServiceResourceProperties { + return []ServiceKindBasicServiceResourceProperties{ServiceKindServiceResourceProperties, ServiceKindStateful1, ServiceKindStateless1} +} + +// ServiceKindBasicServiceResourceUpdateProperties enumerates the values for service kind basic service +// resource update properties. +type ServiceKindBasicServiceResourceUpdateProperties string + +const ( + // ServiceKindBasicServiceResourceUpdatePropertiesServiceKindServiceResourceUpdateProperties ... + ServiceKindBasicServiceResourceUpdatePropertiesServiceKindServiceResourceUpdateProperties ServiceKindBasicServiceResourceUpdateProperties = "ServiceResourceUpdateProperties" + // ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateful ... + ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateful ServiceKindBasicServiceResourceUpdateProperties = "Stateful" + // ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateless ... + ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateless ServiceKindBasicServiceResourceUpdateProperties = "Stateless" +) + +// PossibleServiceKindBasicServiceResourceUpdatePropertiesValues returns an array of possible values for the ServiceKindBasicServiceResourceUpdateProperties const type. +func PossibleServiceKindBasicServiceResourceUpdatePropertiesValues() []ServiceKindBasicServiceResourceUpdateProperties { + return []ServiceKindBasicServiceResourceUpdateProperties{ServiceKindBasicServiceResourceUpdatePropertiesServiceKindServiceResourceUpdateProperties, ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateful, ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateless} +} + +// ServiceLoadMetricWeight enumerates the values for service load metric weight. +type ServiceLoadMetricWeight string + +const ( + // ServiceLoadMetricWeightHigh Specifies the metric weight of the service load as High. The value is 3. + ServiceLoadMetricWeightHigh ServiceLoadMetricWeight = "High" + // ServiceLoadMetricWeightLow Specifies the metric weight of the service load as Low. The value is 1. + ServiceLoadMetricWeightLow ServiceLoadMetricWeight = "Low" + // ServiceLoadMetricWeightMedium Specifies the metric weight of the service load as Medium. The value is 2. + ServiceLoadMetricWeightMedium ServiceLoadMetricWeight = "Medium" + // ServiceLoadMetricWeightZero Disables resource balancing for this metric. This value is zero. + ServiceLoadMetricWeightZero ServiceLoadMetricWeight = "Zero" +) + +// PossibleServiceLoadMetricWeightValues returns an array of possible values for the ServiceLoadMetricWeight const type. +func PossibleServiceLoadMetricWeightValues() []ServiceLoadMetricWeight { + return []ServiceLoadMetricWeight{ServiceLoadMetricWeightHigh, ServiceLoadMetricWeightLow, ServiceLoadMetricWeightMedium, ServiceLoadMetricWeightZero} +} + +// ServicePlacementPolicyType enumerates the values for service placement policy type. +type ServicePlacementPolicyType string + +const ( + // ServicePlacementPolicyTypeInvalid Indicates the type of the placement policy is invalid. All Service + // Fabric enumerations have the invalid type. The value is zero. + ServicePlacementPolicyTypeInvalid ServicePlacementPolicyType = "Invalid" + // ServicePlacementPolicyTypeInvalidDomain Indicates that the ServicePlacementPolicyDescription is of type + // ServicePlacementInvalidDomainPolicyDescription, which indicates that a particular fault or upgrade + // domain cannot be used for placement of this service. The value is 1. + ServicePlacementPolicyTypeInvalidDomain ServicePlacementPolicyType = "InvalidDomain" + // ServicePlacementPolicyTypeNonPartiallyPlaceService Indicates that the ServicePlacementPolicyDescription + // is of type ServicePlacementNonPartiallyPlaceServicePolicyDescription, which indicates that if possible + // all replicas of a particular partition of the service should be placed atomically. The value is 5. + ServicePlacementPolicyTypeNonPartiallyPlaceService ServicePlacementPolicyType = "NonPartiallyPlaceService" + // ServicePlacementPolicyTypePreferredPrimaryDomain Indicates that the ServicePlacementPolicyDescription is + // of type ServicePlacementPreferPrimaryDomainPolicyDescription, which indicates that if possible the + // Primary replica for the partitions of the service should be located in a particular domain as an + // optimization. The value is 3. + ServicePlacementPolicyTypePreferredPrimaryDomain ServicePlacementPolicyType = "PreferredPrimaryDomain" + // ServicePlacementPolicyTypeRequiredDomain Indicates that the ServicePlacementPolicyDescription is of type + // ServicePlacementRequireDomainDistributionPolicyDescription indicating that the replicas of the service + // must be placed in a specific domain. The value is 2. + ServicePlacementPolicyTypeRequiredDomain ServicePlacementPolicyType = "RequiredDomain" + // ServicePlacementPolicyTypeRequiredDomainDistribution Indicates that the + // ServicePlacementPolicyDescription is of type ServicePlacementRequireDomainDistributionPolicyDescription, + // indicating that the system will disallow placement of any two replicas from the same partition in the + // same domain at any time. The value is 4. + ServicePlacementPolicyTypeRequiredDomainDistribution ServicePlacementPolicyType = "RequiredDomainDistribution" +) + +// PossibleServicePlacementPolicyTypeValues returns an array of possible values for the ServicePlacementPolicyType const type. +func PossibleServicePlacementPolicyTypeValues() []ServicePlacementPolicyType { + return []ServicePlacementPolicyType{ServicePlacementPolicyTypeInvalid, ServicePlacementPolicyTypeInvalidDomain, ServicePlacementPolicyTypeNonPartiallyPlaceService, ServicePlacementPolicyTypePreferredPrimaryDomain, ServicePlacementPolicyTypeRequiredDomain, ServicePlacementPolicyTypeRequiredDomainDistribution} +} + +// Type enumerates the values for type. +type Type string + +const ( + // TypeServicePlacementPolicyDescription ... + TypeServicePlacementPolicyDescription Type = "ServicePlacementPolicyDescription" +) + +// PossibleTypeValues returns an array of possible values for the Type const type. +func PossibleTypeValues() []Type { + return []Type{TypeServicePlacementPolicyDescription} +} + +// UpgradeMode enumerates the values for upgrade mode. +type UpgradeMode string + +const ( + // Automatic ... + Automatic UpgradeMode = "Automatic" + // Manual ... + Manual UpgradeMode = "Manual" +) + +// PossibleUpgradeModeValues returns an array of possible values for the UpgradeMode const type. +func PossibleUpgradeModeValues() []UpgradeMode { + return []UpgradeMode{Automatic, Manual} +} + +// UpgradeMode1 enumerates the values for upgrade mode 1. +type UpgradeMode1 string + +const ( + // UpgradeMode1Automatic ... + UpgradeMode1Automatic UpgradeMode1 = "Automatic" + // UpgradeMode1Manual ... + UpgradeMode1Manual UpgradeMode1 = "Manual" +) + +// PossibleUpgradeMode1Values returns an array of possible values for the UpgradeMode1 const type. +func PossibleUpgradeMode1Values() []UpgradeMode1 { + return []UpgradeMode1{UpgradeMode1Automatic, UpgradeMode1Manual} +} + +// X509StoreName enumerates the values for x509 store name. +type X509StoreName string + +const ( + // AddressBook ... + AddressBook X509StoreName = "AddressBook" + // AuthRoot ... + AuthRoot X509StoreName = "AuthRoot" + // CertificateAuthority ... + CertificateAuthority X509StoreName = "CertificateAuthority" + // Disallowed ... + Disallowed X509StoreName = "Disallowed" + // My ... + My X509StoreName = "My" + // Root ... + Root X509StoreName = "Root" + // TrustedPeople ... + TrustedPeople X509StoreName = "TrustedPeople" + // TrustedPublisher ... + TrustedPublisher X509StoreName = "TrustedPublisher" +) + +// PossibleX509StoreNameValues returns an array of possible values for the X509StoreName const type. +func PossibleX509StoreNameValues() []X509StoreName { + return []X509StoreName{AddressBook, AuthRoot, CertificateAuthority, Disallowed, My, Root, TrustedPeople, TrustedPublisher} +} + +// X509StoreName1 enumerates the values for x509 store name 1. +type X509StoreName1 string + +const ( + // X509StoreName1AddressBook ... + X509StoreName1AddressBook X509StoreName1 = "AddressBook" + // X509StoreName1AuthRoot ... + X509StoreName1AuthRoot X509StoreName1 = "AuthRoot" + // X509StoreName1CertificateAuthority ... + X509StoreName1CertificateAuthority X509StoreName1 = "CertificateAuthority" + // X509StoreName1Disallowed ... + X509StoreName1Disallowed X509StoreName1 = "Disallowed" + // X509StoreName1My ... + X509StoreName1My X509StoreName1 = "My" + // X509StoreName1Root ... + X509StoreName1Root X509StoreName1 = "Root" + // X509StoreName1TrustedPeople ... + X509StoreName1TrustedPeople X509StoreName1 = "TrustedPeople" + // X509StoreName1TrustedPublisher ... + X509StoreName1TrustedPublisher X509StoreName1 = "TrustedPublisher" +) + +// PossibleX509StoreName1Values returns an array of possible values for the X509StoreName1 const type. +func PossibleX509StoreName1Values() []X509StoreName1 { + return []X509StoreName1{X509StoreName1AddressBook, X509StoreName1AuthRoot, X509StoreName1CertificateAuthority, X509StoreName1Disallowed, X509StoreName1My, X509StoreName1Root, X509StoreName1TrustedPeople, X509StoreName1TrustedPublisher} +} + +// ApplicationDeltaHealthPolicy defines a delta health policy used to evaluate the health of an application or one +// of its child entities when upgrading the cluster. +type ApplicationDeltaHealthPolicy struct { + // DefaultServiceTypeDeltaHealthPolicy - The delta health policy used by default to evaluate the health of a service type when upgrading the cluster. + DefaultServiceTypeDeltaHealthPolicy *ServiceTypeDeltaHealthPolicy `json:"defaultServiceTypeDeltaHealthPolicy,omitempty"` + // ServiceTypeDeltaHealthPolicies - The map with service type delta health policy per service type name. The map is empty by default. + ServiceTypeDeltaHealthPolicies map[string]*ServiceTypeDeltaHealthPolicy `json:"serviceTypeDeltaHealthPolicies"` +} + +// MarshalJSON is the custom marshaler for ApplicationDeltaHealthPolicy. +func (adhp ApplicationDeltaHealthPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if adhp.DefaultServiceTypeDeltaHealthPolicy != nil { + objectMap["defaultServiceTypeDeltaHealthPolicy"] = adhp.DefaultServiceTypeDeltaHealthPolicy + } + if adhp.ServiceTypeDeltaHealthPolicies != nil { + objectMap["serviceTypeDeltaHealthPolicies"] = adhp.ServiceTypeDeltaHealthPolicies + } + return json.Marshal(objectMap) +} + +// ApplicationHealthPolicy defines a health policy used to evaluate the health of an application or one of its +// children entities. +type ApplicationHealthPolicy struct { + // DefaultServiceTypeHealthPolicy - The health policy used by default to evaluate the health of a service type. + DefaultServiceTypeHealthPolicy *ServiceTypeHealthPolicy `json:"defaultServiceTypeHealthPolicy,omitempty"` + // ServiceTypeHealthPolicies - The map with service type health policy per service type name. The map is empty by default. + ServiceTypeHealthPolicies map[string]*ServiceTypeHealthPolicy `json:"serviceTypeHealthPolicies"` + // ConsiderWarningAsError - Indicates whether warnings are treated with the same severity as errors. + ConsiderWarningAsError *bool `json:"ConsiderWarningAsError,omitempty"` + // MaxPercentUnhealthyDeployedApplications - The maximum allowed percentage of unhealthy deployed applications. Allowed values are Byte values from zero to 100. + // The percentage represents the maximum tolerated percentage of deployed applications that can be unhealthy before the application is considered in error. + // This is calculated by dividing the number of unhealthy deployed applications over the number of nodes where the application is currently deployed on in the cluster. + // The computation rounds up to tolerate one failure on small numbers of nodes. Default percentage is zero. + MaxPercentUnhealthyDeployedApplications *int32 `json:"MaxPercentUnhealthyDeployedApplications,omitempty"` + // DefaultServiceTypeHealthPolicy1 - The health policy used by default to evaluate the health of a service type. + DefaultServiceTypeHealthPolicy1 *ServiceTypeHealthPolicy `json:"DefaultServiceTypeHealthPolicy,omitempty"` + // ServiceTypeHealthPolicyMap - The map with service type health policy per service type name. The map is empty by default. + ServiceTypeHealthPolicyMap map[string]*ServiceTypeHealthPolicy `json:"ServiceTypeHealthPolicyMap"` +} + +// MarshalJSON is the custom marshaler for ApplicationHealthPolicy. +func (ahp ApplicationHealthPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ahp.DefaultServiceTypeHealthPolicy != nil { + objectMap["defaultServiceTypeHealthPolicy"] = ahp.DefaultServiceTypeHealthPolicy + } + if ahp.ServiceTypeHealthPolicies != nil { + objectMap["serviceTypeHealthPolicies"] = ahp.ServiceTypeHealthPolicies + } + if ahp.ConsiderWarningAsError != nil { + objectMap["ConsiderWarningAsError"] = ahp.ConsiderWarningAsError + } + if ahp.MaxPercentUnhealthyDeployedApplications != nil { + objectMap["MaxPercentUnhealthyDeployedApplications"] = ahp.MaxPercentUnhealthyDeployedApplications + } + if ahp.DefaultServiceTypeHealthPolicy1 != nil { + objectMap["DefaultServiceTypeHealthPolicy"] = ahp.DefaultServiceTypeHealthPolicy1 + } + if ahp.ServiceTypeHealthPolicyMap != nil { + objectMap["ServiceTypeHealthPolicyMap"] = ahp.ServiceTypeHealthPolicyMap + } + return json.Marshal(objectMap) +} + +// ApplicationMetricDescription describes capacity information for a custom resource balancing metric. This can be +// used to limit the total consumption of this metric by the services of this application. +type ApplicationMetricDescription struct { + // Name - The name of the metric. + Name *string `json:"Name,omitempty"` + // MaximumCapacity - The maximum node capacity for Service Fabric application. + // This is the maximum Load for an instance of this application on a single node. Even if the capacity of node is greater than this value, Service Fabric will limit the total load of services within the application on each node to this value. + // If set to zero, capacity for this metric is unlimited on each node. + // When creating a new application with application capacity defined, the product of MaximumNodes and this value must always be smaller than or equal to TotalApplicationCapacity. + // When updating existing application with application capacity, the product of MaximumNodes and this value must always be smaller than or equal to TotalApplicationCapacity. + MaximumCapacity *int64 `json:"MaximumCapacity,omitempty"` + // ReservationCapacity - The node reservation capacity for Service Fabric application. + // This is the amount of load which is reserved on nodes which have instances of this application. + // If MinimumNodes is specified, then the product of these values will be the capacity reserved in the cluster for the application. + // If set to zero, no capacity is reserved for this metric. + // When setting application capacity or when updating application capacity; this value must be smaller than or equal to MaximumCapacity for each metric. + ReservationCapacity *int64 `json:"ReservationCapacity,omitempty"` + // TotalApplicationCapacity - The total metric capacity for Service Fabric application. + // This is the total metric capacity for this application in the cluster. Service Fabric will try to limit the sum of loads of services within the application to this value. + // When creating a new application with application capacity defined, the product of MaximumNodes and MaximumCapacity must always be smaller than or equal to this value. + TotalApplicationCapacity *int64 `json:"TotalApplicationCapacity,omitempty"` +} + +// ApplicationResource the application resource. +type ApplicationResource struct { + autorest.Response `json:"-"` + // ApplicationResourceProperties - The application resource properties. + *ApplicationResourceProperties `json:"properties,omitempty"` + // ID - Azure resource identifier. + ID *string `json:"id,omitempty"` + // Name - Azure resource name. + Name *string `json:"name,omitempty"` + // Type - Azure resource type. + Type *string `json:"type,omitempty"` + // Location - Azure resource location. + Location *string `json:"location,omitempty"` +} + +// MarshalJSON is the custom marshaler for ApplicationResource. +func (ar ApplicationResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ar.ApplicationResourceProperties != nil { + objectMap["properties"] = ar.ApplicationResourceProperties + } + if ar.ID != nil { + objectMap["id"] = ar.ID + } + if ar.Name != nil { + objectMap["name"] = ar.Name + } + if ar.Type != nil { + objectMap["type"] = ar.Type + } + if ar.Location != nil { + objectMap["location"] = ar.Location + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ApplicationResource struct. +func (ar *ApplicationResource) 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 applicationResourceProperties ApplicationResourceProperties + err = json.Unmarshal(*v, &applicationResourceProperties) + if err != nil { + return err + } + ar.ApplicationResourceProperties = &applicationResourceProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + ar.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + ar.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + ar.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + ar.Location = &location + } + } + } + + return nil +} + +// ApplicationResourceList the list of application resources. +type ApplicationResourceList struct { + autorest.Response `json:"-"` + Value *[]ApplicationResource `json:"value,omitempty"` +} + +// ApplicationResourceProperties the application resource properties. +type ApplicationResourceProperties struct { + // ProvisioningState - The current deployment or provisioning state, which only appears in the response + ProvisioningState *string `json:"provisioningState,omitempty"` + // TypeName - The application type name as defined in the application manifest. + TypeName *string `json:"typeName,omitempty"` + // TypeVersion - The version of the application type as defined in the application manifest. + TypeVersion *string `json:"typeVersion,omitempty"` + // Parameters - List of application parameters with overridden values from their default values specified in the application manifest. + Parameters map[string]*string `json:"parameters"` + // UpgradePolicy - Describes the policy for a monitored application upgrade. + UpgradePolicy *ApplicationUpgradePolicy `json:"upgradePolicy,omitempty"` + // MinimumNodes - The minimum number of nodes where Service Fabric will reserve capacity for this application. Note that this does not mean that the services of this application will be placed on all of those nodes. If this property is set to zero, no capacity will be reserved. The value of this property cannot be more than the value of the MaximumNodes property. + MinimumNodes *int64 `json:"minimumNodes,omitempty"` + // MaximumNodes - The maximum number of nodes where Service Fabric will reserve capacity for this application. Note that this does not mean that the services of this application will be placed on all of those nodes. By default, the value of this property is zero and it means that the services can be placed on any node. + MaximumNodes *int64 `json:"maximumNodes,omitempty"` + // RemoveApplicationCapacity - Remove the current application capacity settings. + RemoveApplicationCapacity *bool `json:"removeApplicationCapacity,omitempty"` + // Metrics - List of application capacity metric description. + Metrics *[]ApplicationMetricDescription `json:"metrics,omitempty"` +} + +// MarshalJSON is the custom marshaler for ApplicationResourceProperties. +func (arp ApplicationResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if arp.ProvisioningState != nil { + objectMap["provisioningState"] = arp.ProvisioningState + } + if arp.TypeName != nil { + objectMap["typeName"] = arp.TypeName + } + if arp.TypeVersion != nil { + objectMap["typeVersion"] = arp.TypeVersion + } + if arp.Parameters != nil { + objectMap["parameters"] = arp.Parameters + } + if arp.UpgradePolicy != nil { + objectMap["upgradePolicy"] = arp.UpgradePolicy + } + if arp.MinimumNodes != nil { + objectMap["minimumNodes"] = arp.MinimumNodes + } + if arp.MaximumNodes != nil { + objectMap["maximumNodes"] = arp.MaximumNodes + } + if arp.RemoveApplicationCapacity != nil { + objectMap["removeApplicationCapacity"] = arp.RemoveApplicationCapacity + } + if arp.Metrics != nil { + objectMap["metrics"] = arp.Metrics + } + return json.Marshal(objectMap) +} + +// ApplicationResourceUpdate the application resource for patch operations. +type ApplicationResourceUpdate struct { + autorest.Response `json:"-"` + // ApplicationResourceUpdateProperties - The application resource properties for patch operations. + *ApplicationResourceUpdateProperties `json:"properties,omitempty"` + // ID - Azure resource identifier. + ID *string `json:"id,omitempty"` + // Name - Azure resource name. + Name *string `json:"name,omitempty"` + // Type - Azure resource type. + Type *string `json:"type,omitempty"` + // Location - Azure resource location. + Location *string `json:"location,omitempty"` +} + +// MarshalJSON is the custom marshaler for ApplicationResourceUpdate. +func (aru ApplicationResourceUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if aru.ApplicationResourceUpdateProperties != nil { + objectMap["properties"] = aru.ApplicationResourceUpdateProperties + } + if aru.ID != nil { + objectMap["id"] = aru.ID + } + if aru.Name != nil { + objectMap["name"] = aru.Name + } + if aru.Type != nil { + objectMap["type"] = aru.Type + } + if aru.Location != nil { + objectMap["location"] = aru.Location + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ApplicationResourceUpdate struct. +func (aru *ApplicationResourceUpdate) 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 applicationResourceUpdateProperties ApplicationResourceUpdateProperties + err = json.Unmarshal(*v, &applicationResourceUpdateProperties) + if err != nil { + return err + } + aru.ApplicationResourceUpdateProperties = &applicationResourceUpdateProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + aru.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + aru.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + aru.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + aru.Location = &location + } + } + } + + return nil +} + +// ApplicationResourceUpdateProperties the application resource properties for patch operations. +type ApplicationResourceUpdateProperties struct { + // TypeVersion - The version of the application type as defined in the application manifest. + TypeVersion *string `json:"typeVersion,omitempty"` + // Parameters - List of application parameters with overridden values from their default values specified in the application manifest. + Parameters map[string]*string `json:"parameters"` + // UpgradePolicy - Describes the policy for a monitored application upgrade. + UpgradePolicy *ApplicationUpgradePolicy `json:"upgradePolicy,omitempty"` + // MinimumNodes - The minimum number of nodes where Service Fabric will reserve capacity for this application. Note that this does not mean that the services of this application will be placed on all of those nodes. If this property is set to zero, no capacity will be reserved. The value of this property cannot be more than the value of the MaximumNodes property. + MinimumNodes *int64 `json:"minimumNodes,omitempty"` + // MaximumNodes - The maximum number of nodes where Service Fabric will reserve capacity for this application. Note that this does not mean that the services of this application will be placed on all of those nodes. By default, the value of this property is zero and it means that the services can be placed on any node. + MaximumNodes *int64 `json:"maximumNodes,omitempty"` + // RemoveApplicationCapacity - Remove the current application capacity settings. + RemoveApplicationCapacity *bool `json:"removeApplicationCapacity,omitempty"` + // Metrics - List of application capacity metric description. + Metrics *[]ApplicationMetricDescription `json:"metrics,omitempty"` +} + +// MarshalJSON is the custom marshaler for ApplicationResourceUpdateProperties. +func (arup ApplicationResourceUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if arup.TypeVersion != nil { + objectMap["typeVersion"] = arup.TypeVersion + } + if arup.Parameters != nil { + objectMap["parameters"] = arup.Parameters + } + if arup.UpgradePolicy != nil { + objectMap["upgradePolicy"] = arup.UpgradePolicy + } + if arup.MinimumNodes != nil { + objectMap["minimumNodes"] = arup.MinimumNodes + } + if arup.MaximumNodes != nil { + objectMap["maximumNodes"] = arup.MaximumNodes + } + if arup.RemoveApplicationCapacity != nil { + objectMap["removeApplicationCapacity"] = arup.RemoveApplicationCapacity + } + if arup.Metrics != nil { + objectMap["metrics"] = arup.Metrics + } + return json.Marshal(objectMap) +} + +// ApplicationsCreateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type ApplicationsCreateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ApplicationsCreateFuture) Result(client ApplicationsClient) (ar ApplicationResource, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsCreateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicefabric.ApplicationsCreateFuture") + 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.CreateResponder(ar.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsCreateFuture", "Result", ar.Response.Response, "Failure responding to request") + } + } + return +} + +// ApplicationsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type ApplicationsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ApplicationsDeleteFuture) Result(client ApplicationsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicefabric.ApplicationsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ApplicationsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type ApplicationsUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ApplicationsUpdateFuture) Result(client ApplicationsClient) (aru ApplicationResourceUpdate, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicefabric.ApplicationsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if aru.Response.Response, err = future.GetResult(sender); err == nil && aru.Response.Response.StatusCode != http.StatusNoContent { + aru, err = client.UpdateResponder(aru.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationsUpdateFuture", "Result", aru.Response.Response, "Failure responding to request") + } + } + return +} + +// ApplicationTypeResource the application type name resource +type ApplicationTypeResource struct { + autorest.Response `json:"-"` + // ApplicationTypeResourceProperties - The application type name properties + *ApplicationTypeResourceProperties `json:"properties,omitempty"` + // ID - Azure resource identifier. + ID *string `json:"id,omitempty"` + // Name - Azure resource name. + Name *string `json:"name,omitempty"` + // Type - Azure resource type. + Type *string `json:"type,omitempty"` + // Location - Azure resource location. + Location *string `json:"location,omitempty"` +} + +// MarshalJSON is the custom marshaler for ApplicationTypeResource. +func (atr ApplicationTypeResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if atr.ApplicationTypeResourceProperties != nil { + objectMap["properties"] = atr.ApplicationTypeResourceProperties + } + if atr.ID != nil { + objectMap["id"] = atr.ID + } + if atr.Name != nil { + objectMap["name"] = atr.Name + } + if atr.Type != nil { + objectMap["type"] = atr.Type + } + if atr.Location != nil { + objectMap["location"] = atr.Location + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ApplicationTypeResource struct. +func (atr *ApplicationTypeResource) 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 applicationTypeResourceProperties ApplicationTypeResourceProperties + err = json.Unmarshal(*v, &applicationTypeResourceProperties) + if err != nil { + return err + } + atr.ApplicationTypeResourceProperties = &applicationTypeResourceProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + atr.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + atr.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + atr.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + atr.Location = &location + } + } + } + + return nil +} + +// ApplicationTypeResourceList the list of application type names. +type ApplicationTypeResourceList struct { + autorest.Response `json:"-"` + Value *[]ApplicationTypeResource `json:"value,omitempty"` +} + +// ApplicationTypeResourceProperties the application type name properties +type ApplicationTypeResourceProperties struct { + // ProvisioningState - The current deployment or provisioning state, which only appears in the response. + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// ApplicationTypesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ApplicationTypesDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ApplicationTypesDeleteFuture) Result(client ApplicationTypesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicefabric.ApplicationTypesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ApplicationTypeVersionResource an application type version resource for the specified application type name +// resource. +type ApplicationTypeVersionResource struct { + autorest.Response `json:"-"` + // ApplicationTypeVersionResourceProperties - The properties of the application type version resource. + *ApplicationTypeVersionResourceProperties `json:"properties,omitempty"` + // ID - Azure resource identifier. + ID *string `json:"id,omitempty"` + // Name - Azure resource name. + Name *string `json:"name,omitempty"` + // Type - Azure resource type. + Type *string `json:"type,omitempty"` + // Location - Azure resource location. + Location *string `json:"location,omitempty"` +} + +// MarshalJSON is the custom marshaler for ApplicationTypeVersionResource. +func (atvr ApplicationTypeVersionResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if atvr.ApplicationTypeVersionResourceProperties != nil { + objectMap["properties"] = atvr.ApplicationTypeVersionResourceProperties + } + if atvr.ID != nil { + objectMap["id"] = atvr.ID + } + if atvr.Name != nil { + objectMap["name"] = atvr.Name + } + if atvr.Type != nil { + objectMap["type"] = atvr.Type + } + if atvr.Location != nil { + objectMap["location"] = atvr.Location + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ApplicationTypeVersionResource struct. +func (atvr *ApplicationTypeVersionResource) 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 applicationTypeVersionResourceProperties ApplicationTypeVersionResourceProperties + err = json.Unmarshal(*v, &applicationTypeVersionResourceProperties) + if err != nil { + return err + } + atvr.ApplicationTypeVersionResourceProperties = &applicationTypeVersionResourceProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + atvr.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + atvr.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + atvr.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + atvr.Location = &location + } + } + } + + return nil +} + +// ApplicationTypeVersionResourceList the list of application type version resources for the specified application +// type name resource. +type ApplicationTypeVersionResourceList struct { + autorest.Response `json:"-"` + Value *[]ApplicationTypeVersionResource `json:"value,omitempty"` +} + +// ApplicationTypeVersionResourceProperties the properties of the application type version resource. +type ApplicationTypeVersionResourceProperties struct { + // ProvisioningState - The current deployment or provisioning state, which only appears in the response + ProvisioningState *string `json:"provisioningState,omitempty"` + // AppPackageURL - The URL to the application package + AppPackageURL *string `json:"appPackageUrl,omitempty"` + // DefaultParameterList - List of application type parameters that can be overridden when creating or updating the application. + DefaultParameterList map[string]*string `json:"defaultParameterList"` +} + +// MarshalJSON is the custom marshaler for ApplicationTypeVersionResourceProperties. +func (atvrp ApplicationTypeVersionResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if atvrp.ProvisioningState != nil { + objectMap["provisioningState"] = atvrp.ProvisioningState + } + if atvrp.AppPackageURL != nil { + objectMap["appPackageUrl"] = atvrp.AppPackageURL + } + if atvrp.DefaultParameterList != nil { + objectMap["defaultParameterList"] = atvrp.DefaultParameterList + } + return json.Marshal(objectMap) +} + +// ApplicationTypeVersionsCreateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ApplicationTypeVersionsCreateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ApplicationTypeVersionsCreateFuture) Result(client ApplicationTypeVersionsClient) (atvr ApplicationTypeVersionResource, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypeVersionsCreateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicefabric.ApplicationTypeVersionsCreateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if atvr.Response.Response, err = future.GetResult(sender); err == nil && atvr.Response.Response.StatusCode != http.StatusNoContent { + atvr, err = client.CreateResponder(atvr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypeVersionsCreateFuture", "Result", atvr.Response.Response, "Failure responding to request") + } + } + return +} + +// ApplicationTypeVersionsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ApplicationTypeVersionsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ApplicationTypeVersionsDeleteFuture) Result(client ApplicationTypeVersionsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ApplicationTypeVersionsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicefabric.ApplicationTypeVersionsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ApplicationUpgradePolicy describes the policy for a monitored application upgrade. +type ApplicationUpgradePolicy struct { + // UpgradeReplicaSetCheckTimeout - The maximum amount of time to block processing of an upgrade domain and prevent loss of availability when there are unexpected issues. When this timeout expires, processing of the upgrade domain will proceed regardless of availability loss issues. The timeout is reset at the start of each upgrade domain. Valid values are between 0 and 42949672925 inclusive. (unsigned 32-bit integer). + UpgradeReplicaSetCheckTimeout *int64 `json:"upgradeReplicaSetCheckTimeout,omitempty"` + // ForceRestart - If true, then processes are forcefully restarted during upgrade even when the code version has not changed (the upgrade only changes configuration or data). + ForceRestart *bool `json:"forceRestart,omitempty"` + // RollingUpgradeMonitoringPolicy - The policy used for monitoring the application upgrade + RollingUpgradeMonitoringPolicy *RollingUpgradeMonitoringPolicy `json:"rollingUpgradeMonitoringPolicy,omitempty"` + // ApplicationHealthPolicy - Defines a health policy used to evaluate the health of an application or one of its children entities. + ApplicationHealthPolicy *ApplicationHealthPolicy `json:"applicationHealthPolicy,omitempty"` +} + +// AvailableOperationDisplay operation supported by Service Fabric resource provider +type AvailableOperationDisplay struct { + // Provider - The name of the provider. + Provider *string `json:"provider,omitempty"` + // Resource - The resource on which the operation is performed + Resource *string `json:"resource,omitempty"` + // Operation - The operation that can be performed. + Operation *string `json:"operation,omitempty"` + // Description - Operation description + Description *string `json:"description,omitempty"` +} + +// AzureActiveDirectory the settings to enable AAD authentication on the cluster. +type AzureActiveDirectory struct { + // TenantID - Azure active directory tenant id. + TenantID *string `json:"tenantId,omitempty"` + // ClusterApplication - Azure active directory cluster application id. + ClusterApplication *string `json:"clusterApplication,omitempty"` + // ClientApplication - Azure active directory client application id. + ClientApplication *string `json:"clientApplication,omitempty"` +} + +// CertificateDescription describes the certificate details. +type CertificateDescription struct { + // Thumbprint - Thumbprint of the primary certificate. + Thumbprint *string `json:"thumbprint,omitempty"` + // ThumbprintSecondary - Thumbprint of the secondary certificate. + ThumbprintSecondary *string `json:"thumbprintSecondary,omitempty"` + // X509StoreName - The local certificate store location. Possible values include: 'AddressBook', 'AuthRoot', 'CertificateAuthority', 'Disallowed', 'My', 'Root', 'TrustedPeople', 'TrustedPublisher' + X509StoreName X509StoreName `json:"x509StoreName,omitempty"` +} + +// ClientCertificateCommonName describes the client certificate details using common name. +type ClientCertificateCommonName struct { + // IsAdmin - Indicates if the client certificate has admin access to the cluster. Non admin clients can perform only read only operations on the cluster. + IsAdmin *bool `json:"isAdmin,omitempty"` + // CertificateCommonName - The common name of the client certificate. + CertificateCommonName *string `json:"certificateCommonName,omitempty"` + // CertificateIssuerThumbprint - The issuer thumbprint of the client certificate. + CertificateIssuerThumbprint *string `json:"certificateIssuerThumbprint,omitempty"` +} + +// ClientCertificateThumbprint describes the client certificate details using thumbprint. +type ClientCertificateThumbprint struct { + // IsAdmin - Indicates if the client certificate has admin access to the cluster. Non admin clients can perform only read only operations on the cluster. + IsAdmin *bool `json:"isAdmin,omitempty"` + // CertificateThumbprint - The thumbprint of the client certificate. + CertificateThumbprint *string `json:"certificateThumbprint,omitempty"` +} + +// Cluster the cluster resource +type Cluster struct { + autorest.Response `json:"-"` + // ClusterProperties - The cluster resource properties + *ClusterProperties `json:"properties,omitempty"` + // ID - Azure resource identifier. + ID *string `json:"id,omitempty"` + // Name - Azure resource name. + Name *string `json:"name,omitempty"` + // Type - Azure resource type. + Type *string `json:"type,omitempty"` + // Location - Azure resource location. + Location *string `json:"location,omitempty"` + // Tags - Azure resource tags. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Cluster. +func (c Cluster) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if c.ClusterProperties != nil { + objectMap["properties"] = c.ClusterProperties + } + if c.ID != nil { + objectMap["id"] = c.ID + } + if c.Name != nil { + objectMap["name"] = c.Name + } + if c.Type != nil { + objectMap["type"] = c.Type + } + if c.Location != nil { + objectMap["location"] = c.Location + } + if c.Tags != nil { + objectMap["tags"] = c.Tags + } + 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 "properties": + if v != nil { + var clusterProperties ClusterProperties + err = json.Unmarshal(*v, &clusterProperties) + if err != nil { + return err + } + c.ClusterProperties = &clusterProperties + } + 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 + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + c.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + c.Tags = tags + } + } + } + + return nil +} + +// ClusterCodeVersionsListResult the list results of the ServiceFabric runtime versions. +type ClusterCodeVersionsListResult struct { + autorest.Response `json:"-"` + Value *[]ClusterCodeVersionsResult `json:"value,omitempty"` + // NextLink - The URL to use for getting the next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ClusterCodeVersionsResult the result of the ServiceFabric runtime versions +type ClusterCodeVersionsResult struct { + // ID - The identification of the result + ID *string `json:"id,omitempty"` + // Name - The name of the result + Name *string `json:"name,omitempty"` + // Type - The result resource type + Type *string `json:"type,omitempty"` + // ClusterVersionDetails - The detail of the Service Fabric runtime version result + *ClusterVersionDetails `json:"properties,omitempty"` +} + +// MarshalJSON is the custom marshaler for ClusterCodeVersionsResult. +func (ccvr ClusterCodeVersionsResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ccvr.ID != nil { + objectMap["id"] = ccvr.ID + } + if ccvr.Name != nil { + objectMap["name"] = ccvr.Name + } + if ccvr.Type != nil { + objectMap["type"] = ccvr.Type + } + if ccvr.ClusterVersionDetails != nil { + objectMap["properties"] = ccvr.ClusterVersionDetails + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ClusterCodeVersionsResult struct. +func (ccvr *ClusterCodeVersionsResult) 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 + } + ccvr.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + ccvr.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + ccvr.Type = &typeVar + } + case "properties": + if v != nil { + var clusterVersionDetails ClusterVersionDetails + err = json.Unmarshal(*v, &clusterVersionDetails) + if err != nil { + return err + } + ccvr.ClusterVersionDetails = &clusterVersionDetails + } + } + } + + return nil +} + +// ClusterHealthPolicy defines a health policy used to evaluate the health of the cluster or of a cluster node. +type ClusterHealthPolicy struct { + // MaxPercentUnhealthyNodes - The maximum allowed percentage of unhealthy nodes before reporting an error. For example, to allow 10% of nodes to be unhealthy, this value would be 10. + // The percentage represents the maximum tolerated percentage of nodes that can be unhealthy before the cluster is considered in error. + // If the percentage is respected but there is at least one unhealthy node, the health is evaluated as Warning. + // The percentage is calculated by dividing the number of unhealthy nodes over the total number of nodes in the cluster. + // The computation rounds up to tolerate one failure on small numbers of nodes. Default percentage is zero. + // In large clusters, some nodes will always be down or out for repairs, so this percentage should be configured to tolerate that. + MaxPercentUnhealthyNodes *int32 `json:"maxPercentUnhealthyNodes,omitempty"` + // MaxPercentUnhealthyApplications - The maximum allowed percentage of unhealthy applications before reporting an error. For example, to allow 10% of applications to be unhealthy, this value would be 10. + // The percentage represents the maximum tolerated percentage of applications that can be unhealthy before the cluster is considered in error. + // If the percentage is respected but there is at least one unhealthy application, the health is evaluated as Warning. + // This is calculated by dividing the number of unhealthy applications over the total number of application instances in the cluster, excluding applications of application types that are included in the ApplicationTypeHealthPolicyMap. + // The computation rounds up to tolerate one failure on small numbers of applications. Default percentage is zero. + MaxPercentUnhealthyApplications *int32 `json:"maxPercentUnhealthyApplications,omitempty"` + // ApplicationHealthPolicies - Defines the application health policy map used to evaluate the health of an application or one of its children entities. + ApplicationHealthPolicies map[string]*ApplicationHealthPolicy `json:"applicationHealthPolicies"` +} + +// MarshalJSON is the custom marshaler for ClusterHealthPolicy. +func (chp ClusterHealthPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if chp.MaxPercentUnhealthyNodes != nil { + objectMap["maxPercentUnhealthyNodes"] = chp.MaxPercentUnhealthyNodes + } + if chp.MaxPercentUnhealthyApplications != nil { + objectMap["maxPercentUnhealthyApplications"] = chp.MaxPercentUnhealthyApplications + } + if chp.ApplicationHealthPolicies != nil { + objectMap["applicationHealthPolicies"] = chp.ApplicationHealthPolicies + } + return json.Marshal(objectMap) +} + +// ClusterListResult cluster list results +type ClusterListResult struct { + autorest.Response `json:"-"` + Value *[]Cluster `json:"value,omitempty"` + // NextLink - The URL to use for getting the next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ClusterProperties describes the cluster resource properties. +type ClusterProperties struct { + // AddOnFeatures - The list of add-on features to enable in the cluster. + AddOnFeatures *[]string `json:"addOnFeatures,omitempty"` + // AvailableClusterVersions - The Service Fabric runtime versions available for this cluster. + AvailableClusterVersions *[]ClusterVersionDetails `json:"availableClusterVersions,omitempty"` + // AzureActiveDirectory - The AAD authentication settings of the cluster. + AzureActiveDirectory *AzureActiveDirectory `json:"azureActiveDirectory,omitempty"` + // Certificate - The certificate to use for securing the cluster. The certificate provided will be used for node to node security within the cluster, SSL certificate for cluster management endpoint and default admin client. + Certificate *CertificateDescription `json:"certificate,omitempty"` + // CertificateCommonNames - Describes a list of server certificates referenced by common name that are used to secure the cluster. + CertificateCommonNames *ServerCertificateCommonNames `json:"certificateCommonNames,omitempty"` + // ClientCertificateCommonNames - The list of client certificates referenced by common name that are allowed to manage the cluster. + ClientCertificateCommonNames *[]ClientCertificateCommonName `json:"clientCertificateCommonNames,omitempty"` + // ClientCertificateThumbprints - The list of client certificates referenced by thumbprint that are allowed to manage the cluster. + ClientCertificateThumbprints *[]ClientCertificateThumbprint `json:"clientCertificateThumbprints,omitempty"` + // ClusterCodeVersion - The Service Fabric runtime version of the cluster. This property can only by set the user when **upgradeMode** is set to 'Manual'. To get list of available Service Fabric versions for new clusters use [ClusterVersion API](./ClusterVersion.md). To get the list of available version for existing clusters use **availableClusterVersions**. + ClusterCodeVersion *string `json:"clusterCodeVersion,omitempty"` + // ClusterEndpoint - The Azure Resource Provider endpoint. A system service in the cluster connects to this endpoint. + ClusterEndpoint *string `json:"clusterEndpoint,omitempty"` + // ClusterID - A service generated unique identifier for the cluster resource. + ClusterID *string `json:"clusterId,omitempty"` + // ClusterState - The current state of the cluster. + // - WaitingForNodes - Indicates that the cluster resource is created and the resource provider is waiting for Service Fabric VM extension to boot up and report to it. + // - Deploying - Indicates that the Service Fabric runtime is being installed on the VMs. Cluster resource will be in this state until the cluster boots up and system services are up. + // - BaselineUpgrade - Indicates that the cluster is upgrading to establishes the cluster version. This upgrade is automatically initiated when the cluster boots up for the first time. + // - UpdatingUserConfiguration - Indicates that the cluster is being upgraded with the user provided configuration. + // - UpdatingUserCertificate - Indicates that the cluster is being upgraded with the user provided certificate. + // - UpdatingInfrastructure - Indicates that the cluster is being upgraded with the latest Service Fabric runtime version. This happens only when the **upgradeMode** is set to 'Automatic'. + // - EnforcingClusterVersion - Indicates that cluster is on a different version than expected and the cluster is being upgraded to the expected version. + // - UpgradeServiceUnreachable - Indicates that the system service in the cluster is no longer polling the Resource Provider. Clusters in this state cannot be managed by the Resource Provider. + // - AutoScale - Indicates that the ReliabilityLevel of the cluster is being adjusted. + // - Ready - Indicates that the cluster is in a stable state. + // . Possible values include: 'WaitingForNodes', 'Deploying', 'BaselineUpgrade', 'UpdatingUserConfiguration', 'UpdatingUserCertificate', 'UpdatingInfrastructure', 'EnforcingClusterVersion', 'UpgradeServiceUnreachable', 'AutoScale', 'Ready' + ClusterState ClusterState `json:"clusterState,omitempty"` + // DiagnosticsStorageAccountConfig - The storage account information for storing Service Fabric diagnostic logs. + DiagnosticsStorageAccountConfig *DiagnosticsStorageAccountConfig `json:"diagnosticsStorageAccountConfig,omitempty"` + // FabricSettings - The list of custom fabric settings to configure the cluster. + FabricSettings *[]SettingsSectionDescription `json:"fabricSettings,omitempty"` + // ManagementEndpoint - The http management endpoint of the cluster. + ManagementEndpoint *string `json:"managementEndpoint,omitempty"` + // NodeTypes - The list of node types in the cluster. + NodeTypes *[]NodeTypeDescription `json:"nodeTypes,omitempty"` + // ProvisioningState - The provisioning state of the cluster resource. Possible values include: 'Updating', 'Succeeded', 'Failed', 'Canceled' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` + // ReliabilityLevel - The reliability level sets the replica set size of system services. Learn about [ReliabilityLevel](https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-cluster-capacity). + // - None - Run the System services with a target replica set count of 1. This should only be used for test clusters. + // - Bronze - Run the System services with a target replica set count of 3. This should only be used for test clusters. + // - Silver - Run the System services with a target replica set count of 5. + // - Gold - Run the System services with a target replica set count of 7. + // - Platinum - Run the System services with a target replica set count of 9. + // . Possible values include: 'ReliabilityLevelNone', 'ReliabilityLevelBronze', 'ReliabilityLevelSilver', 'ReliabilityLevelGold', 'ReliabilityLevelPlatinum' + ReliabilityLevel ReliabilityLevel `json:"reliabilityLevel,omitempty"` + // ReverseProxyCertificate - The server certificate used by reverse proxy. + ReverseProxyCertificate *CertificateDescription `json:"reverseProxyCertificate,omitempty"` + // ReverseProxyCertificateCommonNames - Describes a list of server certificates referenced by common name that are used to secure the cluster. + ReverseProxyCertificateCommonNames *ServerCertificateCommonNames `json:"reverseProxyCertificateCommonNames,omitempty"` + // UpgradeDescription - The policy to use when upgrading the cluster. + UpgradeDescription *ClusterUpgradePolicy `json:"upgradeDescription,omitempty"` + // UpgradeMode - The upgrade mode of the cluster when new Service Fabric runtime version is available. + // - Automatic - The cluster will be automatically upgraded to the latest Service Fabric runtime version as soon as it is available. + // - Manual - The cluster will not be automatically upgraded to the latest Service Fabric runtime version. The cluster is upgraded by setting the **clusterCodeVersion** property in the cluster resource. + // . Possible values include: 'Automatic', 'Manual' + UpgradeMode UpgradeMode `json:"upgradeMode,omitempty"` + // VMImage - The VM image VMSS has been configured with. Generic names such as Windows or Linux can be used. + VMImage *string `json:"vmImage,omitempty"` +} + +// ClusterPropertiesUpdateParameters describes the cluster resource properties that can be updated during PATCH +// operation. +type ClusterPropertiesUpdateParameters struct { + // AddOnFeatures - The list of add-on features to enable in the cluster. + AddOnFeatures *[]string `json:"addOnFeatures,omitempty"` + // Certificate - The certificate to use for securing the cluster. The certificate provided will be used for node to node security within the cluster, SSL certificate for cluster management endpoint and default admin client. + Certificate *CertificateDescription `json:"certificate,omitempty"` + // CertificateCommonNames - Describes a list of server certificates referenced by common name that are used to secure the cluster. + CertificateCommonNames *ServerCertificateCommonNames `json:"certificateCommonNames,omitempty"` + // ClientCertificateCommonNames - The list of client certificates referenced by common name that are allowed to manage the cluster. This will overwrite the existing list. + ClientCertificateCommonNames *[]ClientCertificateCommonName `json:"clientCertificateCommonNames,omitempty"` + // ClientCertificateThumbprints - The list of client certificates referenced by thumbprint that are allowed to manage the cluster. This will overwrite the existing list. + ClientCertificateThumbprints *[]ClientCertificateThumbprint `json:"clientCertificateThumbprints,omitempty"` + // ClusterCodeVersion - The Service Fabric runtime version of the cluster. This property can only by set the user when **upgradeMode** is set to 'Manual'. To get list of available Service Fabric versions for new clusters use [ClusterVersion API](./ClusterVersion.md). To get the list of available version for existing clusters use **availableClusterVersions**. + ClusterCodeVersion *string `json:"clusterCodeVersion,omitempty"` + // FabricSettings - The list of custom fabric settings to configure the cluster. This will overwrite the existing list. + FabricSettings *[]SettingsSectionDescription `json:"fabricSettings,omitempty"` + // NodeTypes - The list of node types in the cluster. This will overwrite the existing list. + NodeTypes *[]NodeTypeDescription `json:"nodeTypes,omitempty"` + // ReliabilityLevel - The reliability level sets the replica set size of system services. Learn about [ReliabilityLevel](https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-cluster-capacity). + // - None - Run the System services with a target replica set count of 1. This should only be used for test clusters. + // - Bronze - Run the System services with a target replica set count of 3. This should only be used for test clusters. + // - Silver - Run the System services with a target replica set count of 5. + // - Gold - Run the System services with a target replica set count of 7. + // - Platinum - Run the System services with a target replica set count of 9. + // . Possible values include: 'ReliabilityLevel1None', 'ReliabilityLevel1Bronze', 'ReliabilityLevel1Silver', 'ReliabilityLevel1Gold', 'ReliabilityLevel1Platinum' + ReliabilityLevel ReliabilityLevel1 `json:"reliabilityLevel,omitempty"` + // ReverseProxyCertificate - The server certificate used by reverse proxy. + ReverseProxyCertificate *CertificateDescription `json:"reverseProxyCertificate,omitempty"` + // UpgradeDescription - The policy to use when upgrading the cluster. + UpgradeDescription *ClusterUpgradePolicy `json:"upgradeDescription,omitempty"` + // UpgradeMode - The upgrade mode of the cluster when new Service Fabric runtime version is available. + // - Automatic - The cluster will be automatically upgraded to the latest Service Fabric runtime version as soon as it is available. + // - Manual - The cluster will not be automatically upgraded to the latest Service Fabric runtime version. The cluster is upgraded by setting the **clusterCodeVersion** property in the cluster resource. + // . Possible values include: 'UpgradeMode1Automatic', 'UpgradeMode1Manual' + UpgradeMode UpgradeMode1 `json:"upgradeMode,omitempty"` +} + +// ClustersCreateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type ClustersCreateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ClustersCreateFuture) Result(client ClustersClient) (c Cluster, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClustersCreateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicefabric.ClustersCreateFuture") + 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.CreateResponder(c.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClustersCreateFuture", "Result", c.Response.Response, "Failure responding to request") + } + } + return +} + +// ClustersUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type ClustersUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ClustersUpdateFuture) Result(client ClustersClient) (c Cluster, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ClustersUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicefabric.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, "servicefabric.ClustersUpdateFuture", "Result", c.Response.Response, "Failure responding to request") + } + } + return +} + +// ClusterUpdateParameters cluster update request +type ClusterUpdateParameters struct { + // ClusterPropertiesUpdateParameters - Describes the cluster resource properties that can be updated during PATCH operation. + *ClusterPropertiesUpdateParameters `json:"properties,omitempty"` + // Tags - Cluster update parameters + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ClusterUpdateParameters. +func (cup ClusterUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if cup.ClusterPropertiesUpdateParameters != nil { + objectMap["properties"] = cup.ClusterPropertiesUpdateParameters + } + if cup.Tags != nil { + objectMap["tags"] = cup.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ClusterUpdateParameters struct. +func (cup *ClusterUpdateParameters) 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 clusterPropertiesUpdateParameters ClusterPropertiesUpdateParameters + err = json.Unmarshal(*v, &clusterPropertiesUpdateParameters) + if err != nil { + return err + } + cup.ClusterPropertiesUpdateParameters = &clusterPropertiesUpdateParameters + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + cup.Tags = tags + } + } + } + + return nil +} + +// ClusterUpgradeDeltaHealthPolicy describes the delta health policies for the cluster upgrade. +type ClusterUpgradeDeltaHealthPolicy struct { + // MaxPercentDeltaUnhealthyNodes - The maximum allowed percentage of nodes health degradation allowed during cluster upgrades. + // The delta is measured between the state of the nodes at the beginning of upgrade and the state of the nodes at the time of the health evaluation. + // The check is performed after every upgrade domain upgrade completion to make sure the global state of the cluster is within tolerated limits. + MaxPercentDeltaUnhealthyNodes *int32 `json:"maxPercentDeltaUnhealthyNodes,omitempty"` + // MaxPercentUpgradeDomainDeltaUnhealthyNodes - The maximum allowed percentage of upgrade domain nodes health degradation allowed during cluster upgrades. + // The delta is measured between the state of the upgrade domain nodes at the beginning of upgrade and the state of the upgrade domain nodes at the time of the health evaluation. + // The check is performed after every upgrade domain upgrade completion for all completed upgrade domains to make sure the state of the upgrade domains is within tolerated limits. + MaxPercentUpgradeDomainDeltaUnhealthyNodes *int32 `json:"maxPercentUpgradeDomainDeltaUnhealthyNodes,omitempty"` + // MaxPercentDeltaUnhealthyApplications - The maximum allowed percentage of applications health degradation allowed during cluster upgrades. + // The delta is measured between the state of the applications at the beginning of upgrade and the state of the applications at the time of the health evaluation. + // The check is performed after every upgrade domain upgrade completion to make sure the global state of the cluster is within tolerated limits. System services are not included in this. + MaxPercentDeltaUnhealthyApplications *int32 `json:"maxPercentDeltaUnhealthyApplications,omitempty"` + // ApplicationDeltaHealthPolicies - Defines the application delta health policy map used to evaluate the health of an application or one of its child entities when upgrading the cluster. + ApplicationDeltaHealthPolicies map[string]*ApplicationDeltaHealthPolicy `json:"applicationDeltaHealthPolicies"` +} + +// MarshalJSON is the custom marshaler for ClusterUpgradeDeltaHealthPolicy. +func (cudhp ClusterUpgradeDeltaHealthPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if cudhp.MaxPercentDeltaUnhealthyNodes != nil { + objectMap["maxPercentDeltaUnhealthyNodes"] = cudhp.MaxPercentDeltaUnhealthyNodes + } + if cudhp.MaxPercentUpgradeDomainDeltaUnhealthyNodes != nil { + objectMap["maxPercentUpgradeDomainDeltaUnhealthyNodes"] = cudhp.MaxPercentUpgradeDomainDeltaUnhealthyNodes + } + if cudhp.MaxPercentDeltaUnhealthyApplications != nil { + objectMap["maxPercentDeltaUnhealthyApplications"] = cudhp.MaxPercentDeltaUnhealthyApplications + } + if cudhp.ApplicationDeltaHealthPolicies != nil { + objectMap["applicationDeltaHealthPolicies"] = cudhp.ApplicationDeltaHealthPolicies + } + return json.Marshal(objectMap) +} + +// ClusterUpgradePolicy describes the policy used when upgrading the cluster. +type ClusterUpgradePolicy struct { + // ForceRestart - If true, then processes are forcefully restarted during upgrade even when the code version has not changed (the upgrade only changes configuration or data). + ForceRestart *bool `json:"forceRestart,omitempty"` + // UpgradeReplicaSetCheckTimeout - The maximum amount of time to block processing of an upgrade domain and revent loss of availability when there are unexpected issues. When this timeout expires, processing of the upgrade domain will proceed regardless of availability loss issues. The timeout is reset at the start of each upgrade domain. The timeout can be in either hh:mm:ss or in d.hh:mm:ss.ms format. + UpgradeReplicaSetCheckTimeout *string `json:"upgradeReplicaSetCheckTimeout,omitempty"` + // HealthCheckWaitDuration - The length of time to wait after completing an upgrade domain before performing health checks. The duration can be in either hh:mm:ss or in d.hh:mm:ss.ms format. + HealthCheckWaitDuration *string `json:"healthCheckWaitDuration,omitempty"` + // HealthCheckStableDuration - The amount of time that the application or cluster must remain healthy before the upgrade proceeds to the next upgrade domain. The duration can be in either hh:mm:ss or in d.hh:mm:ss.ms format. + HealthCheckStableDuration *string `json:"healthCheckStableDuration,omitempty"` + // HealthCheckRetryTimeout - The amount of time to retry health evaluation when the application or cluster is unhealthy before the upgrade rolls back. The timeout can be in either hh:mm:ss or in d.hh:mm:ss.ms format. + HealthCheckRetryTimeout *string `json:"healthCheckRetryTimeout,omitempty"` + // UpgradeTimeout - The amount of time the overall upgrade has to complete before the upgrade rolls back. The timeout can be in either hh:mm:ss or in d.hh:mm:ss.ms format. + UpgradeTimeout *string `json:"upgradeTimeout,omitempty"` + // UpgradeDomainTimeout - The amount of time each upgrade domain has to complete before the upgrade rolls back. The timeout can be in either hh:mm:ss or in d.hh:mm:ss.ms format. + UpgradeDomainTimeout *string `json:"upgradeDomainTimeout,omitempty"` + // HealthPolicy - The cluster health policy used when upgrading the cluster. + HealthPolicy *ClusterHealthPolicy `json:"healthPolicy,omitempty"` + // DeltaHealthPolicy - The cluster delta health policy used when upgrading the cluster. + DeltaHealthPolicy *ClusterUpgradeDeltaHealthPolicy `json:"deltaHealthPolicy,omitempty"` +} + +// ClusterVersionDetails the detail of the Service Fabric runtime version result +type ClusterVersionDetails struct { + // CodeVersion - The Service Fabric runtime version of the cluster. + CodeVersion *string `json:"codeVersion,omitempty"` + // SupportExpiryUtc - The date of expiry of support of the version. + SupportExpiryUtc *string `json:"supportExpiryUtc,omitempty"` + // Environment - Indicates if this version is for Windows or Linux operating system. Possible values include: 'Windows', 'Linux' + Environment Environment `json:"environment,omitempty"` +} + +// DiagnosticsStorageAccountConfig the storage account information for storing Service Fabric diagnostic logs. +type DiagnosticsStorageAccountConfig struct { + // StorageAccountName - The Azure storage account name. + StorageAccountName *string `json:"storageAccountName,omitempty"` + // ProtectedAccountKeyName - The protected diagnostics storage key name. + ProtectedAccountKeyName *string `json:"protectedAccountKeyName,omitempty"` + // BlobEndpoint - The blob endpoint of the azure storage account. + BlobEndpoint *string `json:"blobEndpoint,omitempty"` + // QueueEndpoint - The queue endpoint of the azure storage account. + QueueEndpoint *string `json:"queueEndpoint,omitempty"` + // TableEndpoint - The table endpoint of the azure storage account. + TableEndpoint *string `json:"tableEndpoint,omitempty"` +} + +// EndpointRangeDescription port range details +type EndpointRangeDescription struct { + // StartPort - Starting port of a range of ports + StartPort *int32 `json:"startPort,omitempty"` + // EndPort - End port of a range of ports + EndPort *int32 `json:"endPort,omitempty"` +} + +// ErrorModel the structure of the error. +type ErrorModel struct { + // Error - The error details. + Error *ErrorModelError `json:"error,omitempty"` +} + +// ErrorModelError the error details. +type ErrorModelError struct { + // Code - The error code. + Code *string `json:"code,omitempty"` + // Message - The error message. + Message *string `json:"message,omitempty"` +} + +// NamedPartitionSchemeDescription describes the named partition scheme of the service. +type NamedPartitionSchemeDescription struct { + // Count - The number of partitions. + Count *int32 `json:"Count,omitempty"` + // Names - Array of size specified by the ‘Count’ parameter, for the names of the partitions. + Names *[]string `json:"Names,omitempty"` + // PartitionScheme - Possible values include: 'PartitionSchemePartitionSchemeDescription', 'PartitionSchemeNamed', 'PartitionSchemeSingleton', 'PartitionSchemeUniformInt64Range' + PartitionScheme PartitionSchemeBasicPartitionSchemeDescription `json:"PartitionScheme,omitempty"` +} + +// MarshalJSON is the custom marshaler for NamedPartitionSchemeDescription. +func (npsd NamedPartitionSchemeDescription) MarshalJSON() ([]byte, error) { + npsd.PartitionScheme = PartitionSchemeNamed + objectMap := make(map[string]interface{}) + if npsd.Count != nil { + objectMap["Count"] = npsd.Count + } + if npsd.Names != nil { + objectMap["Names"] = npsd.Names + } + if npsd.PartitionScheme != "" { + objectMap["PartitionScheme"] = npsd.PartitionScheme + } + return json.Marshal(objectMap) +} + +// AsNamedPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for NamedPartitionSchemeDescription. +func (npsd NamedPartitionSchemeDescription) AsNamedPartitionSchemeDescription() (*NamedPartitionSchemeDescription, bool) { + return &npsd, true +} + +// AsSingletonPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for NamedPartitionSchemeDescription. +func (npsd NamedPartitionSchemeDescription) AsSingletonPartitionSchemeDescription() (*SingletonPartitionSchemeDescription, bool) { + return nil, false +} + +// AsUniformInt64RangePartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for NamedPartitionSchemeDescription. +func (npsd NamedPartitionSchemeDescription) AsUniformInt64RangePartitionSchemeDescription() (*UniformInt64RangePartitionSchemeDescription, bool) { + return nil, false +} + +// AsPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for NamedPartitionSchemeDescription. +func (npsd NamedPartitionSchemeDescription) AsPartitionSchemeDescription() (*PartitionSchemeDescription, bool) { + return nil, false +} + +// AsBasicPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for NamedPartitionSchemeDescription. +func (npsd NamedPartitionSchemeDescription) AsBasicPartitionSchemeDescription() (BasicPartitionSchemeDescription, bool) { + return &npsd, true +} + +// NodeTypeDescription describes a node type in the cluster, each node type represents sub set of nodes in the +// cluster. +type NodeTypeDescription struct { + // Name - The name of the node type. + Name *string `json:"name,omitempty"` + // PlacementProperties - The placement tags applied to nodes in the node type, which can be used to indicate where certain services (workload) should run. + PlacementProperties map[string]*string `json:"placementProperties"` + // Capacities - The capacity tags applied to the nodes in the node type, the cluster resource manager uses these tags to understand how much resource a node has. + Capacities map[string]*string `json:"capacities"` + // ClientConnectionEndpointPort - The TCP cluster management endpoint port. + ClientConnectionEndpointPort *int32 `json:"clientConnectionEndpointPort,omitempty"` + // HTTPGatewayEndpointPort - The HTTP cluster management endpoint port. + HTTPGatewayEndpointPort *int32 `json:"httpGatewayEndpointPort,omitempty"` + // DurabilityLevel - The durability level of the node type. Learn about [DurabilityLevel](https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-cluster-capacity). + // - Bronze - No privileges. This is the default. + // - Silver - The infrastructure jobs can be paused for a duration of 10 minutes per UD. + // - Gold - The infrastructure jobs can be paused for a duration of 2 hours per UD. Gold durability can be enabled only on full node VM skus like D15_V2, G5 etc. + // . Possible values include: 'Bronze', 'Silver', 'Gold' + DurabilityLevel DurabilityLevel `json:"durabilityLevel,omitempty"` + // ApplicationPorts - The range of ports from which cluster assigned port to Service Fabric applications. + ApplicationPorts *EndpointRangeDescription `json:"applicationPorts,omitempty"` + // EphemeralPorts - The range of empheral ports that nodes in this node type should be configured with. + EphemeralPorts *EndpointRangeDescription `json:"ephemeralPorts,omitempty"` + // IsPrimary - The node type on which system services will run. Only one node type should be marked as primary. Primary node type cannot be deleted or changed for existing clusters. + IsPrimary *bool `json:"isPrimary,omitempty"` + // VMInstanceCount - The number of nodes in the node type. This count should match the capacity property in the corresponding VirtualMachineScaleSet resource. + VMInstanceCount *int32 `json:"vmInstanceCount,omitempty"` + // ReverseProxyEndpointPort - The endpoint used by reverse proxy. + ReverseProxyEndpointPort *int32 `json:"reverseProxyEndpointPort,omitempty"` +} + +// MarshalJSON is the custom marshaler for NodeTypeDescription. +func (ntd NodeTypeDescription) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ntd.Name != nil { + objectMap["name"] = ntd.Name + } + if ntd.PlacementProperties != nil { + objectMap["placementProperties"] = ntd.PlacementProperties + } + if ntd.Capacities != nil { + objectMap["capacities"] = ntd.Capacities + } + if ntd.ClientConnectionEndpointPort != nil { + objectMap["clientConnectionEndpointPort"] = ntd.ClientConnectionEndpointPort + } + if ntd.HTTPGatewayEndpointPort != nil { + objectMap["httpGatewayEndpointPort"] = ntd.HTTPGatewayEndpointPort + } + if ntd.DurabilityLevel != "" { + objectMap["durabilityLevel"] = ntd.DurabilityLevel + } + if ntd.ApplicationPorts != nil { + objectMap["applicationPorts"] = ntd.ApplicationPorts + } + if ntd.EphemeralPorts != nil { + objectMap["ephemeralPorts"] = ntd.EphemeralPorts + } + if ntd.IsPrimary != nil { + objectMap["isPrimary"] = ntd.IsPrimary + } + if ntd.VMInstanceCount != nil { + objectMap["vmInstanceCount"] = ntd.VMInstanceCount + } + if ntd.ReverseProxyEndpointPort != nil { + objectMap["reverseProxyEndpointPort"] = ntd.ReverseProxyEndpointPort + } + return json.Marshal(objectMap) +} + +// OperationListResult describes the result of the request to list Service Fabric operations. +type OperationListResult struct { + autorest.Response `json:"-"` + // Value - List of Service Fabric operations supported by the Microsoft.ServiceFabric resource provider. + Value *[]OperationResult `json:"value,omitempty"` + // NextLink - URL to get the next set of operation list results if there are any. + NextLink *string `json:"nextLink,omitempty"` +} + +// OperationListResultIterator provides access to a complete listing of OperationResult values. +type OperationListResultIterator struct { + i int + page OperationListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *OperationListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter OperationListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter OperationListResultIterator) Response() OperationListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter OperationListResultIterator) Value() OperationResult { + if !iter.page.NotDone() { + return OperationResult{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (olr OperationListResult) IsEmpty() bool { + return olr.Value == nil || len(*olr.Value) == 0 +} + +// operationListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (olr OperationListResult) operationListResultPreparer() (*http.Request, error) { + if olr.NextLink == nil || len(to.String(olr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(olr.NextLink))) +} + +// OperationListResultPage contains a page of OperationResult values. +type OperationListResultPage struct { + fn func(OperationListResult) (OperationListResult, error) + olr OperationListResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *OperationListResultPage) Next() error { + next, err := page.fn(page.olr) + if err != nil { + return err + } + page.olr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page OperationListResultPage) NotDone() bool { + return !page.olr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page OperationListResultPage) Response() OperationListResult { + return page.olr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page OperationListResultPage) Values() []OperationResult { + if page.olr.IsEmpty() { + return nil + } + return *page.olr.Value +} + +// OperationResult available operation list result +type OperationResult struct { + // Name - The name of the operation. + Name *string `json:"name,omitempty"` + // Display - The object that represents the operation. + Display *AvailableOperationDisplay `json:"display,omitempty"` + // Origin - Origin result + Origin *string `json:"origin,omitempty"` + // NextLink - The URL to use for getting the next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// BasicPartitionSchemeDescription describes how the service is partitioned. +type BasicPartitionSchemeDescription interface { + AsNamedPartitionSchemeDescription() (*NamedPartitionSchemeDescription, bool) + AsSingletonPartitionSchemeDescription() (*SingletonPartitionSchemeDescription, bool) + AsUniformInt64RangePartitionSchemeDescription() (*UniformInt64RangePartitionSchemeDescription, bool) + AsPartitionSchemeDescription() (*PartitionSchemeDescription, bool) +} + +// PartitionSchemeDescription describes how the service is partitioned. +type PartitionSchemeDescription struct { + // PartitionScheme - Possible values include: 'PartitionSchemePartitionSchemeDescription', 'PartitionSchemeNamed', 'PartitionSchemeSingleton', 'PartitionSchemeUniformInt64Range' + PartitionScheme PartitionSchemeBasicPartitionSchemeDescription `json:"PartitionScheme,omitempty"` +} + +func unmarshalBasicPartitionSchemeDescription(body []byte) (BasicPartitionSchemeDescription, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["PartitionScheme"] { + case string(PartitionSchemeNamed): + var npsd NamedPartitionSchemeDescription + err := json.Unmarshal(body, &npsd) + return npsd, err + case string(PartitionSchemeSingleton): + var spsd SingletonPartitionSchemeDescription + err := json.Unmarshal(body, &spsd) + return spsd, err + case string(PartitionSchemeUniformInt64Range): + var ui6rpsd UniformInt64RangePartitionSchemeDescription + err := json.Unmarshal(body, &ui6rpsd) + return ui6rpsd, err + default: + var psd PartitionSchemeDescription + err := json.Unmarshal(body, &psd) + return psd, err + } +} +func unmarshalBasicPartitionSchemeDescriptionArray(body []byte) ([]BasicPartitionSchemeDescription, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + psdArray := make([]BasicPartitionSchemeDescription, len(rawMessages)) + + for index, rawMessage := range rawMessages { + psd, err := unmarshalBasicPartitionSchemeDescription(*rawMessage) + if err != nil { + return nil, err + } + psdArray[index] = psd + } + return psdArray, nil +} + +// MarshalJSON is the custom marshaler for PartitionSchemeDescription. +func (psd PartitionSchemeDescription) MarshalJSON() ([]byte, error) { + psd.PartitionScheme = PartitionSchemePartitionSchemeDescription + objectMap := make(map[string]interface{}) + if psd.PartitionScheme != "" { + objectMap["PartitionScheme"] = psd.PartitionScheme + } + return json.Marshal(objectMap) +} + +// AsNamedPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for PartitionSchemeDescription. +func (psd PartitionSchemeDescription) AsNamedPartitionSchemeDescription() (*NamedPartitionSchemeDescription, bool) { + return nil, false +} + +// AsSingletonPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for PartitionSchemeDescription. +func (psd PartitionSchemeDescription) AsSingletonPartitionSchemeDescription() (*SingletonPartitionSchemeDescription, bool) { + return nil, false +} + +// AsUniformInt64RangePartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for PartitionSchemeDescription. +func (psd PartitionSchemeDescription) AsUniformInt64RangePartitionSchemeDescription() (*UniformInt64RangePartitionSchemeDescription, bool) { + return nil, false +} + +// AsPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for PartitionSchemeDescription. +func (psd PartitionSchemeDescription) AsPartitionSchemeDescription() (*PartitionSchemeDescription, bool) { + return &psd, true +} + +// AsBasicPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for PartitionSchemeDescription. +func (psd PartitionSchemeDescription) AsBasicPartitionSchemeDescription() (BasicPartitionSchemeDescription, bool) { + return &psd, true +} + +// ProxyResource the resource model definition for proxy-only resource. +type ProxyResource struct { + // ID - Azure resource identifier. + ID *string `json:"id,omitempty"` + // Name - Azure resource name. + Name *string `json:"name,omitempty"` + // Type - Azure resource type. + Type *string `json:"type,omitempty"` + // Location - Azure resource location. + Location *string `json:"location,omitempty"` +} + +// Resource the resource model definition. +type Resource struct { + // ID - Azure resource identifier. + ID *string `json:"id,omitempty"` + // Name - Azure resource name. + Name *string `json:"name,omitempty"` + // Type - Azure resource type. + Type *string `json:"type,omitempty"` + // Location - Azure resource location. + Location *string `json:"location,omitempty"` + // Tags - Azure 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.ID != nil { + objectMap["id"] = r.ID + } + if r.Name != nil { + objectMap["name"] = r.Name + } + if r.Type != nil { + objectMap["type"] = r.Type + } + if r.Location != nil { + objectMap["location"] = r.Location + } + if r.Tags != nil { + objectMap["tags"] = r.Tags + } + return json.Marshal(objectMap) +} + +// RollingUpgradeMonitoringPolicy the policy used for monitoring the application upgrade +type RollingUpgradeMonitoringPolicy struct { + // HealthCheckWaitDuration - The amount of time to wait after completing an upgrade domain before applying health policies. It is first interpreted as a string representing an ISO 8601 duration. If that fails, then it is interpreted as a number representing the total number of milliseconds. + HealthCheckWaitDuration *string `json:"healthCheckWaitDuration,omitempty"` + // HealthCheckStableDuration - The amount of time that the application or cluster must remain healthy before the upgrade proceeds to the next upgrade domain. It is first interpreted as a string representing an ISO 8601 duration. If that fails, then it is interpreted as a number representing the total number of milliseconds. + HealthCheckStableDuration *string `json:"healthCheckStableDuration,omitempty"` + // HealthCheckRetryTimeout - The amount of time to retry health evaluation when the application or cluster is unhealthy before FailureAction is executed. It is first interpreted as a string representing an ISO 8601 duration. If that fails, then it is interpreted as a number representing the total number of milliseconds. + HealthCheckRetryTimeout *string `json:"healthCheckRetryTimeout,omitempty"` + // UpgradeTimeout - The amount of time the overall upgrade has to complete before FailureAction is executed. It is first interpreted as a string representing an ISO 8601 duration. If that fails, then it is interpreted as a number representing the total number of milliseconds. + UpgradeTimeout *string `json:"upgradeTimeout,omitempty"` + // UpgradeDomainTimeout - The amount of time each upgrade domain has to complete before FailureAction is executed. It is first interpreted as a string representing an ISO 8601 duration. If that fails, then it is interpreted as a number representing the total number of milliseconds. + UpgradeDomainTimeout *string `json:"upgradeDomainTimeout,omitempty"` +} + +// ServerCertificateCommonName describes the server certificate details using common name. +type ServerCertificateCommonName struct { + // CertificateCommonName - The common name of the server certificate. + CertificateCommonName *string `json:"certificateCommonName,omitempty"` + // CertificateIssuerThumbprint - The issuer thumbprint of the server certificate. + CertificateIssuerThumbprint *string `json:"certificateIssuerThumbprint,omitempty"` +} + +// ServerCertificateCommonNames describes a list of server certificates referenced by common name that are used to +// secure the cluster. +type ServerCertificateCommonNames struct { + // CommonNames - The list of server certificates referenced by common name that are used to secure the cluster. + CommonNames *[]ServerCertificateCommonName `json:"commonNames,omitempty"` + // X509StoreName - The local certificate store location. Possible values include: 'X509StoreName1AddressBook', 'X509StoreName1AuthRoot', 'X509StoreName1CertificateAuthority', 'X509StoreName1Disallowed', 'X509StoreName1My', 'X509StoreName1Root', 'X509StoreName1TrustedPeople', 'X509StoreName1TrustedPublisher' + X509StoreName X509StoreName1 `json:"x509StoreName,omitempty"` +} + +// ServiceCorrelationDescription creates a particular correlation between services. +type ServiceCorrelationDescription struct { + // Scheme - The ServiceCorrelationScheme which describes the relationship between this service and the service specified via ServiceName. Possible values include: 'ServiceCorrelationSchemeInvalid', 'ServiceCorrelationSchemeAffinity', 'ServiceCorrelationSchemeAlignedAffinity', 'ServiceCorrelationSchemeNonAlignedAffinity' + Scheme ServiceCorrelationScheme `json:"Scheme,omitempty"` + // ServiceName - The name of the service that the correlation relationship is established with. + ServiceName *string `json:"ServiceName,omitempty"` +} + +// ServiceLoadMetricDescription specifies a metric to load balance a service during runtime. +type ServiceLoadMetricDescription struct { + // Name - The name of the metric. If the service chooses to report load during runtime, the load metric name should match the name that is specified in Name exactly. Note that metric names are case sensitive. + Name *string `json:"Name,omitempty"` + // Weight - The service load metric relative weight, compared to other metrics configured for this service, as a number. Possible values include: 'ServiceLoadMetricWeightZero', 'ServiceLoadMetricWeightLow', 'ServiceLoadMetricWeightMedium', 'ServiceLoadMetricWeightHigh' + Weight ServiceLoadMetricWeight `json:"Weight,omitempty"` + // PrimaryDefaultLoad - Used only for Stateful services. The default amount of load, as a number, that this service creates for this metric when it is a Primary replica. + PrimaryDefaultLoad *int32 `json:"PrimaryDefaultLoad,omitempty"` + // SecondaryDefaultLoad - Used only for Stateful services. The default amount of load, as a number, that this service creates for this metric when it is a Secondary replica. + SecondaryDefaultLoad *int32 `json:"SecondaryDefaultLoad,omitempty"` + // DefaultLoad - Used only for Stateless services. The default amount of load, as a number, that this service creates for this metric. + DefaultLoad *int32 `json:"DefaultLoad,omitempty"` +} + +// BasicServicePlacementPolicyDescription describes the policy to be used for placement of a Service Fabric service. +type BasicServicePlacementPolicyDescription interface { + AsServicePlacementPolicyDescription() (*ServicePlacementPolicyDescription, bool) +} + +// ServicePlacementPolicyDescription describes the policy to be used for placement of a Service Fabric service. +type ServicePlacementPolicyDescription struct { + // Type - Possible values include: 'TypeServicePlacementPolicyDescription' + Type Type `json:"Type,omitempty"` +} + +func unmarshalBasicServicePlacementPolicyDescription(body []byte) (BasicServicePlacementPolicyDescription, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["Type"] { + default: + var sppd ServicePlacementPolicyDescription + err := json.Unmarshal(body, &sppd) + return sppd, err + } +} +func unmarshalBasicServicePlacementPolicyDescriptionArray(body []byte) ([]BasicServicePlacementPolicyDescription, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + sppdArray := make([]BasicServicePlacementPolicyDescription, len(rawMessages)) + + for index, rawMessage := range rawMessages { + sppd, err := unmarshalBasicServicePlacementPolicyDescription(*rawMessage) + if err != nil { + return nil, err + } + sppdArray[index] = sppd + } + return sppdArray, nil +} + +// MarshalJSON is the custom marshaler for ServicePlacementPolicyDescription. +func (sppd ServicePlacementPolicyDescription) MarshalJSON() ([]byte, error) { + sppd.Type = TypeServicePlacementPolicyDescription + objectMap := make(map[string]interface{}) + if sppd.Type != "" { + objectMap["Type"] = sppd.Type + } + return json.Marshal(objectMap) +} + +// AsServicePlacementPolicyDescription is the BasicServicePlacementPolicyDescription implementation for ServicePlacementPolicyDescription. +func (sppd ServicePlacementPolicyDescription) AsServicePlacementPolicyDescription() (*ServicePlacementPolicyDescription, bool) { + return &sppd, true +} + +// AsBasicServicePlacementPolicyDescription is the BasicServicePlacementPolicyDescription implementation for ServicePlacementPolicyDescription. +func (sppd ServicePlacementPolicyDescription) AsBasicServicePlacementPolicyDescription() (BasicServicePlacementPolicyDescription, bool) { + return &sppd, true +} + +// ServiceResource the service resource. +type ServiceResource struct { + autorest.Response `json:"-"` + // BasicServiceResourceProperties - The service resource properties. + BasicServiceResourceProperties `json:"properties,omitempty"` + // ID - Azure resource identifier. + ID *string `json:"id,omitempty"` + // Name - Azure resource name. + Name *string `json:"name,omitempty"` + // Type - Azure resource type. + Type *string `json:"type,omitempty"` + // Location - Azure resource location. + Location *string `json:"location,omitempty"` +} + +// MarshalJSON is the custom marshaler for ServiceResource. +func (sr ServiceResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + objectMap["properties"] = sr.BasicServiceResourceProperties + if sr.ID != nil { + objectMap["id"] = sr.ID + } + if sr.Name != nil { + objectMap["name"] = sr.Name + } + if sr.Type != nil { + objectMap["type"] = sr.Type + } + if sr.Location != nil { + objectMap["location"] = sr.Location + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ServiceResource struct. +func (sr *ServiceResource) 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 { + basicServiceResourceProperties, err := unmarshalBasicServiceResourceProperties(*v) + if err != nil { + return err + } + sr.BasicServiceResourceProperties = basicServiceResourceProperties + } + 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 "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + sr.Location = &location + } + } + } + + return nil +} + +// ServiceResourceList the list of service resources. +type ServiceResourceList struct { + autorest.Response `json:"-"` + Value *[]ServiceResource `json:"value,omitempty"` +} + +// BasicServiceResourceProperties the service resource properties. +type BasicServiceResourceProperties interface { + AsStatefulServiceProperties() (*StatefulServiceProperties, bool) + AsStatelessServiceProperties() (*StatelessServiceProperties, bool) + AsServiceResourceProperties() (*ServiceResourceProperties, bool) +} + +// ServiceResourceProperties the service resource properties. +type ServiceResourceProperties struct { + // ProvisioningState - The current deployment or provisioning state, which only appears in the response + ProvisioningState *string `json:"provisioningState,omitempty"` + // ServiceTypeName - The name of the service type + ServiceTypeName *string `json:"serviceTypeName,omitempty"` + // PartitionDescription - Describes how the service is partitioned. + PartitionDescription BasicPartitionSchemeDescription `json:"partitionDescription,omitempty"` + // ServiceKind - Possible values include: 'ServiceKindServiceResourceProperties', 'ServiceKindStateful1', 'ServiceKindStateless1' + ServiceKind ServiceKindBasicServiceResourceProperties `json:"serviceKind,omitempty"` + // PlacementConstraints - The placement constraints as a string. Placement constraints are boolean expressions on node properties and allow for restricting a service to particular nodes based on the service requirements. For example, to place a service on nodes where NodeType is blue specify the following: "NodeColor == blue)". + PlacementConstraints *string `json:"placementConstraints,omitempty"` + // CorrelationScheme - A list that describes the correlation of the service with other services. + CorrelationScheme *[]ServiceCorrelationDescription `json:"correlationScheme,omitempty"` + // ServiceLoadMetrics - The service load metrics is given as an array of ServiceLoadMetricDescription objects. + ServiceLoadMetrics *[]ServiceLoadMetricDescription `json:"serviceLoadMetrics,omitempty"` + // ServicePlacementPolicies - A list that describes the correlation of the service with other services. + ServicePlacementPolicies *[]BasicServicePlacementPolicyDescription `json:"servicePlacementPolicies,omitempty"` + // DefaultMoveCost - Specifies the move cost for the service. Possible values include: 'Zero', 'Low', 'Medium', 'High' + DefaultMoveCost MoveCost `json:"defaultMoveCost,omitempty"` +} + +func unmarshalBasicServiceResourceProperties(body []byte) (BasicServiceResourceProperties, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["serviceKind"] { + case string(ServiceKindStateful1): + var ssp StatefulServiceProperties + err := json.Unmarshal(body, &ssp) + return ssp, err + case string(ServiceKindStateless1): + var ssp StatelessServiceProperties + err := json.Unmarshal(body, &ssp) + return ssp, err + default: + var srp ServiceResourceProperties + err := json.Unmarshal(body, &srp) + return srp, err + } +} +func unmarshalBasicServiceResourcePropertiesArray(body []byte) ([]BasicServiceResourceProperties, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + srpArray := make([]BasicServiceResourceProperties, len(rawMessages)) + + for index, rawMessage := range rawMessages { + srp, err := unmarshalBasicServiceResourceProperties(*rawMessage) + if err != nil { + return nil, err + } + srpArray[index] = srp + } + return srpArray, nil +} + +// MarshalJSON is the custom marshaler for ServiceResourceProperties. +func (srp ServiceResourceProperties) MarshalJSON() ([]byte, error) { + srp.ServiceKind = ServiceKindServiceResourceProperties + objectMap := make(map[string]interface{}) + if srp.ProvisioningState != nil { + objectMap["provisioningState"] = srp.ProvisioningState + } + if srp.ServiceTypeName != nil { + objectMap["serviceTypeName"] = srp.ServiceTypeName + } + objectMap["partitionDescription"] = srp.PartitionDescription + if srp.ServiceKind != "" { + objectMap["serviceKind"] = srp.ServiceKind + } + if srp.PlacementConstraints != nil { + objectMap["placementConstraints"] = srp.PlacementConstraints + } + if srp.CorrelationScheme != nil { + objectMap["correlationScheme"] = srp.CorrelationScheme + } + if srp.ServiceLoadMetrics != nil { + objectMap["serviceLoadMetrics"] = srp.ServiceLoadMetrics + } + if srp.ServicePlacementPolicies != nil { + objectMap["servicePlacementPolicies"] = srp.ServicePlacementPolicies + } + if srp.DefaultMoveCost != "" { + objectMap["defaultMoveCost"] = srp.DefaultMoveCost + } + return json.Marshal(objectMap) +} + +// AsStatefulServiceProperties is the BasicServiceResourceProperties implementation for ServiceResourceProperties. +func (srp ServiceResourceProperties) AsStatefulServiceProperties() (*StatefulServiceProperties, bool) { + return nil, false +} + +// AsStatelessServiceProperties is the BasicServiceResourceProperties implementation for ServiceResourceProperties. +func (srp ServiceResourceProperties) AsStatelessServiceProperties() (*StatelessServiceProperties, bool) { + return nil, false +} + +// AsServiceResourceProperties is the BasicServiceResourceProperties implementation for ServiceResourceProperties. +func (srp ServiceResourceProperties) AsServiceResourceProperties() (*ServiceResourceProperties, bool) { + return &srp, true +} + +// AsBasicServiceResourceProperties is the BasicServiceResourceProperties implementation for ServiceResourceProperties. +func (srp ServiceResourceProperties) AsBasicServiceResourceProperties() (BasicServiceResourceProperties, bool) { + return &srp, true +} + +// UnmarshalJSON is the custom unmarshaler for ServiceResourceProperties struct. +func (srp *ServiceResourceProperties) 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 "provisioningState": + if v != nil { + var provisioningState string + err = json.Unmarshal(*v, &provisioningState) + if err != nil { + return err + } + srp.ProvisioningState = &provisioningState + } + case "serviceTypeName": + if v != nil { + var serviceTypeName string + err = json.Unmarshal(*v, &serviceTypeName) + if err != nil { + return err + } + srp.ServiceTypeName = &serviceTypeName + } + case "partitionDescription": + if v != nil { + partitionDescription, err := unmarshalBasicPartitionSchemeDescription(*v) + if err != nil { + return err + } + srp.PartitionDescription = partitionDescription + } + case "serviceKind": + if v != nil { + var serviceKind ServiceKindBasicServiceResourceProperties + err = json.Unmarshal(*v, &serviceKind) + if err != nil { + return err + } + srp.ServiceKind = serviceKind + } + case "placementConstraints": + if v != nil { + var placementConstraints string + err = json.Unmarshal(*v, &placementConstraints) + if err != nil { + return err + } + srp.PlacementConstraints = &placementConstraints + } + case "correlationScheme": + if v != nil { + var correlationScheme []ServiceCorrelationDescription + err = json.Unmarshal(*v, &correlationScheme) + if err != nil { + return err + } + srp.CorrelationScheme = &correlationScheme + } + case "serviceLoadMetrics": + if v != nil { + var serviceLoadMetrics []ServiceLoadMetricDescription + err = json.Unmarshal(*v, &serviceLoadMetrics) + if err != nil { + return err + } + srp.ServiceLoadMetrics = &serviceLoadMetrics + } + case "servicePlacementPolicies": + if v != nil { + servicePlacementPolicies, err := unmarshalBasicServicePlacementPolicyDescriptionArray(*v) + if err != nil { + return err + } + srp.ServicePlacementPolicies = &servicePlacementPolicies + } + case "defaultMoveCost": + if v != nil { + var defaultMoveCost MoveCost + err = json.Unmarshal(*v, &defaultMoveCost) + if err != nil { + return err + } + srp.DefaultMoveCost = defaultMoveCost + } + } + } + + return nil +} + +// ServiceResourcePropertiesBase the common service resource properties. +type ServiceResourcePropertiesBase struct { + // PlacementConstraints - The placement constraints as a string. Placement constraints are boolean expressions on node properties and allow for restricting a service to particular nodes based on the service requirements. For example, to place a service on nodes where NodeType is blue specify the following: "NodeColor == blue)". + PlacementConstraints *string `json:"placementConstraints,omitempty"` + // CorrelationScheme - A list that describes the correlation of the service with other services. + CorrelationScheme *[]ServiceCorrelationDescription `json:"correlationScheme,omitempty"` + // ServiceLoadMetrics - The service load metrics is given as an array of ServiceLoadMetricDescription objects. + ServiceLoadMetrics *[]ServiceLoadMetricDescription `json:"serviceLoadMetrics,omitempty"` + // ServicePlacementPolicies - A list that describes the correlation of the service with other services. + ServicePlacementPolicies *[]BasicServicePlacementPolicyDescription `json:"servicePlacementPolicies,omitempty"` + // DefaultMoveCost - Specifies the move cost for the service. Possible values include: 'Zero', 'Low', 'Medium', 'High' + DefaultMoveCost MoveCost `json:"defaultMoveCost,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for ServiceResourcePropertiesBase struct. +func (srpb *ServiceResourcePropertiesBase) 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 "placementConstraints": + if v != nil { + var placementConstraints string + err = json.Unmarshal(*v, &placementConstraints) + if err != nil { + return err + } + srpb.PlacementConstraints = &placementConstraints + } + case "correlationScheme": + if v != nil { + var correlationScheme []ServiceCorrelationDescription + err = json.Unmarshal(*v, &correlationScheme) + if err != nil { + return err + } + srpb.CorrelationScheme = &correlationScheme + } + case "serviceLoadMetrics": + if v != nil { + var serviceLoadMetrics []ServiceLoadMetricDescription + err = json.Unmarshal(*v, &serviceLoadMetrics) + if err != nil { + return err + } + srpb.ServiceLoadMetrics = &serviceLoadMetrics + } + case "servicePlacementPolicies": + if v != nil { + servicePlacementPolicies, err := unmarshalBasicServicePlacementPolicyDescriptionArray(*v) + if err != nil { + return err + } + srpb.ServicePlacementPolicies = &servicePlacementPolicies + } + case "defaultMoveCost": + if v != nil { + var defaultMoveCost MoveCost + err = json.Unmarshal(*v, &defaultMoveCost) + if err != nil { + return err + } + srpb.DefaultMoveCost = defaultMoveCost + } + } + } + + return nil +} + +// ServiceResourceUpdate the service resource for patch operations. +type ServiceResourceUpdate struct { + autorest.Response `json:"-"` + // BasicServiceResourceUpdateProperties - The service resource properties for patch operations. + BasicServiceResourceUpdateProperties `json:"properties,omitempty"` + // ID - Azure resource identifier. + ID *string `json:"id,omitempty"` + // Name - Azure resource name. + Name *string `json:"name,omitempty"` + // Type - Azure resource type. + Type *string `json:"type,omitempty"` + // Location - Azure resource location. + Location *string `json:"location,omitempty"` +} + +// MarshalJSON is the custom marshaler for ServiceResourceUpdate. +func (sru ServiceResourceUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + objectMap["properties"] = sru.BasicServiceResourceUpdateProperties + if sru.ID != nil { + objectMap["id"] = sru.ID + } + if sru.Name != nil { + objectMap["name"] = sru.Name + } + if sru.Type != nil { + objectMap["type"] = sru.Type + } + if sru.Location != nil { + objectMap["location"] = sru.Location + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ServiceResourceUpdate struct. +func (sru *ServiceResourceUpdate) 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 { + basicServiceResourceUpdateProperties, err := unmarshalBasicServiceResourceUpdateProperties(*v) + if err != nil { + return err + } + sru.BasicServiceResourceUpdateProperties = basicServiceResourceUpdateProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + sru.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + sru.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + sru.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + sru.Location = &location + } + } + } + + return nil +} + +// BasicServiceResourceUpdateProperties the service resource properties for patch operations. +type BasicServiceResourceUpdateProperties interface { + AsStatefulServiceUpdateProperties() (*StatefulServiceUpdateProperties, bool) + AsStatelessServiceUpdateProperties() (*StatelessServiceUpdateProperties, bool) + AsServiceResourceUpdateProperties() (*ServiceResourceUpdateProperties, bool) +} + +// ServiceResourceUpdateProperties the service resource properties for patch operations. +type ServiceResourceUpdateProperties struct { + // ServiceKind - Possible values include: 'ServiceKindBasicServiceResourceUpdatePropertiesServiceKindServiceResourceUpdateProperties', 'ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateful', 'ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateless' + ServiceKind ServiceKindBasicServiceResourceUpdateProperties `json:"serviceKind,omitempty"` + // PlacementConstraints - The placement constraints as a string. Placement constraints are boolean expressions on node properties and allow for restricting a service to particular nodes based on the service requirements. For example, to place a service on nodes where NodeType is blue specify the following: "NodeColor == blue)". + PlacementConstraints *string `json:"placementConstraints,omitempty"` + // CorrelationScheme - A list that describes the correlation of the service with other services. + CorrelationScheme *[]ServiceCorrelationDescription `json:"correlationScheme,omitempty"` + // ServiceLoadMetrics - The service load metrics is given as an array of ServiceLoadMetricDescription objects. + ServiceLoadMetrics *[]ServiceLoadMetricDescription `json:"serviceLoadMetrics,omitempty"` + // ServicePlacementPolicies - A list that describes the correlation of the service with other services. + ServicePlacementPolicies *[]BasicServicePlacementPolicyDescription `json:"servicePlacementPolicies,omitempty"` + // DefaultMoveCost - Specifies the move cost for the service. Possible values include: 'Zero', 'Low', 'Medium', 'High' + DefaultMoveCost MoveCost `json:"defaultMoveCost,omitempty"` +} + +func unmarshalBasicServiceResourceUpdateProperties(body []byte) (BasicServiceResourceUpdateProperties, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["serviceKind"] { + case string(ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateful): + var ssup StatefulServiceUpdateProperties + err := json.Unmarshal(body, &ssup) + return ssup, err + case string(ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateless): + var ssup StatelessServiceUpdateProperties + err := json.Unmarshal(body, &ssup) + return ssup, err + default: + var srup ServiceResourceUpdateProperties + err := json.Unmarshal(body, &srup) + return srup, err + } +} +func unmarshalBasicServiceResourceUpdatePropertiesArray(body []byte) ([]BasicServiceResourceUpdateProperties, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + srupArray := make([]BasicServiceResourceUpdateProperties, len(rawMessages)) + + for index, rawMessage := range rawMessages { + srup, err := unmarshalBasicServiceResourceUpdateProperties(*rawMessage) + if err != nil { + return nil, err + } + srupArray[index] = srup + } + return srupArray, nil +} + +// MarshalJSON is the custom marshaler for ServiceResourceUpdateProperties. +func (srup ServiceResourceUpdateProperties) MarshalJSON() ([]byte, error) { + srup.ServiceKind = ServiceKindBasicServiceResourceUpdatePropertiesServiceKindServiceResourceUpdateProperties + objectMap := make(map[string]interface{}) + if srup.ServiceKind != "" { + objectMap["serviceKind"] = srup.ServiceKind + } + if srup.PlacementConstraints != nil { + objectMap["placementConstraints"] = srup.PlacementConstraints + } + if srup.CorrelationScheme != nil { + objectMap["correlationScheme"] = srup.CorrelationScheme + } + if srup.ServiceLoadMetrics != nil { + objectMap["serviceLoadMetrics"] = srup.ServiceLoadMetrics + } + if srup.ServicePlacementPolicies != nil { + objectMap["servicePlacementPolicies"] = srup.ServicePlacementPolicies + } + if srup.DefaultMoveCost != "" { + objectMap["defaultMoveCost"] = srup.DefaultMoveCost + } + return json.Marshal(objectMap) +} + +// AsStatefulServiceUpdateProperties is the BasicServiceResourceUpdateProperties implementation for ServiceResourceUpdateProperties. +func (srup ServiceResourceUpdateProperties) AsStatefulServiceUpdateProperties() (*StatefulServiceUpdateProperties, bool) { + return nil, false +} + +// AsStatelessServiceUpdateProperties is the BasicServiceResourceUpdateProperties implementation for ServiceResourceUpdateProperties. +func (srup ServiceResourceUpdateProperties) AsStatelessServiceUpdateProperties() (*StatelessServiceUpdateProperties, bool) { + return nil, false +} + +// AsServiceResourceUpdateProperties is the BasicServiceResourceUpdateProperties implementation for ServiceResourceUpdateProperties. +func (srup ServiceResourceUpdateProperties) AsServiceResourceUpdateProperties() (*ServiceResourceUpdateProperties, bool) { + return &srup, true +} + +// AsBasicServiceResourceUpdateProperties is the BasicServiceResourceUpdateProperties implementation for ServiceResourceUpdateProperties. +func (srup ServiceResourceUpdateProperties) AsBasicServiceResourceUpdateProperties() (BasicServiceResourceUpdateProperties, bool) { + return &srup, true +} + +// UnmarshalJSON is the custom unmarshaler for ServiceResourceUpdateProperties struct. +func (srup *ServiceResourceUpdateProperties) 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 "serviceKind": + if v != nil { + var serviceKind ServiceKindBasicServiceResourceUpdateProperties + err = json.Unmarshal(*v, &serviceKind) + if err != nil { + return err + } + srup.ServiceKind = serviceKind + } + case "placementConstraints": + if v != nil { + var placementConstraints string + err = json.Unmarshal(*v, &placementConstraints) + if err != nil { + return err + } + srup.PlacementConstraints = &placementConstraints + } + case "correlationScheme": + if v != nil { + var correlationScheme []ServiceCorrelationDescription + err = json.Unmarshal(*v, &correlationScheme) + if err != nil { + return err + } + srup.CorrelationScheme = &correlationScheme + } + case "serviceLoadMetrics": + if v != nil { + var serviceLoadMetrics []ServiceLoadMetricDescription + err = json.Unmarshal(*v, &serviceLoadMetrics) + if err != nil { + return err + } + srup.ServiceLoadMetrics = &serviceLoadMetrics + } + case "servicePlacementPolicies": + if v != nil { + servicePlacementPolicies, err := unmarshalBasicServicePlacementPolicyDescriptionArray(*v) + if err != nil { + return err + } + srup.ServicePlacementPolicies = &servicePlacementPolicies + } + case "defaultMoveCost": + if v != nil { + var defaultMoveCost MoveCost + err = json.Unmarshal(*v, &defaultMoveCost) + if err != nil { + return err + } + srup.DefaultMoveCost = defaultMoveCost + } + } + } + + return nil +} + +// ServicesCreateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type ServicesCreateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ServicesCreateFuture) Result(client ServicesClient) (sr ServiceResource, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesCreateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicefabric.ServicesCreateFuture") + 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.CreateResponder(sr.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesCreateFuture", "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.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ServicesDeleteFuture) Result(client ServicesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicefabric.ServicesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ServicesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type ServicesUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ServicesUpdateFuture) Result(client ServicesClient) (sru ServiceResourceUpdate, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicefabric.ServicesUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if sru.Response.Response, err = future.GetResult(sender); err == nil && sru.Response.Response.StatusCode != http.StatusNoContent { + sru, err = client.UpdateResponder(sru.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesUpdateFuture", "Result", sru.Response.Response, "Failure responding to request") + } + } + return +} + +// ServiceTypeDeltaHealthPolicy represents the delta health policy used to evaluate the health of services +// belonging to a service type when upgrading the cluster. +type ServiceTypeDeltaHealthPolicy struct { + // MaxPercentDeltaUnhealthyServices - The maximum allowed percentage of services health degradation allowed during cluster upgrades. + // The delta is measured between the state of the services at the beginning of upgrade and the state of the services at the time of the health evaluation. + // The check is performed after every upgrade domain upgrade completion to make sure the global state of the cluster is within tolerated limits. + MaxPercentDeltaUnhealthyServices *int32 `json:"maxPercentDeltaUnhealthyServices,omitempty"` +} + +// ServiceTypeHealthPolicy represents the health policy used to evaluate the health of services belonging to a +// service type. +type ServiceTypeHealthPolicy struct { + // MaxPercentUnhealthyServices - The maximum percentage of services allowed to be unhealthy before your application is considered in error. + MaxPercentUnhealthyServices *int32 `json:"maxPercentUnhealthyServices,omitempty"` +} + +// SettingsParameterDescription describes a parameter in fabric settings of the cluster. +type SettingsParameterDescription struct { + // Name - The parameter name of fabric setting. + Name *string `json:"name,omitempty"` + // Value - The parameter value of fabric setting. + Value *string `json:"value,omitempty"` +} + +// SettingsSectionDescription describes a section in the fabric settings of the cluster. +type SettingsSectionDescription struct { + // Name - The section name of the fabric settings. + Name *string `json:"name,omitempty"` + // Parameters - The collection of parameters in the section. + Parameters *[]SettingsParameterDescription `json:"parameters,omitempty"` +} + +// SingletonPartitionSchemeDescription describes the partition scheme of a singleton-partitioned, or +// non-partitioned service. +type SingletonPartitionSchemeDescription struct { + // PartitionScheme - Possible values include: 'PartitionSchemePartitionSchemeDescription', 'PartitionSchemeNamed', 'PartitionSchemeSingleton', 'PartitionSchemeUniformInt64Range' + PartitionScheme PartitionSchemeBasicPartitionSchemeDescription `json:"PartitionScheme,omitempty"` +} + +// MarshalJSON is the custom marshaler for SingletonPartitionSchemeDescription. +func (spsd SingletonPartitionSchemeDescription) MarshalJSON() ([]byte, error) { + spsd.PartitionScheme = PartitionSchemeSingleton + objectMap := make(map[string]interface{}) + if spsd.PartitionScheme != "" { + objectMap["PartitionScheme"] = spsd.PartitionScheme + } + return json.Marshal(objectMap) +} + +// AsNamedPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for SingletonPartitionSchemeDescription. +func (spsd SingletonPartitionSchemeDescription) AsNamedPartitionSchemeDescription() (*NamedPartitionSchemeDescription, bool) { + return nil, false +} + +// AsSingletonPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for SingletonPartitionSchemeDescription. +func (spsd SingletonPartitionSchemeDescription) AsSingletonPartitionSchemeDescription() (*SingletonPartitionSchemeDescription, bool) { + return &spsd, true +} + +// AsUniformInt64RangePartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for SingletonPartitionSchemeDescription. +func (spsd SingletonPartitionSchemeDescription) AsUniformInt64RangePartitionSchemeDescription() (*UniformInt64RangePartitionSchemeDescription, bool) { + return nil, false +} + +// AsPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for SingletonPartitionSchemeDescription. +func (spsd SingletonPartitionSchemeDescription) AsPartitionSchemeDescription() (*PartitionSchemeDescription, bool) { + return nil, false +} + +// AsBasicPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for SingletonPartitionSchemeDescription. +func (spsd SingletonPartitionSchemeDescription) AsBasicPartitionSchemeDescription() (BasicPartitionSchemeDescription, bool) { + return &spsd, true +} + +// StatefulServiceProperties the properties of a stateful service resource. +type StatefulServiceProperties struct { + // HasPersistedState - A flag indicating whether this is a persistent service which stores states on the local disk. If it is then the value of this property is true, if not it is false. + HasPersistedState *bool `json:"hasPersistedState,omitempty"` + // TargetReplicaSetSize - The target replica set size as a number. + TargetReplicaSetSize *int32 `json:"targetReplicaSetSize,omitempty"` + // MinReplicaSetSize - The minimum replica set size as a number. + MinReplicaSetSize *int32 `json:"minReplicaSetSize,omitempty"` + // ReplicaRestartWaitDuration - The duration between when a replica goes down and when a new replica is created, represented in ISO 8601 format (hh:mm:ss.s). + ReplicaRestartWaitDuration *date.Time `json:"replicaRestartWaitDuration,omitempty"` + // QuorumLossWaitDuration - The maximum duration for which a partition is allowed to be in a state of quorum loss, represented in ISO 8601 format (hh:mm:ss.s). + QuorumLossWaitDuration *date.Time `json:"quorumLossWaitDuration,omitempty"` + // StandByReplicaKeepDuration - The definition on how long StandBy replicas should be maintained before being removed, represented in ISO 8601 format (hh:mm:ss.s). + StandByReplicaKeepDuration *date.Time `json:"standByReplicaKeepDuration,omitempty"` + // ProvisioningState - The current deployment or provisioning state, which only appears in the response + ProvisioningState *string `json:"provisioningState,omitempty"` + // ServiceTypeName - The name of the service type + ServiceTypeName *string `json:"serviceTypeName,omitempty"` + // PartitionDescription - Describes how the service is partitioned. + PartitionDescription BasicPartitionSchemeDescription `json:"partitionDescription,omitempty"` + // ServiceKind - Possible values include: 'ServiceKindServiceResourceProperties', 'ServiceKindStateful1', 'ServiceKindStateless1' + ServiceKind ServiceKindBasicServiceResourceProperties `json:"serviceKind,omitempty"` + // PlacementConstraints - The placement constraints as a string. Placement constraints are boolean expressions on node properties and allow for restricting a service to particular nodes based on the service requirements. For example, to place a service on nodes where NodeType is blue specify the following: "NodeColor == blue)". + PlacementConstraints *string `json:"placementConstraints,omitempty"` + // CorrelationScheme - A list that describes the correlation of the service with other services. + CorrelationScheme *[]ServiceCorrelationDescription `json:"correlationScheme,omitempty"` + // ServiceLoadMetrics - The service load metrics is given as an array of ServiceLoadMetricDescription objects. + ServiceLoadMetrics *[]ServiceLoadMetricDescription `json:"serviceLoadMetrics,omitempty"` + // ServicePlacementPolicies - A list that describes the correlation of the service with other services. + ServicePlacementPolicies *[]BasicServicePlacementPolicyDescription `json:"servicePlacementPolicies,omitempty"` + // DefaultMoveCost - Specifies the move cost for the service. Possible values include: 'Zero', 'Low', 'Medium', 'High' + DefaultMoveCost MoveCost `json:"defaultMoveCost,omitempty"` +} + +// MarshalJSON is the custom marshaler for StatefulServiceProperties. +func (ssp StatefulServiceProperties) MarshalJSON() ([]byte, error) { + ssp.ServiceKind = ServiceKindStateful1 + objectMap := make(map[string]interface{}) + if ssp.HasPersistedState != nil { + objectMap["hasPersistedState"] = ssp.HasPersistedState + } + if ssp.TargetReplicaSetSize != nil { + objectMap["targetReplicaSetSize"] = ssp.TargetReplicaSetSize + } + if ssp.MinReplicaSetSize != nil { + objectMap["minReplicaSetSize"] = ssp.MinReplicaSetSize + } + if ssp.ReplicaRestartWaitDuration != nil { + objectMap["replicaRestartWaitDuration"] = ssp.ReplicaRestartWaitDuration + } + if ssp.QuorumLossWaitDuration != nil { + objectMap["quorumLossWaitDuration"] = ssp.QuorumLossWaitDuration + } + if ssp.StandByReplicaKeepDuration != nil { + objectMap["standByReplicaKeepDuration"] = ssp.StandByReplicaKeepDuration + } + if ssp.ProvisioningState != nil { + objectMap["provisioningState"] = ssp.ProvisioningState + } + if ssp.ServiceTypeName != nil { + objectMap["serviceTypeName"] = ssp.ServiceTypeName + } + objectMap["partitionDescription"] = ssp.PartitionDescription + if ssp.ServiceKind != "" { + objectMap["serviceKind"] = ssp.ServiceKind + } + if ssp.PlacementConstraints != nil { + objectMap["placementConstraints"] = ssp.PlacementConstraints + } + if ssp.CorrelationScheme != nil { + objectMap["correlationScheme"] = ssp.CorrelationScheme + } + if ssp.ServiceLoadMetrics != nil { + objectMap["serviceLoadMetrics"] = ssp.ServiceLoadMetrics + } + if ssp.ServicePlacementPolicies != nil { + objectMap["servicePlacementPolicies"] = ssp.ServicePlacementPolicies + } + if ssp.DefaultMoveCost != "" { + objectMap["defaultMoveCost"] = ssp.DefaultMoveCost + } + return json.Marshal(objectMap) +} + +// AsStatefulServiceProperties is the BasicServiceResourceProperties implementation for StatefulServiceProperties. +func (ssp StatefulServiceProperties) AsStatefulServiceProperties() (*StatefulServiceProperties, bool) { + return &ssp, true +} + +// AsStatelessServiceProperties is the BasicServiceResourceProperties implementation for StatefulServiceProperties. +func (ssp StatefulServiceProperties) AsStatelessServiceProperties() (*StatelessServiceProperties, bool) { + return nil, false +} + +// AsServiceResourceProperties is the BasicServiceResourceProperties implementation for StatefulServiceProperties. +func (ssp StatefulServiceProperties) AsServiceResourceProperties() (*ServiceResourceProperties, bool) { + return nil, false +} + +// AsBasicServiceResourceProperties is the BasicServiceResourceProperties implementation for StatefulServiceProperties. +func (ssp StatefulServiceProperties) AsBasicServiceResourceProperties() (BasicServiceResourceProperties, bool) { + return &ssp, true +} + +// UnmarshalJSON is the custom unmarshaler for StatefulServiceProperties struct. +func (ssp *StatefulServiceProperties) 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 "hasPersistedState": + if v != nil { + var hasPersistedState bool + err = json.Unmarshal(*v, &hasPersistedState) + if err != nil { + return err + } + ssp.HasPersistedState = &hasPersistedState + } + case "targetReplicaSetSize": + if v != nil { + var targetReplicaSetSize int32 + err = json.Unmarshal(*v, &targetReplicaSetSize) + if err != nil { + return err + } + ssp.TargetReplicaSetSize = &targetReplicaSetSize + } + case "minReplicaSetSize": + if v != nil { + var minReplicaSetSize int32 + err = json.Unmarshal(*v, &minReplicaSetSize) + if err != nil { + return err + } + ssp.MinReplicaSetSize = &minReplicaSetSize + } + case "replicaRestartWaitDuration": + if v != nil { + var replicaRestartWaitDuration date.Time + err = json.Unmarshal(*v, &replicaRestartWaitDuration) + if err != nil { + return err + } + ssp.ReplicaRestartWaitDuration = &replicaRestartWaitDuration + } + case "quorumLossWaitDuration": + if v != nil { + var quorumLossWaitDuration date.Time + err = json.Unmarshal(*v, &quorumLossWaitDuration) + if err != nil { + return err + } + ssp.QuorumLossWaitDuration = &quorumLossWaitDuration + } + case "standByReplicaKeepDuration": + if v != nil { + var standByReplicaKeepDuration date.Time + err = json.Unmarshal(*v, &standByReplicaKeepDuration) + if err != nil { + return err + } + ssp.StandByReplicaKeepDuration = &standByReplicaKeepDuration + } + case "provisioningState": + if v != nil { + var provisioningState string + err = json.Unmarshal(*v, &provisioningState) + if err != nil { + return err + } + ssp.ProvisioningState = &provisioningState + } + case "serviceTypeName": + if v != nil { + var serviceTypeName string + err = json.Unmarshal(*v, &serviceTypeName) + if err != nil { + return err + } + ssp.ServiceTypeName = &serviceTypeName + } + case "partitionDescription": + if v != nil { + partitionDescription, err := unmarshalBasicPartitionSchemeDescription(*v) + if err != nil { + return err + } + ssp.PartitionDescription = partitionDescription + } + case "serviceKind": + if v != nil { + var serviceKind ServiceKindBasicServiceResourceProperties + err = json.Unmarshal(*v, &serviceKind) + if err != nil { + return err + } + ssp.ServiceKind = serviceKind + } + case "placementConstraints": + if v != nil { + var placementConstraints string + err = json.Unmarshal(*v, &placementConstraints) + if err != nil { + return err + } + ssp.PlacementConstraints = &placementConstraints + } + case "correlationScheme": + if v != nil { + var correlationScheme []ServiceCorrelationDescription + err = json.Unmarshal(*v, &correlationScheme) + if err != nil { + return err + } + ssp.CorrelationScheme = &correlationScheme + } + case "serviceLoadMetrics": + if v != nil { + var serviceLoadMetrics []ServiceLoadMetricDescription + err = json.Unmarshal(*v, &serviceLoadMetrics) + if err != nil { + return err + } + ssp.ServiceLoadMetrics = &serviceLoadMetrics + } + case "servicePlacementPolicies": + if v != nil { + servicePlacementPolicies, err := unmarshalBasicServicePlacementPolicyDescriptionArray(*v) + if err != nil { + return err + } + ssp.ServicePlacementPolicies = &servicePlacementPolicies + } + case "defaultMoveCost": + if v != nil { + var defaultMoveCost MoveCost + err = json.Unmarshal(*v, &defaultMoveCost) + if err != nil { + return err + } + ssp.DefaultMoveCost = defaultMoveCost + } + } + } + + return nil +} + +// StatefulServiceUpdateProperties the properties of a stateful service resource for patch operations. +type StatefulServiceUpdateProperties struct { + // TargetReplicaSetSize - The target replica set size as a number. + TargetReplicaSetSize *int32 `json:"targetReplicaSetSize,omitempty"` + // MinReplicaSetSize - The minimum replica set size as a number. + MinReplicaSetSize *int32 `json:"minReplicaSetSize,omitempty"` + // ReplicaRestartWaitDuration - The duration between when a replica goes down and when a new replica is created, represented in ISO 8601 format (hh:mm:ss.s). + ReplicaRestartWaitDuration *date.Time `json:"replicaRestartWaitDuration,omitempty"` + // QuorumLossWaitDuration - The maximum duration for which a partition is allowed to be in a state of quorum loss, represented in ISO 8601 format (hh:mm:ss.s). + QuorumLossWaitDuration *date.Time `json:"quorumLossWaitDuration,omitempty"` + // StandByReplicaKeepDuration - The definition on how long StandBy replicas should be maintained before being removed, represented in ISO 8601 format (hh:mm:ss.s). + StandByReplicaKeepDuration *date.Time `json:"standByReplicaKeepDuration,omitempty"` + // ServiceKind - Possible values include: 'ServiceKindBasicServiceResourceUpdatePropertiesServiceKindServiceResourceUpdateProperties', 'ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateful', 'ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateless' + ServiceKind ServiceKindBasicServiceResourceUpdateProperties `json:"serviceKind,omitempty"` + // PlacementConstraints - The placement constraints as a string. Placement constraints are boolean expressions on node properties and allow for restricting a service to particular nodes based on the service requirements. For example, to place a service on nodes where NodeType is blue specify the following: "NodeColor == blue)". + PlacementConstraints *string `json:"placementConstraints,omitempty"` + // CorrelationScheme - A list that describes the correlation of the service with other services. + CorrelationScheme *[]ServiceCorrelationDescription `json:"correlationScheme,omitempty"` + // ServiceLoadMetrics - The service load metrics is given as an array of ServiceLoadMetricDescription objects. + ServiceLoadMetrics *[]ServiceLoadMetricDescription `json:"serviceLoadMetrics,omitempty"` + // ServicePlacementPolicies - A list that describes the correlation of the service with other services. + ServicePlacementPolicies *[]BasicServicePlacementPolicyDescription `json:"servicePlacementPolicies,omitempty"` + // DefaultMoveCost - Specifies the move cost for the service. Possible values include: 'Zero', 'Low', 'Medium', 'High' + DefaultMoveCost MoveCost `json:"defaultMoveCost,omitempty"` +} + +// MarshalJSON is the custom marshaler for StatefulServiceUpdateProperties. +func (ssup StatefulServiceUpdateProperties) MarshalJSON() ([]byte, error) { + ssup.ServiceKind = ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateful + objectMap := make(map[string]interface{}) + if ssup.TargetReplicaSetSize != nil { + objectMap["targetReplicaSetSize"] = ssup.TargetReplicaSetSize + } + if ssup.MinReplicaSetSize != nil { + objectMap["minReplicaSetSize"] = ssup.MinReplicaSetSize + } + if ssup.ReplicaRestartWaitDuration != nil { + objectMap["replicaRestartWaitDuration"] = ssup.ReplicaRestartWaitDuration + } + if ssup.QuorumLossWaitDuration != nil { + objectMap["quorumLossWaitDuration"] = ssup.QuorumLossWaitDuration + } + if ssup.StandByReplicaKeepDuration != nil { + objectMap["standByReplicaKeepDuration"] = ssup.StandByReplicaKeepDuration + } + if ssup.ServiceKind != "" { + objectMap["serviceKind"] = ssup.ServiceKind + } + if ssup.PlacementConstraints != nil { + objectMap["placementConstraints"] = ssup.PlacementConstraints + } + if ssup.CorrelationScheme != nil { + objectMap["correlationScheme"] = ssup.CorrelationScheme + } + if ssup.ServiceLoadMetrics != nil { + objectMap["serviceLoadMetrics"] = ssup.ServiceLoadMetrics + } + if ssup.ServicePlacementPolicies != nil { + objectMap["servicePlacementPolicies"] = ssup.ServicePlacementPolicies + } + if ssup.DefaultMoveCost != "" { + objectMap["defaultMoveCost"] = ssup.DefaultMoveCost + } + return json.Marshal(objectMap) +} + +// AsStatefulServiceUpdateProperties is the BasicServiceResourceUpdateProperties implementation for StatefulServiceUpdateProperties. +func (ssup StatefulServiceUpdateProperties) AsStatefulServiceUpdateProperties() (*StatefulServiceUpdateProperties, bool) { + return &ssup, true +} + +// AsStatelessServiceUpdateProperties is the BasicServiceResourceUpdateProperties implementation for StatefulServiceUpdateProperties. +func (ssup StatefulServiceUpdateProperties) AsStatelessServiceUpdateProperties() (*StatelessServiceUpdateProperties, bool) { + return nil, false +} + +// AsServiceResourceUpdateProperties is the BasicServiceResourceUpdateProperties implementation for StatefulServiceUpdateProperties. +func (ssup StatefulServiceUpdateProperties) AsServiceResourceUpdateProperties() (*ServiceResourceUpdateProperties, bool) { + return nil, false +} + +// AsBasicServiceResourceUpdateProperties is the BasicServiceResourceUpdateProperties implementation for StatefulServiceUpdateProperties. +func (ssup StatefulServiceUpdateProperties) AsBasicServiceResourceUpdateProperties() (BasicServiceResourceUpdateProperties, bool) { + return &ssup, true +} + +// UnmarshalJSON is the custom unmarshaler for StatefulServiceUpdateProperties struct. +func (ssup *StatefulServiceUpdateProperties) 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 "targetReplicaSetSize": + if v != nil { + var targetReplicaSetSize int32 + err = json.Unmarshal(*v, &targetReplicaSetSize) + if err != nil { + return err + } + ssup.TargetReplicaSetSize = &targetReplicaSetSize + } + case "minReplicaSetSize": + if v != nil { + var minReplicaSetSize int32 + err = json.Unmarshal(*v, &minReplicaSetSize) + if err != nil { + return err + } + ssup.MinReplicaSetSize = &minReplicaSetSize + } + case "replicaRestartWaitDuration": + if v != nil { + var replicaRestartWaitDuration date.Time + err = json.Unmarshal(*v, &replicaRestartWaitDuration) + if err != nil { + return err + } + ssup.ReplicaRestartWaitDuration = &replicaRestartWaitDuration + } + case "quorumLossWaitDuration": + if v != nil { + var quorumLossWaitDuration date.Time + err = json.Unmarshal(*v, &quorumLossWaitDuration) + if err != nil { + return err + } + ssup.QuorumLossWaitDuration = &quorumLossWaitDuration + } + case "standByReplicaKeepDuration": + if v != nil { + var standByReplicaKeepDuration date.Time + err = json.Unmarshal(*v, &standByReplicaKeepDuration) + if err != nil { + return err + } + ssup.StandByReplicaKeepDuration = &standByReplicaKeepDuration + } + case "serviceKind": + if v != nil { + var serviceKind ServiceKindBasicServiceResourceUpdateProperties + err = json.Unmarshal(*v, &serviceKind) + if err != nil { + return err + } + ssup.ServiceKind = serviceKind + } + case "placementConstraints": + if v != nil { + var placementConstraints string + err = json.Unmarshal(*v, &placementConstraints) + if err != nil { + return err + } + ssup.PlacementConstraints = &placementConstraints + } + case "correlationScheme": + if v != nil { + var correlationScheme []ServiceCorrelationDescription + err = json.Unmarshal(*v, &correlationScheme) + if err != nil { + return err + } + ssup.CorrelationScheme = &correlationScheme + } + case "serviceLoadMetrics": + if v != nil { + var serviceLoadMetrics []ServiceLoadMetricDescription + err = json.Unmarshal(*v, &serviceLoadMetrics) + if err != nil { + return err + } + ssup.ServiceLoadMetrics = &serviceLoadMetrics + } + case "servicePlacementPolicies": + if v != nil { + servicePlacementPolicies, err := unmarshalBasicServicePlacementPolicyDescriptionArray(*v) + if err != nil { + return err + } + ssup.ServicePlacementPolicies = &servicePlacementPolicies + } + case "defaultMoveCost": + if v != nil { + var defaultMoveCost MoveCost + err = json.Unmarshal(*v, &defaultMoveCost) + if err != nil { + return err + } + ssup.DefaultMoveCost = defaultMoveCost + } + } + } + + return nil +} + +// StatelessServiceProperties the properties of a stateless service resource. +type StatelessServiceProperties struct { + // InstanceCount - The instance count. + InstanceCount *int32 `json:"instanceCount,omitempty"` + // ProvisioningState - The current deployment or provisioning state, which only appears in the response + ProvisioningState *string `json:"provisioningState,omitempty"` + // ServiceTypeName - The name of the service type + ServiceTypeName *string `json:"serviceTypeName,omitempty"` + // PartitionDescription - Describes how the service is partitioned. + PartitionDescription BasicPartitionSchemeDescription `json:"partitionDescription,omitempty"` + // ServiceKind - Possible values include: 'ServiceKindServiceResourceProperties', 'ServiceKindStateful1', 'ServiceKindStateless1' + ServiceKind ServiceKindBasicServiceResourceProperties `json:"serviceKind,omitempty"` + // PlacementConstraints - The placement constraints as a string. Placement constraints are boolean expressions on node properties and allow for restricting a service to particular nodes based on the service requirements. For example, to place a service on nodes where NodeType is blue specify the following: "NodeColor == blue)". + PlacementConstraints *string `json:"placementConstraints,omitempty"` + // CorrelationScheme - A list that describes the correlation of the service with other services. + CorrelationScheme *[]ServiceCorrelationDescription `json:"correlationScheme,omitempty"` + // ServiceLoadMetrics - The service load metrics is given as an array of ServiceLoadMetricDescription objects. + ServiceLoadMetrics *[]ServiceLoadMetricDescription `json:"serviceLoadMetrics,omitempty"` + // ServicePlacementPolicies - A list that describes the correlation of the service with other services. + ServicePlacementPolicies *[]BasicServicePlacementPolicyDescription `json:"servicePlacementPolicies,omitempty"` + // DefaultMoveCost - Specifies the move cost for the service. Possible values include: 'Zero', 'Low', 'Medium', 'High' + DefaultMoveCost MoveCost `json:"defaultMoveCost,omitempty"` +} + +// MarshalJSON is the custom marshaler for StatelessServiceProperties. +func (ssp StatelessServiceProperties) MarshalJSON() ([]byte, error) { + ssp.ServiceKind = ServiceKindStateless1 + objectMap := make(map[string]interface{}) + if ssp.InstanceCount != nil { + objectMap["instanceCount"] = ssp.InstanceCount + } + if ssp.ProvisioningState != nil { + objectMap["provisioningState"] = ssp.ProvisioningState + } + if ssp.ServiceTypeName != nil { + objectMap["serviceTypeName"] = ssp.ServiceTypeName + } + objectMap["partitionDescription"] = ssp.PartitionDescription + if ssp.ServiceKind != "" { + objectMap["serviceKind"] = ssp.ServiceKind + } + if ssp.PlacementConstraints != nil { + objectMap["placementConstraints"] = ssp.PlacementConstraints + } + if ssp.CorrelationScheme != nil { + objectMap["correlationScheme"] = ssp.CorrelationScheme + } + if ssp.ServiceLoadMetrics != nil { + objectMap["serviceLoadMetrics"] = ssp.ServiceLoadMetrics + } + if ssp.ServicePlacementPolicies != nil { + objectMap["servicePlacementPolicies"] = ssp.ServicePlacementPolicies + } + if ssp.DefaultMoveCost != "" { + objectMap["defaultMoveCost"] = ssp.DefaultMoveCost + } + return json.Marshal(objectMap) +} + +// AsStatefulServiceProperties is the BasicServiceResourceProperties implementation for StatelessServiceProperties. +func (ssp StatelessServiceProperties) AsStatefulServiceProperties() (*StatefulServiceProperties, bool) { + return nil, false +} + +// AsStatelessServiceProperties is the BasicServiceResourceProperties implementation for StatelessServiceProperties. +func (ssp StatelessServiceProperties) AsStatelessServiceProperties() (*StatelessServiceProperties, bool) { + return &ssp, true +} + +// AsServiceResourceProperties is the BasicServiceResourceProperties implementation for StatelessServiceProperties. +func (ssp StatelessServiceProperties) AsServiceResourceProperties() (*ServiceResourceProperties, bool) { + return nil, false +} + +// AsBasicServiceResourceProperties is the BasicServiceResourceProperties implementation for StatelessServiceProperties. +func (ssp StatelessServiceProperties) AsBasicServiceResourceProperties() (BasicServiceResourceProperties, bool) { + return &ssp, true +} + +// UnmarshalJSON is the custom unmarshaler for StatelessServiceProperties struct. +func (ssp *StatelessServiceProperties) 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 "instanceCount": + if v != nil { + var instanceCount int32 + err = json.Unmarshal(*v, &instanceCount) + if err != nil { + return err + } + ssp.InstanceCount = &instanceCount + } + case "provisioningState": + if v != nil { + var provisioningState string + err = json.Unmarshal(*v, &provisioningState) + if err != nil { + return err + } + ssp.ProvisioningState = &provisioningState + } + case "serviceTypeName": + if v != nil { + var serviceTypeName string + err = json.Unmarshal(*v, &serviceTypeName) + if err != nil { + return err + } + ssp.ServiceTypeName = &serviceTypeName + } + case "partitionDescription": + if v != nil { + partitionDescription, err := unmarshalBasicPartitionSchemeDescription(*v) + if err != nil { + return err + } + ssp.PartitionDescription = partitionDescription + } + case "serviceKind": + if v != nil { + var serviceKind ServiceKindBasicServiceResourceProperties + err = json.Unmarshal(*v, &serviceKind) + if err != nil { + return err + } + ssp.ServiceKind = serviceKind + } + case "placementConstraints": + if v != nil { + var placementConstraints string + err = json.Unmarshal(*v, &placementConstraints) + if err != nil { + return err + } + ssp.PlacementConstraints = &placementConstraints + } + case "correlationScheme": + if v != nil { + var correlationScheme []ServiceCorrelationDescription + err = json.Unmarshal(*v, &correlationScheme) + if err != nil { + return err + } + ssp.CorrelationScheme = &correlationScheme + } + case "serviceLoadMetrics": + if v != nil { + var serviceLoadMetrics []ServiceLoadMetricDescription + err = json.Unmarshal(*v, &serviceLoadMetrics) + if err != nil { + return err + } + ssp.ServiceLoadMetrics = &serviceLoadMetrics + } + case "servicePlacementPolicies": + if v != nil { + servicePlacementPolicies, err := unmarshalBasicServicePlacementPolicyDescriptionArray(*v) + if err != nil { + return err + } + ssp.ServicePlacementPolicies = &servicePlacementPolicies + } + case "defaultMoveCost": + if v != nil { + var defaultMoveCost MoveCost + err = json.Unmarshal(*v, &defaultMoveCost) + if err != nil { + return err + } + ssp.DefaultMoveCost = defaultMoveCost + } + } + } + + return nil +} + +// StatelessServiceUpdateProperties the properties of a stateless service resource for patch operations. +type StatelessServiceUpdateProperties struct { + // InstanceCount - The instance count. + InstanceCount *int32 `json:"instanceCount,omitempty"` + // ServiceKind - Possible values include: 'ServiceKindBasicServiceResourceUpdatePropertiesServiceKindServiceResourceUpdateProperties', 'ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateful', 'ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateless' + ServiceKind ServiceKindBasicServiceResourceUpdateProperties `json:"serviceKind,omitempty"` + // PlacementConstraints - The placement constraints as a string. Placement constraints are boolean expressions on node properties and allow for restricting a service to particular nodes based on the service requirements. For example, to place a service on nodes where NodeType is blue specify the following: "NodeColor == blue)". + PlacementConstraints *string `json:"placementConstraints,omitempty"` + // CorrelationScheme - A list that describes the correlation of the service with other services. + CorrelationScheme *[]ServiceCorrelationDescription `json:"correlationScheme,omitempty"` + // ServiceLoadMetrics - The service load metrics is given as an array of ServiceLoadMetricDescription objects. + ServiceLoadMetrics *[]ServiceLoadMetricDescription `json:"serviceLoadMetrics,omitempty"` + // ServicePlacementPolicies - A list that describes the correlation of the service with other services. + ServicePlacementPolicies *[]BasicServicePlacementPolicyDescription `json:"servicePlacementPolicies,omitempty"` + // DefaultMoveCost - Specifies the move cost for the service. Possible values include: 'Zero', 'Low', 'Medium', 'High' + DefaultMoveCost MoveCost `json:"defaultMoveCost,omitempty"` +} + +// MarshalJSON is the custom marshaler for StatelessServiceUpdateProperties. +func (ssup StatelessServiceUpdateProperties) MarshalJSON() ([]byte, error) { + ssup.ServiceKind = ServiceKindBasicServiceResourceUpdatePropertiesServiceKindStateless + objectMap := make(map[string]interface{}) + if ssup.InstanceCount != nil { + objectMap["instanceCount"] = ssup.InstanceCount + } + if ssup.ServiceKind != "" { + objectMap["serviceKind"] = ssup.ServiceKind + } + if ssup.PlacementConstraints != nil { + objectMap["placementConstraints"] = ssup.PlacementConstraints + } + if ssup.CorrelationScheme != nil { + objectMap["correlationScheme"] = ssup.CorrelationScheme + } + if ssup.ServiceLoadMetrics != nil { + objectMap["serviceLoadMetrics"] = ssup.ServiceLoadMetrics + } + if ssup.ServicePlacementPolicies != nil { + objectMap["servicePlacementPolicies"] = ssup.ServicePlacementPolicies + } + if ssup.DefaultMoveCost != "" { + objectMap["defaultMoveCost"] = ssup.DefaultMoveCost + } + return json.Marshal(objectMap) +} + +// AsStatefulServiceUpdateProperties is the BasicServiceResourceUpdateProperties implementation for StatelessServiceUpdateProperties. +func (ssup StatelessServiceUpdateProperties) AsStatefulServiceUpdateProperties() (*StatefulServiceUpdateProperties, bool) { + return nil, false +} + +// AsStatelessServiceUpdateProperties is the BasicServiceResourceUpdateProperties implementation for StatelessServiceUpdateProperties. +func (ssup StatelessServiceUpdateProperties) AsStatelessServiceUpdateProperties() (*StatelessServiceUpdateProperties, bool) { + return &ssup, true +} + +// AsServiceResourceUpdateProperties is the BasicServiceResourceUpdateProperties implementation for StatelessServiceUpdateProperties. +func (ssup StatelessServiceUpdateProperties) AsServiceResourceUpdateProperties() (*ServiceResourceUpdateProperties, bool) { + return nil, false +} + +// AsBasicServiceResourceUpdateProperties is the BasicServiceResourceUpdateProperties implementation for StatelessServiceUpdateProperties. +func (ssup StatelessServiceUpdateProperties) AsBasicServiceResourceUpdateProperties() (BasicServiceResourceUpdateProperties, bool) { + return &ssup, true +} + +// UnmarshalJSON is the custom unmarshaler for StatelessServiceUpdateProperties struct. +func (ssup *StatelessServiceUpdateProperties) 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 "instanceCount": + if v != nil { + var instanceCount int32 + err = json.Unmarshal(*v, &instanceCount) + if err != nil { + return err + } + ssup.InstanceCount = &instanceCount + } + case "serviceKind": + if v != nil { + var serviceKind ServiceKindBasicServiceResourceUpdateProperties + err = json.Unmarshal(*v, &serviceKind) + if err != nil { + return err + } + ssup.ServiceKind = serviceKind + } + case "placementConstraints": + if v != nil { + var placementConstraints string + err = json.Unmarshal(*v, &placementConstraints) + if err != nil { + return err + } + ssup.PlacementConstraints = &placementConstraints + } + case "correlationScheme": + if v != nil { + var correlationScheme []ServiceCorrelationDescription + err = json.Unmarshal(*v, &correlationScheme) + if err != nil { + return err + } + ssup.CorrelationScheme = &correlationScheme + } + case "serviceLoadMetrics": + if v != nil { + var serviceLoadMetrics []ServiceLoadMetricDescription + err = json.Unmarshal(*v, &serviceLoadMetrics) + if err != nil { + return err + } + ssup.ServiceLoadMetrics = &serviceLoadMetrics + } + case "servicePlacementPolicies": + if v != nil { + servicePlacementPolicies, err := unmarshalBasicServicePlacementPolicyDescriptionArray(*v) + if err != nil { + return err + } + ssup.ServicePlacementPolicies = &servicePlacementPolicies + } + case "defaultMoveCost": + if v != nil { + var defaultMoveCost MoveCost + err = json.Unmarshal(*v, &defaultMoveCost) + if err != nil { + return err + } + ssup.DefaultMoveCost = defaultMoveCost + } + } + } + + return nil +} + +// UniformInt64RangePartitionSchemeDescription describes a partitioning scheme where an integer range is allocated +// evenly across a number of partitions. +type UniformInt64RangePartitionSchemeDescription struct { + // Count - The number of partitions. + Count *int32 `json:"Count,omitempty"` + // LowKey - String indicating the lower bound of the partition key range that + // should be split between the partition ‘Count’ + LowKey *string `json:"LowKey,omitempty"` + // HighKey - String indicating the upper bound of the partition key range that + // should be split between the partition ‘Count’ + HighKey *string `json:"HighKey,omitempty"` + // PartitionScheme - Possible values include: 'PartitionSchemePartitionSchemeDescription', 'PartitionSchemeNamed', 'PartitionSchemeSingleton', 'PartitionSchemeUniformInt64Range' + PartitionScheme PartitionSchemeBasicPartitionSchemeDescription `json:"PartitionScheme,omitempty"` +} + +// MarshalJSON is the custom marshaler for UniformInt64RangePartitionSchemeDescription. +func (ui6rpsd UniformInt64RangePartitionSchemeDescription) MarshalJSON() ([]byte, error) { + ui6rpsd.PartitionScheme = PartitionSchemeUniformInt64Range + objectMap := make(map[string]interface{}) + if ui6rpsd.Count != nil { + objectMap["Count"] = ui6rpsd.Count + } + if ui6rpsd.LowKey != nil { + objectMap["LowKey"] = ui6rpsd.LowKey + } + if ui6rpsd.HighKey != nil { + objectMap["HighKey"] = ui6rpsd.HighKey + } + if ui6rpsd.PartitionScheme != "" { + objectMap["PartitionScheme"] = ui6rpsd.PartitionScheme + } + return json.Marshal(objectMap) +} + +// AsNamedPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for UniformInt64RangePartitionSchemeDescription. +func (ui6rpsd UniformInt64RangePartitionSchemeDescription) AsNamedPartitionSchemeDescription() (*NamedPartitionSchemeDescription, bool) { + return nil, false +} + +// AsSingletonPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for UniformInt64RangePartitionSchemeDescription. +func (ui6rpsd UniformInt64RangePartitionSchemeDescription) AsSingletonPartitionSchemeDescription() (*SingletonPartitionSchemeDescription, bool) { + return nil, false +} + +// AsUniformInt64RangePartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for UniformInt64RangePartitionSchemeDescription. +func (ui6rpsd UniformInt64RangePartitionSchemeDescription) AsUniformInt64RangePartitionSchemeDescription() (*UniformInt64RangePartitionSchemeDescription, bool) { + return &ui6rpsd, true +} + +// AsPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for UniformInt64RangePartitionSchemeDescription. +func (ui6rpsd UniformInt64RangePartitionSchemeDescription) AsPartitionSchemeDescription() (*PartitionSchemeDescription, bool) { + return nil, false +} + +// AsBasicPartitionSchemeDescription is the BasicPartitionSchemeDescription implementation for UniformInt64RangePartitionSchemeDescription. +func (ui6rpsd UniformInt64RangePartitionSchemeDescription) AsBasicPartitionSchemeDescription() (BasicPartitionSchemeDescription, bool) { + return &ui6rpsd, true +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/operations.go new file mode 100644 index 0000000000000..617b66ddc49e3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/operations.go @@ -0,0 +1,126 @@ +package servicefabric + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// OperationsClient is the service Fabric Management Client +type OperationsClient struct { + BaseClient +} + +// NewOperationsClient creates an instance of the OperationsClient client. +func NewOperationsClient(subscriptionID string) OperationsClient { + return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client. +func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { + return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List get the list of available Service Fabric resource provider API operations. +func (client OperationsClient) List(ctx context.Context) (result OperationListResultPage, err error) { + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.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, "servicefabric.OperationsClient", "List", resp, "Failure sending request") + return + } + + result.olr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.OperationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + const APIVersion = "" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.ServiceFabric/operations"), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client OperationsClient) listNextResults(lastResults OperationListResult) (result OperationListResult, err error) { + req, err := lastResults.operationListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicefabric.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, "servicefabric.OperationsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.OperationsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client OperationsClient) ListComplete(ctx context.Context) (result OperationListResultIterator, err error) { + result.page, err = client.List(ctx) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/services.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/services.go new file mode 100644 index 0000000000000..8cbc4ffed22e4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/services.go @@ -0,0 +1,412 @@ +package servicefabric + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ServicesClient is the service Fabric Management Client +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. +func NewServicesClientWithBaseURI(baseURI string, subscriptionID string) ServicesClient { + return ServicesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Create create or update a Service Fabric service resource with the specified name. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationName - the name of the application resource. +// serviceName - the name of the service resource in the format of {applicationName}~{serviceName}. +// parameters - the service resource. +func (client ServicesClient) Create(ctx context.Context, resourceGroupName string, clusterName string, applicationName string, serviceName string, parameters ServiceResource) (result ServicesCreateFuture, err error) { + req, err := client.CreatePreparer(ctx, resourceGroupName, clusterName, applicationName, serviceName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesClient", "Create", nil, "Failure preparing request") + return + } + + result, err = client.CreateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesClient", "Create", result.Response(), "Failure sending request") + return + } + + return +} + +// CreatePreparer prepares the Create request. +func (client ServicesClient) CreatePreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationName string, serviceName string, parameters ServiceResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationName": autorest.Encode("path", applicationName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applications/{applicationName}/services/{serviceName}", pathParameters), + autorest.WithJSON(parameters), + 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 ServicesClient) CreateSender(req *http.Request) (future ServicesCreateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client ServicesClient) CreateResponder(resp *http.Response) (result ServiceResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete a Service Fabric service resource with the specified name. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationName - the name of the application resource. +// serviceName - the name of the service resource in the format of {applicationName}~{serviceName}. +func (client ServicesClient) Delete(ctx context.Context, resourceGroupName string, clusterName string, applicationName string, serviceName string) (result ServicesDeleteFuture, err error) { + req, err := client.DeletePreparer(ctx, resourceGroupName, clusterName, applicationName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ServicesClient) DeletePreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationName": autorest.Encode("path", applicationName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applications/{applicationName}/services/{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 + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ServicesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get a Service Fabric service resource created or in the process of being created in the Service Fabric +// application resource. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationName - the name of the application resource. +// serviceName - the name of the service resource in the format of {applicationName}~{serviceName}. +func (client ServicesClient) Get(ctx context.Context, resourceGroupName string, clusterName string, applicationName string, serviceName string) (result ServiceResource, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, clusterName, applicationName, serviceName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.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, "servicefabric.ServicesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ServicesClient) GetPreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationName string, serviceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationName": autorest.Encode("path", applicationName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applications/{applicationName}/services/{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 autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ServicesClient) GetResponder(resp *http.Response) (result ServiceResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets all service resources created or in the process of being created in the Service Fabric application +// resource. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationName - the name of the application resource. +func (client ServicesClient) List(ctx context.Context, resourceGroupName string, clusterName string, applicationName string) (result ServiceResourceList, err error) { + req, err := client.ListPreparer(ctx, resourceGroupName, clusterName, applicationName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicefabric.ServicesClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ServicesClient) ListPreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationName": autorest.Encode("path", applicationName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applications/{applicationName}/services", 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 autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ServicesClient) ListResponder(resp *http.Response) (result ServiceResourceList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update update a Service Fabric service resource with the specified name. +// Parameters: +// resourceGroupName - the name of the resource group. +// clusterName - the name of the cluster resource. +// applicationName - the name of the application resource. +// serviceName - the name of the service resource in the format of {applicationName}~{serviceName}. +// parameters - the service resource for patch operations. +func (client ServicesClient) Update(ctx context.Context, resourceGroupName string, clusterName string, applicationName string, serviceName string, parameters ServiceResourceUpdate) (result ServicesUpdateFuture, err error) { + req, err := client.UpdatePreparer(ctx, resourceGroupName, clusterName, applicationName, serviceName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicefabric.ServicesClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client ServicesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, clusterName string, applicationName string, serviceName string, parameters ServiceResourceUpdate) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "applicationName": autorest.Encode("path", applicationName), + "clusterName": autorest.Encode("path", clusterName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceName": autorest.Encode("path", serviceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-07-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.ServiceFabric/clusters/{clusterName}/applications/{applicationName}/services/{serviceName}", 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 ServicesClient) UpdateSender(req *http.Request) (future ServicesUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + 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 ServiceResourceUpdate, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + 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/dns/mgmt/2017-10-01/dns/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/version.go similarity index 91% rename from vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/version.go rename to vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/version.go index 34ac2e2261ec6..9f2d3bd80f534 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric/version.go @@ -1,4 +1,4 @@ -package dns +package servicefabric import "github.com/Azure/azure-sdk-for-go/version" @@ -21,7 +21,7 @@ import "github.com/Azure/azure-sdk-for-go/version" // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return "Azure-SDK-For-Go/" + version.Number + " dns/2017-10-01" + return "Azure-SDK-For-Go/" + version.Number + " servicefabric/2018-02-01" } // Version returns the semantic version (see http://semver.org) of the client. diff --git a/vendor/github.com/hashicorp/errwrap/README.md b/vendor/github.com/hashicorp/errwrap/README.md index 1c95f59782bb5..444df08f8e775 100644 --- a/vendor/github.com/hashicorp/errwrap/README.md +++ b/vendor/github.com/hashicorp/errwrap/README.md @@ -48,7 +48,7 @@ func main() { // We can use the Contains helpers to check if an error contains // another error. It is safe to do this with a nil error, or with // an error that doesn't even use the errwrap package. - if errwrap.Contains(err, ErrNotExist) { + if errwrap.Contains(err, "does not exist") { // Do something } if errwrap.ContainsType(err, new(os.PathError)) { diff --git a/vendor/github.com/mitchellh/go-homedir/homedir.go b/vendor/github.com/mitchellh/go-homedir/homedir.go index 47e1f9ef8e6c9..fb87bef94f3f7 100644 --- a/vendor/github.com/mitchellh/go-homedir/homedir.go +++ b/vendor/github.com/mitchellh/go-homedir/homedir.go @@ -77,33 +77,51 @@ func Expand(path string) (string, error) { } func dirUnix() (string, error) { + homeEnv := "HOME" + if runtime.GOOS == "plan9" { + // On plan9, env vars are lowercase. + homeEnv = "home" + } + // First prefer the HOME environmental variable - if home := os.Getenv("HOME"); home != "" { + if home := os.Getenv(homeEnv); home != "" { return home, nil } - // If that fails, try getent var stdout bytes.Buffer - cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid())) - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - // If the error is ErrNotFound, we ignore it. Otherwise, return it. - if err != exec.ErrNotFound { - return "", err + + // If that fails, try OS specific commands + if runtime.GOOS == "darwin" { + cmd := exec.Command("sh", "-c", `dscl -q . -read /Users/"$(whoami)" NFSHomeDirectory | sed 's/^[^ ]*: //'`) + cmd.Stdout = &stdout + if err := cmd.Run(); err == nil { + result := strings.TrimSpace(stdout.String()) + if result != "" { + return result, nil + } } } else { - if passwd := strings.TrimSpace(stdout.String()); passwd != "" { - // username:password:uid:gid:gecos:home:shell - passwdParts := strings.SplitN(passwd, ":", 7) - if len(passwdParts) > 5 { - return passwdParts[5], nil + cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid())) + cmd.Stdout = &stdout + if err := cmd.Run(); err != nil { + // If the error is ErrNotFound, we ignore it. Otherwise, return it. + if err != exec.ErrNotFound { + return "", err + } + } else { + if passwd := strings.TrimSpace(stdout.String()); passwd != "" { + // username:password:uid:gid:gecos:home:shell + passwdParts := strings.SplitN(passwd, ":", 7) + if len(passwdParts) > 5 { + return passwdParts[5], nil + } } } } // If all else fails, try the shell stdout.Reset() - cmd = exec.Command("sh", "-c", "cd && pwd") + cmd := exec.Command("sh", "-c", "cd && pwd") cmd.Stdout = &stdout if err := cmd.Run(); err != nil { return "", err @@ -123,14 +141,16 @@ func dirWindows() (string, error) { return home, nil } + // Prefer standard environment variable USERPROFILE + if home := os.Getenv("USERPROFILE"); home != "" { + return home, nil + } + drive := os.Getenv("HOMEDRIVE") path := os.Getenv("HOMEPATH") home := drive + path if drive == "" || path == "" { - home = os.Getenv("USERPROFILE") - } - if home == "" { - return "", errors.New("HOMEDRIVE, HOMEPATH, and USERPROFILE are blank") + return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE are blank") } return home, nil diff --git a/vendor/github.com/rancher/go-rancher/Dockerfile.dapper b/vendor/github.com/rancher/go-rancher/Dockerfile.dapper deleted file mode 100644 index d5bfad7a7402a..0000000000000 --- a/vendor/github.com/rancher/go-rancher/Dockerfile.dapper +++ /dev/null @@ -1,30 +0,0 @@ -FROM ubuntu:16.04 -# FROM arm=armhf/ubuntu:16.04 - -ARG DAPPER_HOST_ARCH=amd64 -ENV HOST_ARCH=${DAPPER_HOST_ARCH} ARCH=${DAPPER_HOST_ARCH} - -RUN apt-get update && \ - apt-get install -y gcc ca-certificates git wget curl vim less file && \ - rm -f /bin/sh && ln -s /bin/bash /bin/sh - -ENV GOLANG_ARCH_amd64=amd64 GOLANG_ARCH_arm=armv6l GOLANG_ARCH=GOLANG_ARCH_${ARCH} \ - GOPATH=/go PATH=/go/bin:/usr/local/go/bin:${PATH} SHELL=/bin/bash - -ENV DOCKER_URL_amd64=https://get.docker.com/builds/Linux/x86_64/docker-1.10.3 \ - DOCKER_URL_arm=https://github.com/rancher/docker/releases/download/v1.10.3-ros1/docker-1.10.3_arm \ - DOCKER_URL=DOCKER_URL_${ARCH} -RUN wget -O - ${!DOCKER_URL} > /usr/bin/docker && chmod +x /usr/bin/docker - -RUN wget -O - https://storage.googleapis.com/golang/go1.7.1.linux-${!GOLANG_ARCH}.tar.gz | tar -xzf - -C /usr/local && \ - go get github.com/rancher/trash && go get github.com/golang/lint/golint - -ENV DAPPER_SOURCE /go/src/github.com/rancher/go-rancher/ -ENV DAPPER_OUTPUT ./bin -ENV DAPPER_DOCKER_SOCKET true -ENV TRASH_CACHE ${DAPPER_SOURCE}/.trash-cache -ENV HOME ${DAPPER_SOURCE} -WORKDIR ${DAPPER_SOURCE} - -ENTRYPOINT ["./scripts/entry"] -CMD ["ci"] diff --git a/vendor/github.com/rancher/go-rancher/LICENSE b/vendor/github.com/rancher/go-rancher/LICENSE deleted file mode 100644 index f433b1a53f5b8..0000000000000 --- a/vendor/github.com/rancher/go-rancher/LICENSE +++ /dev/null @@ -1,177 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS diff --git a/vendor/github.com/rancher/go-rancher/Makefile b/vendor/github.com/rancher/go-rancher/Makefile deleted file mode 100644 index d7d72a16d549c..0000000000000 --- a/vendor/github.com/rancher/go-rancher/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -TARGETS := $(shell ls scripts) - -.dapper: - @echo Downloading dapper - @curl -sL https://releases.rancher.com/dapper/latest/dapper-`uname -s`-`uname -m` > .dapper.tmp - @@chmod +x .dapper.tmp - @./.dapper.tmp -v - @mv .dapper.tmp .dapper - -$(TARGETS): .dapper - ./.dapper $@ - -trash: .dapper - ./.dapper -m bind trash - -trash-keep: .dapper - ./.dapper -m bind trash -k - -deps: trash - -.DEFAULT_GOAL := ci - -.PHONY: $(TARGETS) diff --git a/vendor/github.com/rancher/go-rancher/README.md b/vendor/github.com/rancher/go-rancher/README.md deleted file mode 100644 index 58e479a9d4932..0000000000000 --- a/vendor/github.com/rancher/go-rancher/README.md +++ /dev/null @@ -1,55 +0,0 @@ -# Go Bindings for Rancher API - -# Generating Code -First, you must have a master version of Rancher running. The best way to do this is: -```sh -docker run -p 8080:8080 -d rancher/server:master -``` - -Once Rancher is running, you can run the gen-schema.sh script: -```sh -./scripts/gen-schema.sh http://:8080 - -# The default url is http://localhost:8080, so if rancher/server is listening on localhost, you can omit the url: -./scripts/gen-schema.sh -``` - -This will add, remove, and modify go files appropriately. Submit a PR that includes *all* these changes. - -## Important caveats -1. If you are running on macOS, you must have gnu-sed installed as sed for this to work properly. -2. If you are running against cattle that is running out of an IDE and you don't have go-machine-service running (you probably don't), you'll see a number of unexpected removed or modified files like `generated_host.go` `generated_machine.go` and `generated_*config.go`. - -# Building - -```sh -godep go build ./client -``` - -# Tests - -```sh -godep go test ./client -``` -# Contact -For bugs, questions, comments, corrections, suggestions, etc., open an issue in - [rancher/rancher](//github.com/rancher/rancher/issues) with a title starting with `[go-rancher] `. - -Or just [click here](//github.com/rancher/rancher/issues/new?title=%5Bgo-rancher%5D%20) to create a new issue. - - -# License -Copyright (c) 2014-2015 [Rancher Labs, Inc.](http://rancher.com) - -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](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/github.com/rancher/go-rancher/main.go b/vendor/github.com/rancher/go-rancher/main.go deleted file mode 100644 index e8274c8a1b106..0000000000000 --- a/vendor/github.com/rancher/go-rancher/main.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import ( - "fmt" - _ "github.com/rancher/go-rancher/client" -) - -func main() { - fmt.Println("I have nothing to do...") -} diff --git a/vendor/github.com/rancher/go-rancher/trash.conf b/vendor/github.com/rancher/go-rancher/trash.conf deleted file mode 100644 index 30cb3a9597330..0000000000000 --- a/vendor/github.com/rancher/go-rancher/trash.conf +++ /dev/null @@ -1,6 +0,0 @@ -github.com/pkg/errors 1d2e60385a13aaa66134984235061c2f9302520e -github.com/gorilla/context 215affda49addc4c8ef7e2534915df2c8c35c6cd -github.com/gorilla/mux f15e0c49460fd49eebe2bcc8486b05d1bef68d3a -github.com/gorilla/websocket 1551221275a7bd42978745a376b2531f791d88f3 -github.com/Sirupsen/logrus 26709e2714106fb8ad40b773b711ebce25b78914 -gopkg.in/yaml.v2 a83829b6f1293c91addabc89d0571c246397bbf4 diff --git a/vendor/vendor.json b/vendor/vendor.json index 4740f90bb3125..79f43333cd0e6 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -123,8 +123,8 @@ "versionExact": "v18.0.0" }, { - "checksumSHA1": "UllFPDJZazs7Vy9wdcfKPe0r1u0=", - "path": "github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices", + "checksumSHA1": "kVhbkr1IPBMGfJbFHY4fbr/c2wU=", + "path": "github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2018-04-01/devices", "revision": "fbe7db0e3f9793ba3e5704efbab84f51436c136e", "revisionTime": "2018-07-03T19:15:42Z", "version": "=v18.0.0", @@ -322,6 +322,14 @@ "version": "=v18.0.0", "versionExact": "v18.0.0" }, + { + "checksumSHA1": "E6K9qLJIuos/ZGzhOpfbCxb77MQ=", + "path": "github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2018-02-01/servicefabric", + "revision": "fbe7db0e3f9793ba3e5704efbab84f51436c136e", + "revisionTime": "2018-07-03T19:15:42Z", + "version": "=v18.0.0", + "versionExact": "v18.0.0" + }, { "checksumSHA1": "ySkjHczHi2zN8B1TuWfvKVLGetw=", "path": "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2017-10-01/storage", @@ -736,9 +744,10 @@ "revisionTime": "2017-08-14T14:36:39Z" }, { - "checksumSHA1": "cdOCt0Yb+hdErz8NAQqayxPmRsY=", + "checksumSHA1": "dVqCmA2mEDIDr8tEXu4gTaK9uPs=", "path": "github.com/hashicorp/errwrap", - "revision": "7554cd9344cec97297fa6649b055a8c98c2a1e55" + "revision": "d6c0cd88035724dd42e0f335ae30161c20575ecc", + "revisionTime": "2018-07-15T04:49:06Z" }, { "checksumSHA1": "b8F628srIitj5p7Y130xc9k0QWs=", @@ -1166,10 +1175,10 @@ "revisionTime": "2016-10-13T19:53:42Z" }, { - "checksumSHA1": "V/quM7+em2ByJbWBLOsEwnY3j/Q=", + "checksumSHA1": "Li0PaRmaVBdibS/zs8myzc07L6o=", "path": "github.com/mitchellh/go-homedir", - "revision": "b8bc1bf767474819792c23f32d8286a45736f1c6", - "revisionTime": "2016-12-03T19:45:07Z" + "revision": "58046073cbffe2f25d425fe1331102f55cf719de", + "revisionTime": "2018-08-01T23:32:06Z" }, { "checksumSHA1": "6TBW88DSxRHf4WvOC9K5ilBZx/8=", @@ -1224,12 +1233,6 @@ "revision": "88e59760adaddb8276c9b15511302890690e2dae", "revisionTime": "2017-09-08T12:52:45Z" }, - { - "checksumSHA1": "u5s2PZ7fzCOqQX7bVPf9IJ+qNLQ=", - "path": "github.com/rancher/go-rancher", - "revision": "ec24b7f12fca9f78fbfcd62a0ea8bce14ade8792", - "revisionTime": "2017-04-07T04:09:43Z" - }, { "checksumSHA1": "zmC8/3V4ls53DJlNTKDZwPSC/dA=", "path": "github.com/satori/go.uuid", diff --git a/website/azurerm.erb b/website/azurerm.erb index 847623041c633..c5ce3bfb0ac74 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -103,6 +103,10 @@ azurerm_kubernetes_cluster + > + azurerm_log_analytics_workspace + + > azurerm_logic_app_workflow @@ -700,9 +704,13 @@ - > + > Monitor Resources + > + Service Fabric Resources + + + > Storage Resources