diff --git a/azurerm/config.go b/azurerm/config.go index 8fdb95d19a7a..585ad9ba1e93 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -12,6 +12,7 @@ import ( "github.com/Azure/azure-sdk-for-go/arm/containerregistry" "github.com/Azure/azure-sdk-for-go/arm/containerservice" "github.com/Azure/azure-sdk-for-go/arm/disk" + "github.com/Azure/azure-sdk-for-go/arm/documentdb" "github.com/Azure/azure-sdk-for-go/arm/eventhub" "github.com/Azure/azure-sdk-for-go/arm/keyvault" "github.com/Azure/azure-sdk-for-go/arm/network" @@ -50,7 +51,8 @@ type ArmClient struct { vmImageClient compute.VirtualMachineImagesClient vmClient compute.VirtualMachinesClient - diskClient disk.DisksClient + diskClient disk.DisksClient + documentDBClient documentdb.DatabaseAccountsClient appGatewayClient network.ApplicationGatewaysClient ifaceClient network.InterfacesClient @@ -254,6 +256,12 @@ func (c *Config) getArmClient() (*ArmClient, error) { csc.Sender = autorest.CreateSender(withRequestLogging()) client.containerServicesClient = csc + ddb := documentdb.NewDatabaseAccountsClientWithBaseURI(endpoint, c.SubscriptionID) + setUserAgent(&ddb.Client) + ddb.Authorizer = auth + ddb.Sender = autorest.CreateSender(withRequestLogging()) + client.documentDBClient = ddb + dkc := disk.NewDisksClientWithBaseURI(endpoint, c.SubscriptionID) setUserAgent(&dkc.Client) dkc.Authorizer = auth diff --git a/azurerm/import_arm_cosmosdb_account_test.go b/azurerm/import_arm_cosmosdb_account_test.go new file mode 100644 index 000000000000..593ff18319f9 --- /dev/null +++ b/azurerm/import_arm_cosmosdb_account_test.go @@ -0,0 +1,152 @@ +package azurerm + +import ( + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccAzureRMCosmosDBAccount_importBoundedStaleness(t *testing.T) { + resourceName := "azurerm_cosmosdb_account.test" + + ri := acctest.RandInt() + config := testAccAzureRMCosmosDBAccount_boundedStaleness(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMCosmosDBAccount_importBoundedStalenessComplete(t *testing.T) { + resourceName := "azurerm_cosmosdb_account.test" + + ri := acctest.RandInt() + config := testAccAzureRMCosmosDBAccount_boundedStalenessComplete(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMCosmosDBAccount_importEventualConsistency(t *testing.T) { + resourceName := "azurerm_cosmosdb_account.test" + + ri := acctest.RandInt() + config := testAccAzureRMCosmosDBAccount_eventualConsistency(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMCosmosDBAccount_importSession(t *testing.T) { + resourceName := "azurerm_cosmosdb_account.test" + + ri := acctest.RandInt() + config := testAccAzureRMCosmosDBAccount_session(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMCosmosDBAccount_importStrong(t *testing.T) { + resourceName := "azurerm_cosmosdb_account.test" + + ri := acctest.RandInt() + config := testAccAzureRMCosmosDBAccount_strong(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAzureRMCosmosDBAccount_importGeoReplicated(t *testing.T) { + resourceName := "azurerm_cosmosdb_account.test" + + ri := acctest.RandInt() + config := testAccAzureRMCosmosDBAccount_geoReplicated(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/azurerm/provider.go b/azurerm/provider.go index 05c10505cfd9..bddfae7acf36 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -74,6 +74,7 @@ func Provider() terraform.ResourceProvider { "azurerm_cdn_profile": resourceArmCdnProfile(), "azurerm_container_registry": resourceArmContainerRegistry(), "azurerm_container_service": resourceArmContainerService(), + "azurerm_cosmosdb_account": resourceArmCosmosDBAccount(), "azurerm_eventhub": resourceArmEventHub(), "azurerm_eventhub_authorization_rule": resourceArmEventHubAuthorizationRule(), diff --git a/azurerm/resource_arm_cosmos_db_account.go b/azurerm/resource_arm_cosmos_db_account.go new file mode 100644 index 000000000000..75c46e6ffb8f --- /dev/null +++ b/azurerm/resource_arm_cosmos_db_account.go @@ -0,0 +1,411 @@ +package azurerm + +import ( + "bytes" + "fmt" + "log" + "net/http" + "regexp" + + "github.com/Azure/azure-sdk-for-go/arm/documentdb" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" +) + +func resourceArmCosmosDBAccount() *schema.Resource { + return &schema.Resource{ + Create: resourceArmCosmosDBAccountCreateUpdate, + Read: resourceArmCosmosDBAccountRead, + Update: resourceArmCosmosDBAccountCreateUpdate, + Delete: resourceArmCosmosDBAccountDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateAzureRmCosmosDBAccountName, + }, + + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: azureRMNormalizeLocation, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "offer_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(documentdb.Standard), + }, true), + }, + + "ip_range_filter": { + Type: schema.TypeString, + Optional: true, + }, + + "consistency_policy": { + Type: schema.TypeSet, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "consistency_level": { + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + ValidateFunc: validation.StringInSlice([]string{ + string(documentdb.BoundedStaleness), + string(documentdb.Eventual), + string(documentdb.Session), + string(documentdb.Strong), + }, true), + }, + + "max_interval_in_seconds": { + Type: schema.TypeInt, + Optional: true, + Default: 5, + ValidateFunc: validation.IntBetween(1, 100), + }, + + "max_staleness_prefix": { + Type: schema.TypeInt, + Optional: true, + Default: 100, + ValidateFunc: validation.IntBetween(1, 2147483647), + }, + }, + }, + Set: resourceAzureRMCosmosDBAccountConsistencyPolicyHash, + }, + + "failover_policy": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "location": { + Type: schema.TypeString, + Required: true, + StateFunc: azureRMNormalizeLocation, + }, + + "priority": { + Type: schema.TypeInt, + Required: true, + }, + }, + }, + Set: resourceAzureRMCosmosDBAccountFailoverPolicyHash, + }, + + "primary_master_key": { + Type: schema.TypeString, + Computed: true, + }, + + "secondary_master_key": { + Type: schema.TypeString, + Computed: true, + }, + + "primary_readonly_master_key": { + Type: schema.TypeString, + Computed: true, + }, + + "secondary_readonly_master_key": { + Type: schema.TypeString, + Computed: true, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmCosmosDBAccountCreateUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).documentDBClient + log.Printf("[INFO] preparing arguments for AzureRM Cosmos DB Account creation.") + + name := d.Get("name").(string) + location := d.Get("location").(string) + resGroup := d.Get("resource_group_name").(string) + offerType := d.Get("offer_type").(string) + ipRangeFilter := d.Get("ip_range_filter").(string) + + consistencyPolicy := expandAzureRmCosmosDBAccountConsistencyPolicy(d) + failoverPolicies, err := expandAzureRmCosmosDBAccountFailoverPolicies(name, d) + if err != nil { + return err + } + tags := d.Get("tags").(map[string]interface{}) + + parameters := documentdb.DatabaseAccountCreateUpdateParameters{ + Location: &location, + DatabaseAccountCreateUpdateProperties: &documentdb.DatabaseAccountCreateUpdateProperties{ + ConsistencyPolicy: &consistencyPolicy, + DatabaseAccountOfferType: &offerType, + Locations: &failoverPolicies, + IPRangeFilter: &ipRangeFilter, + }, + Tags: expandTags(tags), + } + + _, error := client.CreateOrUpdate(resGroup, name, parameters, make(chan struct{})) + err = <-error + if err != nil { + return err + } + + read, err := client.Get(resGroup, name) + if err != nil { + return err + } + + if read.ID == nil { + return fmt.Errorf("Cannot read CosmosDB Account '%s' (resource group %s) ID", name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmCosmosDBAccountRead(d, meta) +} + +func resourceArmCosmosDBAccountRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).documentDBClient + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["databaseAccounts"] + + resp, err := client.Get(resGroup, name) + if err != nil { + return fmt.Errorf("Error making Read request on AzureRM CosmosDB Account '%s': %s", name, err) + } + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + + d.Set("name", resp.Name) + d.Set("location", azureRMNormalizeLocation(*resp.Location)) + d.Set("resource_group_name", resGroup) + d.Set("offer_type", string(resp.DatabaseAccountOfferType)) + d.Set("ip_range_filter", resp.IPRangeFilter) + flattenAndSetAzureRmCosmosDBAccountConsistencyPolicy(d, resp.ConsistencyPolicy) + flattenAndSetAzureRmCosmosDBAccountFailoverPolicy(d, resp.FailoverPolicies) + + keys, err := client.ListKeys(resGroup, name) + if err != nil { + log.Printf("[ERROR] Unable to List Write keys for CosmosDB Account %s: %s", name, err) + } else { + d.Set("primary_master_key", keys.PrimaryMasterKey) + d.Set("secondary_master_key", keys.SecondaryMasterKey) + } + + readonlyKeys, err := client.ListReadOnlyKeys(resGroup, name) + if err != nil { + log.Printf("[ERROR] Unable to List read-only keys for CosmosDB Account %s: %s", name, err) + } else { + d.Set("primary_readonly_master_key", readonlyKeys.PrimaryReadonlyMasterKey) + d.Set("secondary_readonly_master_key", readonlyKeys.SecondaryReadonlyMasterKey) + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmCosmosDBAccountDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).documentDBClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["databaseAccounts"] + + deleteResp, error := client.Delete(resGroup, name, make(chan struct{})) + resp := <-deleteResp + err = <-error + + if err != nil { + if resp.StatusCode == http.StatusNotFound { + return nil + } + + return fmt.Errorf("Error issuing AzureRM delete request for CosmosDB Account '%s': %+v", name, err) + } + + return nil +} + +func expandAzureRmCosmosDBAccountConsistencyPolicy(d *schema.ResourceData) documentdb.ConsistencyPolicy { + inputs := d.Get("consistency_policy").(*schema.Set).List() + input := inputs[0].(map[string]interface{}) + + consistencyLevel := input["consistency_level"].(string) + + policy := documentdb.ConsistencyPolicy{ + DefaultConsistencyLevel: documentdb.DefaultConsistencyLevel(consistencyLevel), + } + + if stalenessPrefix := input["max_staleness_prefix"].(int); stalenessPrefix > 0 { + maxStalenessPrefix := int64(stalenessPrefix) + policy.MaxStalenessPrefix = &maxStalenessPrefix + } + + if maxInterval := input["max_interval_in_seconds"].(int); maxInterval > 0 { + maxIntervalInSeconds := int32(maxInterval) + policy.MaxIntervalInSeconds = &maxIntervalInSeconds + } + + return policy +} + +func expandAzureRmCosmosDBAccountFailoverPolicies(databaseName string, d *schema.ResourceData) ([]documentdb.Location, error) { + input := d.Get("failover_policy").(*schema.Set).List() + locations := make([]documentdb.Location, 0, len(input)) + + for _, configRaw := range input { + data := configRaw.(map[string]interface{}) + + locationName := azureRMNormalizeLocation(data["location"].(string)) + id := fmt.Sprintf("%s-%s", databaseName, locationName) + failoverPriority := int32(data["priority"].(int)) + + location := documentdb.Location{ + ID: &id, + LocationName: &locationName, + FailoverPriority: &failoverPriority, + } + + locations = append(locations, location) + } + + containsWriteLocation := false + writeFailoverPriority := int32(0) + for _, location := range locations { + if *location.FailoverPriority == writeFailoverPriority { + containsWriteLocation = true + break + } + } + + // all priorities must be unique + locationIds := make(map[int]struct{}, len(locations)) + for _, location := range locations { + priority := int(*location.FailoverPriority) + if _, ok := locationIds[priority]; ok { + err := fmt.Errorf("Each Failover Policy needs to be unique") + return nil, err + } + + locationIds[priority] = struct{}{} + } + + if !containsWriteLocation { + err := fmt.Errorf("Failover Policy should contain a Write Location (Location '0')") + return nil, err + } + + return locations, nil +} + +func flattenAndSetAzureRmCosmosDBAccountConsistencyPolicy(d *schema.ResourceData, policy *documentdb.ConsistencyPolicy) { + results := schema.Set{ + F: resourceAzureRMCosmosDBAccountConsistencyPolicyHash, + } + + result := map[string]interface{}{} + result["consistency_level"] = string(policy.DefaultConsistencyLevel) + result["max_interval_in_seconds"] = int(*policy.MaxIntervalInSeconds) + result["max_staleness_prefix"] = int(*policy.MaxStalenessPrefix) + results.Add(result) + + d.Set("consistency_policy", &results) +} + +func flattenAndSetAzureRmCosmosDBAccountFailoverPolicy(d *schema.ResourceData, list *[]documentdb.FailoverPolicy) { + results := schema.Set{ + F: resourceAzureRMCosmosDBAccountFailoverPolicyHash, + } + + for _, i := range *list { + result := map[string]interface{}{ + "id": *i.ID, + "location": azureRMNormalizeLocation(*i.LocationName), + "priority": int(*i.FailoverPriority), + } + + results.Add(result) + } + + d.Set("failover_policy", &results) +} + +func resourceAzureRMCosmosDBAccountConsistencyPolicyHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + + consistencyLevel := m["consistency_level"].(string) + maxInterval := m["max_interval_in_seconds"].(int) + maxStalenessPrefix := m["max_staleness_prefix"].(int) + + buf.WriteString(fmt.Sprintf("%s-%d-%d", consistencyLevel, maxInterval, maxStalenessPrefix)) + + return hashcode.String(buf.String()) +} + +func resourceAzureRMCosmosDBAccountFailoverPolicyHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + + locationName := m["location"].(string) + location := azureRMNormalizeLocation(locationName) + priority := int32(m["priority"].(int)) + + buf.WriteString(fmt.Sprintf("%s-%d", location, priority)) + + return hashcode.String(buf.String()) +} + +func validateAzureRmCosmosDBAccountName(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + + r, _ := regexp.Compile("[a-z0-9-]") + if !r.MatchString(value) { + errors = append(errors, fmt.Errorf("CosmosDB Account Name can only contain lower-case characters, numbers and the `-` character.")) + } + + length := len(value) + if length > 50 || 3 > length { + errors = append(errors, fmt.Errorf("CosmosDB Account Name can only be between 3 and 50 seconds.")) + } + + return +} diff --git a/azurerm/resource_arm_cosmos_db_account_test.go b/azurerm/resource_arm_cosmos_db_account_test.go new file mode 100644 index 000000000000..14ad1a893701 --- /dev/null +++ b/azurerm/resource_arm_cosmos_db_account_test.go @@ -0,0 +1,368 @@ +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 TestAccAzureRMCosmosDBAccountName_validation(t *testing.T) { + str := acctest.RandString(50) + cases := []struct { + Value string + ErrCount int + }{ + { + Value: "ab", + ErrCount: 1, + }, + { + Value: "abc", + ErrCount: 0, + }, + { + Value: str, + ErrCount: 0, + }, + { + Value: str + "a", + ErrCount: 1, + }, + } + + for _, tc := range cases { + _, errors := validateAzureRmCosmosDBAccountName(tc.Value, "azurerm_cosmosdb_account") + + if len(errors) != tc.ErrCount { + t.Fatalf("Expected the AzureRM CosmosDB Name to trigger a validation error for '%s'", tc.Value) + } + } +} + +func TestAccAzureRMCosmosDBAccount_boundedStaleness(t *testing.T) { + + ri := acctest.RandInt() + config := testAccAzureRMCosmosDBAccount_boundedStaleness(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMCosmosDBAccount_boundedStalenessComplete(t *testing.T) { + + ri := acctest.RandInt() + config := testAccAzureRMCosmosDBAccount_boundedStalenessComplete(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMCosmosDBAccount_eventualConsistency(t *testing.T) { + ri := acctest.RandInt() + config := testAccAzureRMCosmosDBAccount_eventualConsistency(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMCosmosDBAccount_session(t *testing.T) { + ri := acctest.RandInt() + config := testAccAzureRMCosmosDBAccount_session(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMCosmosDBAccount_strong(t *testing.T) { + ri := acctest.RandInt() + config := testAccAzureRMCosmosDBAccount_strong(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMCosmosDBAccount_geoReplicated(t *testing.T) { + + ri := acctest.RandInt() + config := testAccAzureRMCosmosDBAccount_geoReplicated(ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCosmosDBAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMCosmosDBAccountExists("azurerm_cosmosdb_account.test"), + ), + }, + }, + }) +} + +func testCheckAzureRMCosmosDBAccountDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).documentDBClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_cosmos_db" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, name) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("CosmosDB Account still exists:\n%#v", resp) + } + } + + return nil +} + +func testCheckAzureRMCosmosDBAccountExists(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) + } + + name := 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 CosmosDB Account: '%s'", name) + } + + conn := testAccProvider.Meta().(*ArmClient).documentDBClient + + resp, err := conn.Get(resourceGroup, name) + if err != nil { + return fmt.Errorf("Bad: Get on documentDBClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: CosmosDB Account '%s' (resource group: '%s') does not exist", name, resourceGroup) + } + + return nil + } +} + +func testAccAzureRMCosmosDBAccount_boundedStaleness(rInt int) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US" +} +resource "azurerm_cosmosdb_account" "test" { + name = "acctest-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + offer_type = "Standard" + + consistency_policy { + consistency_level = "BoundedStaleness" + } + + failover_policy { + location = "${azurerm_resource_group.test.location}" + priority = 0 + } +} +`, rInt, rInt) +} + +func testAccAzureRMCosmosDBAccount_boundedStalenessComplete(rInt int) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US" +} +resource "azurerm_cosmosdb_account" "test" { + name = "acctest-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + offer_type = "Standard" + + consistency_policy { + consistency_level = "BoundedStaleness" + max_interval_in_seconds = 10 + max_staleness_prefix = 200 + } + + failover_policy { + location = "${azurerm_resource_group.test.location}" + priority = 0 + } +} +`, rInt, rInt) +} + +func testAccAzureRMCosmosDBAccount_eventualConsistency(rInt int) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US" +} +resource "azurerm_cosmosdb_account" "test" { + name = "acctest-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + offer_type = "Standard" + + consistency_policy { + consistency_level = "Eventual" + } + + failover_policy { + location = "${azurerm_resource_group.test.location}" + priority = 0 + } +} +`, rInt, rInt) +} + +func testAccAzureRMCosmosDBAccount_session(rInt int) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US" +} +resource "azurerm_cosmosdb_account" "test" { + name = "acctest-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + offer_type = "Standard" + + consistency_policy { + consistency_level = "Session" + } + + failover_policy { + location = "${azurerm_resource_group.test.location}" + priority = 0 + } +} +`, rInt, rInt) +} + +func testAccAzureRMCosmosDBAccount_strong(rInt int) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US" +} +resource "azurerm_cosmosdb_account" "test" { + name = "acctest-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + offer_type = "Standard" + + consistency_policy { + consistency_level = "Strong" + } + + failover_policy { + location = "${azurerm_resource_group.test.location}" + priority = 0 + } +} +`, rInt, rInt) +} + +func testAccAzureRMCosmosDBAccount_geoReplicated(rInt int) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "West US" +} +resource "azurerm_cosmosdb_account" "test" { + name = "acctest-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + offer_type = "Standard" + + consistency_policy { + consistency_level = "BoundedStaleness" + max_interval_in_seconds = 10 + max_staleness_prefix = 200 + } + + failover_policy { + location = "${azurerm_resource_group.test.location}" + priority = 0 + } + + failover_policy { + location = "West Europe" + priority = 1 + } +} +`, rInt, rInt) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/documentdb/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/documentdb/client.go new file mode 100755 index 000000000000..5c0752c01209 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/documentdb/client.go @@ -0,0 +1,53 @@ +// Package documentdb implements the Azure ARM Documentdb service API version +// 2015-04-08. +// +// Azure DocumentDB Database Service Resource Provider REST API +package documentdb + +// 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 1.0.1.0 +// 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 Documentdb + DefaultBaseURI = "https://management.azure.com" +) + +// ManagementClient is the base client for Documentdb. +type ManagementClient struct { + autorest.Client + BaseURI string + SubscriptionID string +} + +// New creates an instance of the ManagementClient client. +func New(subscriptionID string) ManagementClient { + return NewWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWithBaseURI creates an instance of the ManagementClient client. +func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { + return ManagementClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + SubscriptionID: subscriptionID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/documentdb/databaseaccounts.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/documentdb/databaseaccounts.go new file mode 100755 index 000000000000..7d4480742267 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/documentdb/databaseaccounts.go @@ -0,0 +1,1069 @@ +package documentdb + +// 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 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// DatabaseAccountsClient is the azure DocumentDB Database Service Resource +// Provider REST API +type DatabaseAccountsClient struct { + ManagementClient +} + +// NewDatabaseAccountsClient creates an instance of the DatabaseAccountsClient +// client. +func NewDatabaseAccountsClient(subscriptionID string) DatabaseAccountsClient { + return NewDatabaseAccountsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewDatabaseAccountsClientWithBaseURI creates an instance of the +// DatabaseAccountsClient client. +func NewDatabaseAccountsClientWithBaseURI(baseURI string, subscriptionID string) DatabaseAccountsClient { + return DatabaseAccountsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CheckNameExists checks that the Azure DocumentDB account name already +// exists. A valid account name may contain only lowercase letters, numbers, +// and the '-' character, and must be between 3 and 50 characters. +// +// accountName is documentDB database account name. +func (client DatabaseAccountsClient) CheckNameExists(accountName string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "documentdb.DatabaseAccountsClient", "CheckNameExists") + } + + req, err := client.CheckNameExistsPreparer(accountName) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "CheckNameExists", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameExistsSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "CheckNameExists", resp, "Failure sending request") + return + } + + result, err = client.CheckNameExistsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "CheckNameExists", resp, "Failure responding to request") + } + + return +} + +// CheckNameExistsPreparer prepares the CheckNameExists request. +func (client DatabaseAccountsClient) CheckNameExistsPreparer(accountName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + } + + const APIVersion = "2015-04-08" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsHead(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/providers/Microsoft.DocumentDB/databaseAccountNames/{accountName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// CheckNameExistsSender sends the CheckNameExists request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseAccountsClient) CheckNameExistsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// CheckNameExistsResponder handles the response to the CheckNameExists request. The method always +// closes the http.Response Body. +func (client DatabaseAccountsClient) CheckNameExistsResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNotFound), + autorest.ByClosing()) + result.Response = resp + return +} + +// CreateOrUpdate creates or updates an Azure DocumentDB database account. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and any +// outstanding HTTP requests. +// +// resourceGroupName is name of an Azure resource group. accountName is +// documentDB database account name. createUpdateParameters is the parameters +// to provide for the current database account. +func (client DatabaseAccountsClient) CreateOrUpdate(resourceGroupName string, accountName string, createUpdateParameters DatabaseAccountCreateUpdateParameters, cancel <-chan struct{}) (<-chan DatabaseAccount, <-chan error) { + resultChan := make(chan DatabaseAccount, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}, + {TargetValue: createUpdateParameters, + Constraints: []validation.Constraint{{Target: "createUpdateParameters.DatabaseAccountCreateUpdateProperties", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "createUpdateParameters.DatabaseAccountCreateUpdateProperties.ConsistencyPolicy", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "createUpdateParameters.DatabaseAccountCreateUpdateProperties.ConsistencyPolicy.MaxStalenessPrefix", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "createUpdateParameters.DatabaseAccountCreateUpdateProperties.ConsistencyPolicy.MaxStalenessPrefix", Name: validation.InclusiveMaximum, Rule: 2147483647, Chain: nil}, + {Target: "createUpdateParameters.DatabaseAccountCreateUpdateProperties.ConsistencyPolicy.MaxStalenessPrefix", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}, + {Target: "createUpdateParameters.DatabaseAccountCreateUpdateProperties.ConsistencyPolicy.MaxIntervalInSeconds", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "createUpdateParameters.DatabaseAccountCreateUpdateProperties.ConsistencyPolicy.MaxIntervalInSeconds", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "createUpdateParameters.DatabaseAccountCreateUpdateProperties.ConsistencyPolicy.MaxIntervalInSeconds", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}, + }}, + {Target: "createUpdateParameters.DatabaseAccountCreateUpdateProperties.Locations", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "createUpdateParameters.DatabaseAccountCreateUpdateProperties.DatabaseAccountOfferType", Name: validation.Null, Rule: true, Chain: nil}, + }}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "documentdb.DatabaseAccountsClient", "CreateOrUpdate") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result DatabaseAccount + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, accountName, createUpdateParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client DatabaseAccountsClient) CreateOrUpdatePreparer(resourceGroupName string, accountName string, createUpdateParameters DatabaseAccountCreateUpdateParameters, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2015-04-08" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}", pathParameters), + autorest.WithJSON(createUpdateParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseAccountsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client DatabaseAccountsClient) CreateOrUpdateResponder(resp *http.Response) (result DatabaseAccount, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an existing Azure DocumentDB database account. This method +// may poll for completion. Polling can be canceled by passing the cancel +// channel argument. The channel will be used to cancel polling and any +// outstanding HTTP requests. +// +// resourceGroupName is name of an Azure resource group. accountName is +// documentDB database account name. +func (client DatabaseAccountsClient) Delete(resourceGroupName string, accountName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "documentdb.DatabaseAccountsClient", "Delete") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, accountName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// DeletePreparer prepares the Delete request. +func (client DatabaseAccountsClient) DeletePreparer(resourceGroupName string, accountName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2015-04-08" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseAccountsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client DatabaseAccountsClient) 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 +} + +// FailoverPriorityChange changes the failover priority for the Azure +// DocumentDB database account. A failover priority of 0 indicates a write +// region. The maximum value for a failover priority = (total number of regions +// - 1). Failover priority values must be unique for each of the regions in +// which the database account exists. This method may poll for completion. +// Polling can be canceled by passing the cancel channel argument. The channel +// will be used to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is name of an Azure resource group. accountName is +// documentDB database account name. failoverParameters is the new failover +// policies for the database account. +func (client DatabaseAccountsClient) FailoverPriorityChange(resourceGroupName string, accountName string, failoverParameters FailoverPolicies, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "documentdb.DatabaseAccountsClient", "FailoverPriorityChange") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.FailoverPriorityChangePreparer(resourceGroupName, accountName, failoverParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "FailoverPriorityChange", nil, "Failure preparing request") + return + } + + resp, err := client.FailoverPriorityChangeSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "FailoverPriorityChange", resp, "Failure sending request") + return + } + + result, err = client.FailoverPriorityChangeResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "FailoverPriorityChange", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// FailoverPriorityChangePreparer prepares the FailoverPriorityChange request. +func (client DatabaseAccountsClient) FailoverPriorityChangePreparer(resourceGroupName string, accountName string, failoverParameters FailoverPolicies, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2015-04-08" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/failoverPriorityChange", pathParameters), + autorest.WithJSON(failoverParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// FailoverPriorityChangeSender sends the FailoverPriorityChange request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseAccountsClient) FailoverPriorityChangeSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// FailoverPriorityChangeResponder handles the response to the FailoverPriorityChange request. The method always +// closes the http.Response Body. +func (client DatabaseAccountsClient) FailoverPriorityChangeResponder(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 retrieves the properties of an existing Azure DocumentDB database +// account. +// +// resourceGroupName is name of an Azure resource group. accountName is +// documentDB database account name. +func (client DatabaseAccountsClient) Get(resourceGroupName string, accountName string) (result DatabaseAccount, 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}}}, + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "documentdb.DatabaseAccountsClient", "Get") + } + + req, err := client.GetPreparer(resourceGroupName, accountName) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client DatabaseAccountsClient) GetPreparer(resourceGroupName string, accountName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2015-04-08" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseAccountsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client DatabaseAccountsClient) GetResponder(resp *http.Response) (result DatabaseAccount, 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 all the Azure DocumentDB database accounts available under the +// subscription. +func (client DatabaseAccountsClient) List() (result DatabaseAccountsListResult, err error) { + req, err := client.ListPreparer() + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client DatabaseAccountsClient) ListPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2015-04-08" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/databaseAccounts", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseAccountsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client DatabaseAccountsClient) ListResponder(resp *http.Response) (result DatabaseAccountsListResult, 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 lists all the Azure DocumentDB database accounts +// available under the given resource group. +// +// resourceGroupName is name of an Azure resource group. +func (client DatabaseAccountsClient) ListByResourceGroup(resourceGroupName string) (result DatabaseAccountsListResult, 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.NewErrorWithValidationError(err, "documentdb.DatabaseAccountsClient", "ListByResourceGroup") + } + + req, err := client.ListByResourceGroupPreparer(resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client DatabaseAccountsClient) ListByResourceGroupPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2015-04-08" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseAccountsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client DatabaseAccountsClient) ListByResourceGroupResponder(resp *http.Response) (result DatabaseAccountsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListConnectionStrings lists the connection strings for the specified Azure +// DocumentDB database account. +// +// resourceGroupName is name of an Azure resource group. accountName is +// documentDB database account name. +func (client DatabaseAccountsClient) ListConnectionStrings(resourceGroupName string, accountName string) (result DatabaseAccountListConnectionStringsResult, 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}}}, + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "documentdb.DatabaseAccountsClient", "ListConnectionStrings") + } + + req, err := client.ListConnectionStringsPreparer(resourceGroupName, accountName) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "ListConnectionStrings", nil, "Failure preparing request") + return + } + + resp, err := client.ListConnectionStringsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "ListConnectionStrings", resp, "Failure sending request") + return + } + + result, err = client.ListConnectionStringsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "ListConnectionStrings", resp, "Failure responding to request") + } + + return +} + +// ListConnectionStringsPreparer prepares the ListConnectionStrings request. +func (client DatabaseAccountsClient) ListConnectionStringsPreparer(resourceGroupName string, accountName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2015-04-08" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/listConnectionStrings", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListConnectionStringsSender sends the ListConnectionStrings request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseAccountsClient) ListConnectionStringsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListConnectionStringsResponder handles the response to the ListConnectionStrings request. The method always +// closes the http.Response Body. +func (client DatabaseAccountsClient) ListConnectionStringsResponder(resp *http.Response) (result DatabaseAccountListConnectionStringsResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListKeys lists the access keys for the specified Azure DocumentDB database +// account. +// +// resourceGroupName is name of an Azure resource group. accountName is +// documentDB database account name. +func (client DatabaseAccountsClient) ListKeys(resourceGroupName string, accountName string) (result DatabaseAccountListKeysResult, 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}}}, + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "documentdb.DatabaseAccountsClient", "ListKeys") + } + + req, err := client.ListKeysPreparer(resourceGroupName, accountName) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "ListKeys", nil, "Failure preparing request") + return + } + + resp, err := client.ListKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "ListKeys", resp, "Failure sending request") + return + } + + result, err = client.ListKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "ListKeys", resp, "Failure responding to request") + } + + return +} + +// ListKeysPreparer prepares the ListKeys request. +func (client DatabaseAccountsClient) ListKeysPreparer(resourceGroupName string, accountName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2015-04-08" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/listKeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListKeysSender sends the ListKeys request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseAccountsClient) ListKeysSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListKeysResponder handles the response to the ListKeys request. The method always +// closes the http.Response Body. +func (client DatabaseAccountsClient) ListKeysResponder(resp *http.Response) (result DatabaseAccountListKeysResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListReadOnlyKeys lists the read-only access keys for the specified Azure +// DocumentDB database account. +// +// resourceGroupName is name of an Azure resource group. accountName is +// documentDB database account name. +func (client DatabaseAccountsClient) ListReadOnlyKeys(resourceGroupName string, accountName string) (result DatabaseAccountListReadOnlyKeysResult, 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}}}, + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "documentdb.DatabaseAccountsClient", "ListReadOnlyKeys") + } + + req, err := client.ListReadOnlyKeysPreparer(resourceGroupName, accountName) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "ListReadOnlyKeys", nil, "Failure preparing request") + return + } + + resp, err := client.ListReadOnlyKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "ListReadOnlyKeys", resp, "Failure sending request") + return + } + + result, err = client.ListReadOnlyKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "ListReadOnlyKeys", resp, "Failure responding to request") + } + + return +} + +// ListReadOnlyKeysPreparer prepares the ListReadOnlyKeys request. +func (client DatabaseAccountsClient) ListReadOnlyKeysPreparer(resourceGroupName string, accountName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2015-04-08" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/readonlykeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListReadOnlyKeysSender sends the ListReadOnlyKeys request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseAccountsClient) ListReadOnlyKeysSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListReadOnlyKeysResponder handles the response to the ListReadOnlyKeys request. The method always +// closes the http.Response Body. +func (client DatabaseAccountsClient) ListReadOnlyKeysResponder(resp *http.Response) (result DatabaseAccountListReadOnlyKeysResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Patch patches the properties of an existing Azure DocumentDB database +// account. This method may poll for completion. Polling can be canceled by +// passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. +// +// resourceGroupName is name of an Azure resource group. accountName is +// documentDB database account name. updateParameters is the tags parameter to +// patch for the current database account. +func (client DatabaseAccountsClient) Patch(resourceGroupName string, accountName string, updateParameters DatabaseAccountPatchParameters, cancel <-chan struct{}) (<-chan DatabaseAccount, <-chan error) { + resultChan := make(chan DatabaseAccount, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "documentdb.DatabaseAccountsClient", "Patch") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result DatabaseAccount + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.PatchPreparer(resourceGroupName, accountName, updateParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "Patch", nil, "Failure preparing request") + return + } + + resp, err := client.PatchSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "Patch", resp, "Failure sending request") + return + } + + result, err = client.PatchResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "Patch", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// PatchPreparer prepares the Patch request. +func (client DatabaseAccountsClient) PatchPreparer(resourceGroupName string, accountName string, updateParameters DatabaseAccountPatchParameters, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2015-04-08" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}", pathParameters), + autorest.WithJSON(updateParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// PatchSender sends the Patch request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseAccountsClient) PatchSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// PatchResponder handles the response to the Patch request. The method always +// closes the http.Response Body. +func (client DatabaseAccountsClient) PatchResponder(resp *http.Response) (result DatabaseAccount, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// RegenerateKey regenerates an access key for the specified Azure DocumentDB +// database account. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used to +// cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is name of an Azure resource group. accountName is +// documentDB database account name. keyToRegenerate is the name of the key to +// regenerate. +func (client DatabaseAccountsClient) RegenerateKey(resourceGroupName string, accountName string, keyToRegenerate DatabaseAccountRegenerateKeyParameters, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "documentdb.DatabaseAccountsClient", "RegenerateKey") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.RegenerateKeyPreparer(resourceGroupName, accountName, keyToRegenerate, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "RegenerateKey", nil, "Failure preparing request") + return + } + + resp, err := client.RegenerateKeySender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "RegenerateKey", resp, "Failure sending request") + return + } + + result, err = client.RegenerateKeyResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "documentdb.DatabaseAccountsClient", "RegenerateKey", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// RegenerateKeyPreparer prepares the RegenerateKey request. +func (client DatabaseAccountsClient) RegenerateKeyPreparer(resourceGroupName string, accountName string, keyToRegenerate DatabaseAccountRegenerateKeyParameters, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2015-04-08" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/regenerateKey", pathParameters), + autorest.WithJSON(keyToRegenerate), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// RegenerateKeySender sends the RegenerateKey request. The method will close the +// http.Response Body if it receives an error. +func (client DatabaseAccountsClient) RegenerateKeySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// RegenerateKeyResponder handles the response to the RegenerateKey request. The method always +// closes the http.Response Body. +func (client DatabaseAccountsClient) RegenerateKeyResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/documentdb/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/documentdb/models.go new file mode 100755 index 000000000000..cc2d6de0384e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/documentdb/models.go @@ -0,0 +1,210 @@ +package documentdb + +// 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 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" +) + +// DatabaseAccountKind enumerates the values for database account kind. +type DatabaseAccountKind string + +const ( + // GlobalDocumentDB specifies the global document db state for database + // account kind. + GlobalDocumentDB DatabaseAccountKind = "GlobalDocumentDB" + // MongoDB specifies the mongo db state for database account kind. + MongoDB DatabaseAccountKind = "MongoDB" + // Parse specifies the parse state for database account kind. + Parse DatabaseAccountKind = "Parse" +) + +// DatabaseAccountOfferType enumerates the values for database account offer +// type. +type DatabaseAccountOfferType string + +const ( + // Standard specifies the standard state for database account offer type. + Standard DatabaseAccountOfferType = "Standard" +) + +// DefaultConsistencyLevel enumerates the values for default consistency level. +type DefaultConsistencyLevel string + +const ( + // BoundedStaleness specifies the bounded staleness state for default + // consistency level. + BoundedStaleness DefaultConsistencyLevel = "BoundedStaleness" + // Eventual specifies the eventual state for default consistency level. + Eventual DefaultConsistencyLevel = "Eventual" + // Session specifies the session state for default consistency level. + Session DefaultConsistencyLevel = "Session" + // Strong specifies the strong state for default consistency level. + Strong DefaultConsistencyLevel = "Strong" +) + +// KeyKind enumerates the values for key kind. +type KeyKind string + +const ( + // Primary specifies the primary state for key kind. + Primary KeyKind = "primary" + // PrimaryReadonly specifies the primary readonly state for key kind. + PrimaryReadonly KeyKind = "primaryReadonly" + // Secondary specifies the secondary state for key kind. + Secondary KeyKind = "secondary" + // SecondaryReadonly specifies the secondary readonly state for key kind. + SecondaryReadonly KeyKind = "secondaryReadonly" +) + +// ConsistencyPolicy is the consistency policy for the DocumentDB database +// account. +type ConsistencyPolicy struct { + DefaultConsistencyLevel DefaultConsistencyLevel `json:"defaultConsistencyLevel,omitempty"` + MaxStalenessPrefix *int64 `json:"maxStalenessPrefix,omitempty"` + MaxIntervalInSeconds *int32 `json:"maxIntervalInSeconds,omitempty"` +} + +// DatabaseAccount is a DocumentDB database account. +type DatabaseAccount struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Kind DatabaseAccountKind `json:"kind,omitempty"` + *DatabaseAccountProperties `json:"properties,omitempty"` +} + +// DatabaseAccountConnectionString is connection string for the DocumentDB +// account +type DatabaseAccountConnectionString struct { + ConnectionString *string `json:"connectionString,omitempty"` + Description *string `json:"description,omitempty"` +} + +// DatabaseAccountCreateUpdateParameters is parameters to create and update +// DocumentDB database accounts. +type DatabaseAccountCreateUpdateParameters struct { + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Kind DatabaseAccountKind `json:"kind,omitempty"` + *DatabaseAccountCreateUpdateProperties `json:"properties,omitempty"` +} + +// DatabaseAccountCreateUpdateProperties is properties to create and update +// Azure DocumentDB database accounts. +type DatabaseAccountCreateUpdateProperties struct { + ConsistencyPolicy *ConsistencyPolicy `json:"consistencyPolicy,omitempty"` + Locations *[]Location `json:"locations,omitempty"` + DatabaseAccountOfferType *string `json:"databaseAccountOfferType,omitempty"` + IPRangeFilter *string `json:"ipRangeFilter,omitempty"` +} + +// DatabaseAccountListConnectionStringsResult is the connection strings for the +// given database account. +type DatabaseAccountListConnectionStringsResult struct { + autorest.Response `json:"-"` + ConnectionStrings *[]DatabaseAccountConnectionString `json:"connectionStrings,omitempty"` +} + +// DatabaseAccountListKeysResult is the access keys for the given database +// account. +type DatabaseAccountListKeysResult struct { + autorest.Response `json:"-"` + PrimaryMasterKey *string `json:"primaryMasterKey,omitempty"` + SecondaryMasterKey *string `json:"secondaryMasterKey,omitempty"` + *DatabaseAccountListReadOnlyKeysResult `json:"properties,omitempty"` +} + +// DatabaseAccountListReadOnlyKeysResult is the read-only access keys for the +// given database account. +type DatabaseAccountListReadOnlyKeysResult struct { + autorest.Response `json:"-"` + PrimaryReadonlyMasterKey *string `json:"primaryReadonlyMasterKey,omitempty"` + SecondaryReadonlyMasterKey *string `json:"secondaryReadonlyMasterKey,omitempty"` +} + +// DatabaseAccountPatchParameters is parameters for patching Azure DocumentDB +// database account properties. +type DatabaseAccountPatchParameters struct { + Tags *map[string]*string `json:"tags,omitempty"` +} + +// DatabaseAccountProperties is properties for the database account. +type DatabaseAccountProperties struct { + ProvisioningState *string `json:"provisioningState,omitempty"` + DocumentEndpoint *string `json:"documentEndpoint,omitempty"` + DatabaseAccountOfferType DatabaseAccountOfferType `json:"databaseAccountOfferType,omitempty"` + IPRangeFilter *string `json:"ipRangeFilter,omitempty"` + ConsistencyPolicy *ConsistencyPolicy `json:"consistencyPolicy,omitempty"` + WriteLocations *[]Location `json:"writeLocations,omitempty"` + ReadLocations *[]Location `json:"readLocations,omitempty"` + FailoverPolicies *[]FailoverPolicy `json:"failoverPolicies,omitempty"` +} + +// DatabaseAccountRegenerateKeyParameters is parameters to regenerate the keys +// within the database account. +type DatabaseAccountRegenerateKeyParameters struct { + KeyKind KeyKind `json:"keyKind,omitempty"` +} + +// DatabaseAccountsListResult is the List operation response, that contains the +// database accounts and their properties. +type DatabaseAccountsListResult struct { + autorest.Response `json:"-"` + Value *[]DatabaseAccount `json:"value,omitempty"` +} + +// FailoverPolicies is the list of new failover policies for the failover +// priority change. +type FailoverPolicies struct { + FailoverPolicies *[]FailoverPolicy `json:"failoverPolicies,omitempty"` +} + +// FailoverPolicy is the failover policy for a given region of a database +// account. +type FailoverPolicy struct { + ID *string `json:"id,omitempty"` + LocationName *string `json:"locationName,omitempty"` + FailoverPriority *int32 `json:"failoverPriority,omitempty"` +} + +// Location is a region in which the Azure DocumentDB database account is +// deployed. +type Location struct { + ID *string `json:"id,omitempty"` + LocationName *string `json:"locationName,omitempty"` + DocumentEndpoint *string `json:"documentEndpoint,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + FailoverPriority *int32 `json:"failoverPriority,omitempty"` +} + +// Resource is a database account resource. +type Resource struct { + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/documentdb/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/documentdb/version.go new file mode 100755 index 000000000000..dbbd4d7b1f9a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/documentdb/version.go @@ -0,0 +1,29 @@ +package documentdb + +// 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 1.0.1.0 +// 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/v10.0.2-beta arm-documentdb/2015-04-08" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return "v10.0.2-beta" +} diff --git a/vendor/vendor.json b/vendor/vendor.json index c2a730060651..683bf78e9876 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -42,6 +42,14 @@ "version": "v10.0.2-beta", "versionExact": "v10.0.2-beta" }, + { + "checksumSHA1": "wQBiO1nFX8II54iaQW2vJ7iBcuI=", + "path": "github.com/Azure/azure-sdk-for-go/arm/documentdb", + "revision": "5841475edc7c8725d79885d635aa8956f97fdf0e", + "revisionTime": "2017-05-10T22:14:13Z", + "version": "=v10.0.2-beta", + "versionExact": "v10.0.2-beta" + }, { "checksumSHA1": "eautqQaMqPwrTLVl81qpTSVtxI8=", "path": "github.com/Azure/azure-sdk-for-go/arm/eventhub", diff --git a/website/azurerm.erb b/website/azurerm.erb index 95c5b39791cf..9b281a0f29e1 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -21,7 +21,7 @@ > azurerm_resource_group - + > azurerm_public_ip @@ -67,6 +67,17 @@ + > + CosmosDB (DocumentDB) Resources + + + > DNS Resources