diff --git a/azurerm/internal/services/compute/parse/virtual_machine.go b/azurerm/internal/services/compute/parse/virtual_machine.go new file mode 100644 index 000000000000..5781c72c596d --- /dev/null +++ b/azurerm/internal/services/compute/parse/virtual_machine.go @@ -0,0 +1,33 @@ +package parse + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" +) + +type VirtualMachineId struct { + ResourceGroup string + Name string +} + +func VirtualMachineID(input string) (*VirtualMachineId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, fmt.Errorf("[ERROR] Unable to parse VM ID %q: %+v", input, err) + } + + vm := VirtualMachineId{ + ResourceGroup: id.ResourceGroup, + } + + if vm.Name, err = id.PopSegment("virtualMachines"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &vm, nil +} diff --git a/azurerm/internal/services/compute/parse/virtual_machine_test.go b/azurerm/internal/services/compute/parse/virtual_machine_test.go new file mode 100644 index 000000000000..806e3da3e2a3 --- /dev/null +++ b/azurerm/internal/services/compute/parse/virtual_machine_test.go @@ -0,0 +1,70 @@ +package parse + +import "testing" + +func TestVirtualMachineID(t *testing.T) { + var testData = []struct { + Name string + Input string + Expected *VirtualMachineId + }{ + { + Name: "Empty", + Input: "", + Expected: nil, + }, + { + Name: "No Resource Groups Segment", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000", + Expected: nil, + }, + { + Name: "No Resource Groups Value", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/", + Expected: nil, + }, + { + Name: "Resource Group ID", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/foo/", + Expected: nil, + }, + { + Name: "Missing Stores Value", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Compute/virtualMachines/", + Expected: nil, + }, + { + Name: "App Configuration ID", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Compute/virtualMachines/vm1", + Expected: &VirtualMachineId{ + Name: "vm1", + ResourceGroup: "resGroup1", + }, + }, + { + Name: "Wrong Casing", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Compute/VirtualMachines/vm1", + Expected: nil, + }, + } + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Name) + + actual, err := VirtualMachineID(v.Input) + if err != nil { + if v.Expected == nil { + continue + } + + t.Fatalf("Expected a value but got an error: %s", err) + } + + if actual.Name != v.Expected.Name { + t.Fatalf("Expected %q but got %q for Name", v.Expected.Name, actual.Name) + } + + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for Resource Group", v.Expected.ResourceGroup, actual.ResourceGroup) + } + } +} diff --git a/azurerm/internal/services/mssql/client/client.go b/azurerm/internal/services/mssql/client/client.go index 9f504ef8db51..fe5cfb274661 100644 --- a/azurerm/internal/services/mssql/client/client.go +++ b/azurerm/internal/services/mssql/client/client.go @@ -2,6 +2,7 @@ package client import ( "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql" + "github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/common" ) @@ -12,6 +13,7 @@ type Client struct { ServersClient *sql.ServersClient ServerSecurityAlertPoliciesClient *sql.ServerSecurityAlertPoliciesClient ServerVulnerabilityAssessmentsClient *sql.ServerVulnerabilityAssessmentsClient + VirtualMachinesClient *sqlvirtualmachine.SQLVirtualMachinesClient } func NewClient(o *common.ClientOptions) *Client { @@ -33,6 +35,9 @@ func NewClient(o *common.ClientOptions) *Client { ServerVulnerabilityAssessmentsClient := sql.NewServerVulnerabilityAssessmentsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&ServerVulnerabilityAssessmentsClient.Client, o.ResourceManagerAuthorizer) + SQLVirtualMachinesClient := sqlvirtualmachine.NewSQLVirtualMachinesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&SQLVirtualMachinesClient.Client, o.ResourceManagerAuthorizer) + return &Client{ DatabasesClient: &DatabasesClient, ElasticPoolsClient: &ElasticPoolsClient, @@ -40,5 +45,6 @@ func NewClient(o *common.ClientOptions) *Client { ServersClient: &ServersClient, ServerSecurityAlertPoliciesClient: &ServerSecurityAlertPoliciesClient, ServerVulnerabilityAssessmentsClient: &ServerVulnerabilityAssessmentsClient, + VirtualMachinesClient: &SQLVirtualMachinesClient, } } diff --git a/azurerm/internal/services/mssql/parse/mssql.go b/azurerm/internal/services/mssql/parse/mssql.go index c30862557d7b..70e8e20c17fa 100644 --- a/azurerm/internal/services/mssql/parse/mssql.go +++ b/azurerm/internal/services/mssql/parse/mssql.go @@ -93,3 +93,29 @@ func MSSqlElasticPoolID(input string) (*MsSqlElasticPoolId, error) { return &elasticPool, nil } + +type MssqlVmId struct { + ResourceGroup string + Name string +} + +func MssqlVmID(input string) (*MssqlVmId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, fmt.Errorf("[ERROR] Unable to parse Microsoft Sql VM ID %q: %+v", input, err) + } + + sqlvm := MssqlVmId{ + ResourceGroup: id.ResourceGroup, + } + + if sqlvm.Name, err = id.PopSegment("sqlVirtualMachines"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &sqlvm, nil +} diff --git a/azurerm/internal/services/mssql/parse/mssql_test.go b/azurerm/internal/services/mssql/parse/mssql_test.go index 4e304333f26f..2dd56719b3a3 100644 --- a/azurerm/internal/services/mssql/parse/mssql_test.go +++ b/azurerm/internal/services/mssql/parse/mssql_test.go @@ -154,3 +154,71 @@ func TestMsSqlServerID(t *testing.T) { } } } + +func TestMsSqlVmID(t *testing.T) { + testData := []struct { + Name string + Input string + Expected *MssqlVmId + }{ + { + Name: "Empty", + Input: "", + Expected: nil, + }, + { + Name: "No Resource Groups Segment", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000", + Expected: nil, + }, + { + Name: "No Resource Groups Value", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/", + Expected: nil, + }, + { + Name: "Resource Group ID", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/foo/", + Expected: nil, + }, + { + Name: "Missing Mssql VM Value", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/", + Expected: nil, + }, + { + Name: "Mssql VM ID", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/mssqlvm1", + Expected: &MssqlVmId{ + Name: "mssqlvm1", + ResourceGroup: "resGroup1", + }, + }, + { + Name: "Wrong Casing", + Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.SqlVirtualMachine/SqlVirtualMachines/mssqlvm1", + Expected: nil, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Name) + + actual, err := MssqlVmID(v.Input) + if err != nil { + if v.Expected == nil { + continue + } + + t.Fatalf("Expected a value but got an error: %s", err) + } + + if actual.Name != v.Expected.Name { + t.Fatalf("Expected %q but got %q for Name", v.Expected.Name, actual.Name) + } + + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for Resource Group", v.Expected.ResourceGroup, actual.ResourceGroup) + } + } +} diff --git a/azurerm/internal/services/mssql/registration.go b/azurerm/internal/services/mssql/registration.go index 9b14b0f795bc..5971b5482d30 100644 --- a/azurerm/internal/services/mssql/registration.go +++ b/azurerm/internal/services/mssql/registration.go @@ -34,5 +34,6 @@ func (r Registration) SupportedResources() map[string]*schema.Resource { "azurerm_mssql_elasticpool": resourceArmMsSqlElasticPool(), "azurerm_mssql_server_security_alert_policy": resourceArmMssqlServerSecurityAlertPolicy(), "azurerm_mssql_server_vulnerability_assessment": resourceArmMssqlServerVulnerabilityAssessment(), + "azurerm_mssql_virtual_machine": resourceArmMsSqlVirtualMachine(), } } diff --git a/azurerm/internal/services/mssql/resource_arm_mssql_virtual_machine.go b/azurerm/internal/services/mssql/resource_arm_mssql_virtual_machine.go new file mode 100644 index 000000000000..85771b252bec --- /dev/null +++ b/azurerm/internal/services/mssql/resource_arm_mssql_virtual_machine.go @@ -0,0 +1,422 @@ +package mssql + +import ( + "fmt" + "log" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine" + "github.com/hashicorp/go-azure-helpers/response" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/compute" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mssql/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mssql/validate" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags" + azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmMsSqlVirtualMachine() *schema.Resource { + return &schema.Resource{ + Create: resourceArmMsSqlVirtualMachineCreateUpdate, + Read: resourceArmMsSqlVirtualMachineRead, + Update: resourceArmMsSqlVirtualMachineCreateUpdate, + Delete: resourceArmMsSqlVirtualMachineDelete, + + Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error { + _, err := parse.MssqlVmID(id) + return err + }), + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(60 * time.Minute), + Read: schema.DefaultTimeout(5 * time.Minute), + Update: schema.DefaultTimeout(60 * time.Minute), + Delete: schema.DefaultTimeout(60 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "virtual_machine_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validate.VMID, + }, + + "sql_license_type": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{ + string(sqlvirtualmachine.PAYG), + string(sqlvirtualmachine.AHUB), + }, false), + }, + + "auto_patching": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "day_of_week": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + string(sqlvirtualmachine.Monday), + string(sqlvirtualmachine.Tuesday), + string(sqlvirtualmachine.Wednesday), + string(sqlvirtualmachine.Thursday), + string(sqlvirtualmachine.Friday), + string(sqlvirtualmachine.Saturday), + string(sqlvirtualmachine.Sunday), + }, false), + }, + + "maintenance_window_duration_in_minutes": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(30, 180), + }, + + "maintenance_window_starting_hour": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(0, 23), + }, + }, + }, + }, + + "key_vault_credential": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringIsNotEmpty, + //api will add updated credential name, and return "sqlvmName:name1,sqlvmName:name2" + DiffSuppressFunc: mssqlVMCredentialNameDiffSuppressFunc, + }, + + "key_vault_url": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Sensitive: true, + ValidateFunc: validation.IsURLWithHTTPS, + }, + + "service_principal_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Sensitive: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "service_principal_secret": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Sensitive: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + }, + }, + }, + + "r_services_enabled": { + Type: schema.TypeBool, + Optional: true, + }, + + "sql_connectivity_port": { + Type: schema.TypeInt, + Optional: true, + Default: 1433, + ValidateFunc: validation.IntBetween(1024, 65535), + }, + + "sql_connectivity_type": { + Type: schema.TypeString, + Optional: true, + Default: string(sqlvirtualmachine.PRIVATE), + ValidateFunc: validation.StringInSlice([]string{ + string(sqlvirtualmachine.LOCAL), + string(sqlvirtualmachine.PRIVATE), + string(sqlvirtualmachine.PUBLIC), + }, false), + }, + + "sql_connectivity_update_password": { + Type: schema.TypeString, + Optional: true, + Sensitive: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "sql_connectivity_update_username": { + Type: schema.TypeString, + Optional: true, + Sensitive: true, + ValidateFunc: validate.MsSqlVMLoginUserName, + }, + + "tags": tags.Schema(), + }, + } +} + +func resourceArmMsSqlVirtualMachineCreateUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).MSSQL.VirtualMachinesClient + vmclient := meta.(*clients.Client).Compute.VMClient + ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) + defer cancel() + + vmId := d.Get("virtual_machine_id").(string) + id, err := compute.ParseVirtualMachineID(vmId) + if err != nil { + return err + } + + if features.ShouldResourcesBeImported() && d.IsNewResource() { + existing, err := client.Get(ctx, id.ResourceGroup, id.Name, "*") + if err != nil { + if !utils.ResponseWasNotFound(existing.Response) { + return fmt.Errorf("Failure in checking for present of existing Sql Virtual Machine (Sql Virtual Machine Name %q / Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + } + } + if existing.ID != nil && *existing.ID != "" { + return tf.ImportAsExistsError("azurerm_mssql_virtual_machine", *existing.ID) + } + } + + // get location from vm + respvm, err := vmclient.Get(ctx, id.ResourceGroup, id.Name, "") + if err != nil { + return fmt.Errorf("Failure in making Read request on Azure Virtual Machine %s: %+v", id.Name, err) + } + + if *respvm.Location == "" { + return fmt.Errorf("Location is empty from making Read request on Azure Virtual Machine %s: %+v", id.Name, err) + } + + parameters := sqlvirtualmachine.SQLVirtualMachine{ + Location: utils.String(*respvm.Location), + Properties: &sqlvirtualmachine.Properties{ + VirtualMachineResourceID: utils.String(d.Get("virtual_machine_id").(string)), + SQLServerLicenseType: sqlvirtualmachine.SQLServerLicenseType(d.Get("sql_license_type").(string)), + SQLManagement: sqlvirtualmachine.Full, + AutoPatchingSettings: expandArmSqlVirtualMachineAutoPatchingSettings(d.Get("auto_patching").([]interface{})), + KeyVaultCredentialSettings: expandArmSqlVirtualMachineKeyVaultCredential(d.Get("key_vault_credential").([]interface{})), + ServerConfigurationsManagementSettings: &sqlvirtualmachine.ServerConfigurationsManagementSettings{ + AdditionalFeaturesServerConfigurations: &sqlvirtualmachine.AdditionalFeaturesServerConfigurations{ + IsRServicesEnabled: utils.Bool(d.Get("r_services_enabled").(bool)), + }, + SQLConnectivityUpdateSettings: &sqlvirtualmachine.SQLConnectivityUpdateSettings{ + Port: utils.Int32(int32(d.Get("sql_connectivity_port").(int))), + ConnectivityType: sqlvirtualmachine.ConnectivityType(d.Get("sql_connectivity_type").(string)), + SQLAuthUpdatePassword: utils.String(d.Get("sql_connectivity_update_password").(string)), + SQLAuthUpdateUserName: utils.String(d.Get("sql_connectivity_update_username").(string)), + }, + }, + }, + Tags: tags.Expand(d.Get("tags").(map[string]interface{})), + } + + future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.Name, parameters) + if err != nil { + return fmt.Errorf("Failure in creating Sql Virtual Machine (Sql Virtual Machine Name %q / Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + } + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + return fmt.Errorf("Failure in waiting for creation of Sql Virtual Machine (Sql Virtual Machine Name %q / Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + } + + resp, err := client.Get(ctx, id.ResourceGroup, id.Name, "*") + if err != nil { + return fmt.Errorf("Failure in retrieving Sql Virtual Machine (Sql Virtual Machine Name %q / Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + } + if resp.ID == nil { + return fmt.Errorf("Cannot read Sql Virtual Machine (Sql Virtual Machine Name %q / Resource Group %q) ID", id.Name, id.ResourceGroup) + } + d.SetId(*resp.ID) + + return resourceArmMsSqlVirtualMachineRead(d, meta) +} + +func resourceArmMsSqlVirtualMachineRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).MSSQL.VirtualMachinesClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.MssqlVmID(d.Id()) + if err != nil { + return err + } + + resp, err := client.Get(ctx, id.ResourceGroup, id.Name, "*") + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[INFO] Sql Virtual Machine %q does not exist - removing from state", d.Id()) + d.SetId("") + return nil + } + return fmt.Errorf("Failure in reading Sql Virtual Machine (Sql Virtual Machine Name %q / Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + } + + if props := resp.Properties; props != nil { + d.Set("virtual_machine_id", props.VirtualMachineResourceID) + d.Set("sql_license_type", string(props.SQLServerLicenseType)) + if err := d.Set("auto_patching", flattenArmSqlVirtualMachineAutoPatching(props.AutoPatchingSettings)); err != nil { + return fmt.Errorf("Failure in setting `auto_patching`: %+v", err) + } + + if err := d.Set("key_vault_credential", flattenArmSqlVirtualMachineKeyVaultCredential(props.KeyVaultCredentialSettings, d)); err != nil { + return fmt.Errorf("Failure in setting `key_vault_credential`: %+v", err) + } + + if mgmtSettings := props.ServerConfigurationsManagementSettings; mgmtSettings != nil { + if cfgs := mgmtSettings.AdditionalFeaturesServerConfigurations; cfgs != nil { + d.Set("r_services_enabled", mgmtSettings.AdditionalFeaturesServerConfigurations.IsRServicesEnabled) + } + if scus := mgmtSettings.SQLConnectivityUpdateSettings; scus != nil { + d.Set("sql_connectivity_port", mgmtSettings.SQLConnectivityUpdateSettings.Port) + d.Set("sql_connectivity_type", mgmtSettings.SQLConnectivityUpdateSettings.ConnectivityType) + } + } + } + return tags.FlattenAndSet(d, resp.Tags) +} + +func resourceArmMsSqlVirtualMachineDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).MSSQL.VirtualMachinesClient + ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.MssqlVmID(d.Id()) + if err != nil { + return err + } + + future, err := client.Delete(ctx, id.ResourceGroup, id.Name) + if err != nil { + return fmt.Errorf("Failure in deleting Sql Virtual Machine (Sql Virtual Machine Name %q / Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + } + + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + if !response.WasNotFound(future.Response()) { + return fmt.Errorf("Failure in waiting for deleting Sql Virtual Machine (Sql Virtual Machine Name %q / Resource Group %q): %+v", id.Name, id.ResourceGroup, err) + } + } + + return nil +} + +func expandArmSqlVirtualMachineAutoPatchingSettings(input []interface{}) *sqlvirtualmachine.AutoPatchingSettings { + if len(input) == 0 { + return nil + } + autoPatchingSetting := input[0].(map[string]interface{}) + + return &sqlvirtualmachine.AutoPatchingSettings{ + Enable: utils.Bool(true), + MaintenanceWindowDuration: utils.Int32(int32(autoPatchingSetting["maintenance_window_duration_in_minutes"].(int))), + MaintenanceWindowStartingHour: utils.Int32(int32(autoPatchingSetting["maintenance_window_starting_hour"].(int))), + DayOfWeek: sqlvirtualmachine.DayOfWeek(autoPatchingSetting["day_of_week"].(string)), + } +} + +func flattenArmSqlVirtualMachineAutoPatching(autoPatching *sqlvirtualmachine.AutoPatchingSettings) []interface{} { + if autoPatching == nil || !*autoPatching.Enable { + return []interface{}{} + } + + var startHour int32 + if autoPatching.MaintenanceWindowStartingHour != nil { + startHour = *autoPatching.MaintenanceWindowStartingHour + } + + var duration int32 + if autoPatching.MaintenanceWindowDuration != nil { + duration = *autoPatching.MaintenanceWindowDuration + } + + return []interface{}{ + map[string]interface{}{ + "day_of_week": string(autoPatching.DayOfWeek), + "maintenance_window_starting_hour": startHour, + "maintenance_window_duration_in_minutes": duration, + }, + } +} + +func expandArmSqlVirtualMachineKeyVaultCredential(input []interface{}) *sqlvirtualmachine.KeyVaultCredentialSettings { + if len(input) == 0 { + return nil + } + keyVaultCredentialSetting := input[0].(map[string]interface{}) + + return &sqlvirtualmachine.KeyVaultCredentialSettings{ + Enable: utils.Bool(true), + CredentialName: utils.String(keyVaultCredentialSetting["name"].(string)), + AzureKeyVaultURL: utils.String(keyVaultCredentialSetting["key_vault_url"].(string)), + ServicePrincipalName: utils.String(keyVaultCredentialSetting["service_principal_name"].(string)), + ServicePrincipalSecret: utils.String(keyVaultCredentialSetting["service_principal_secret"].(string)), + } +} + +func flattenArmSqlVirtualMachineKeyVaultCredential(keyVault *sqlvirtualmachine.KeyVaultCredentialSettings, d *schema.ResourceData) []interface{} { + if keyVault == nil || !*keyVault.Enable { + return []interface{}{} + } + + name := "" + if keyVault.CredentialName != nil { + name = *keyVault.CredentialName + } + + keyVaultUrl := "" + if v, ok := d.GetOk("key_vault_credential.0.key_vault_url"); ok { + keyVaultUrl = v.(string) + } + + servicePrincipalName := "" + if v, ok := d.GetOk("key_vault_credential.0.service_principal_name"); ok { + servicePrincipalName = v.(string) + } + + servicePrincipalSecret := "" + if v, ok := d.GetOk("key_vault_credential.0.service_principal_secret"); ok { + servicePrincipalSecret = v.(string) + } + + return []interface{}{ + map[string]interface{}{ + "name": name, + "key_vault_url": keyVaultUrl, + "service_principal_name": servicePrincipalName, + "service_principal_secret": servicePrincipalSecret, + }, + } +} + +func mssqlVMCredentialNameDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool { + oldNamelist := strings.Split(old, ",") + for _, n := range oldNamelist { + cur := strings.Split(n, ":") + if len(cur) > 1 && cur[1] == new { + return true + } + } + return false +} diff --git a/azurerm/internal/services/mssql/tests/resource_arm_mssql_virtual_machine_test.go b/azurerm/internal/services/mssql/tests/resource_arm_mssql_virtual_machine_test.go new file mode 100644 index 000000000000..8f743b83c212 --- /dev/null +++ b/azurerm/internal/services/mssql/tests/resource_arm_mssql_virtual_machine_test.go @@ -0,0 +1,583 @@ +package tests + +import ( + "fmt" + "regexp" + "testing" + + "github.com/hashicorp/go-uuid" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mssql/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func TestAccAzureRMMsSqlVirtualMachine_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mssql_virtual_machine", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMsSqlVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMsSqlVirtualMachine_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlVirtualMachineExists(data.ResourceName), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMMsSqlVirtualMachine_requiresImport(t *testing.T) { + if !features.ShouldResourcesBeImported() { + t.Skip("Skipping since resources aren't required to be imported") + return + } + + data := acceptance.BuildTestData(t, "azurerm_mssql_virtual_machine", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMsSqlVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMsSqlVirtualMachine_basic(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlVirtualMachineExists(data.ResourceName), + ), + }, + data.RequiresImportErrorStep(testAccAzureRMMsSqlVirtualMachine_requiresImport), + }, + }) +} + +func TestAccAzureRMMsSqlVirtualMachine_complete(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mssql_virtual_machine", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMsSqlVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMsSqlVirtualMachine_complete(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlVirtualMachineExists(data.ResourceName), + resource.TestCheckResourceAttr(data.ResourceName, "r_services_enabled", "true"), + resource.TestCheckResourceAttr(data.ResourceName, "sql_connectivity_type", "PRIVATE"), + resource.TestCheckResourceAttr(data.ResourceName, "sql_connectivity_port", "1433"), + ), + }, + data.ImportStep("sql_connectivity_update_password", "sql_connectivity_update_username"), + { + Config: testAccAzureRMMsSqlVirtualMachine_update(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlVirtualMachineExists(data.ResourceName), + resource.TestCheckResourceAttr(data.ResourceName, "r_services_enabled", "false"), + resource.TestCheckResourceAttr(data.ResourceName, "sql_connectivity_type", "PUBLIC"), + resource.TestCheckResourceAttr(data.ResourceName, "sql_connectivity_port", "1533"), + ), + }, + data.ImportStep("sql_connectivity_update_password", "sql_connectivity_update_username"), + }, + }) +} + +func TestAccAzureRMMsSqlVirtualMachine_updateAutoPatching(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mssql_virtual_machine", "test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMsSqlVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMsSqlVirtualMachine_withAutoPatching(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlVirtualMachineExists(data.ResourceName), + resource.TestCheckResourceAttr(data.ResourceName, "auto_patching.0.day_of_week", "Sunday"), + resource.TestCheckResourceAttr(data.ResourceName, "auto_patching.0.maintenance_window_duration_in_minutes", "60"), + resource.TestCheckResourceAttr(data.ResourceName, "auto_patching.0.maintenance_window_starting_hour", "2"), + ), + }, + data.ImportStep(), + { + Config: testAccAzureRMMsSqlVirtualMachine_withAutoPatchingUpdated(data), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlVirtualMachineExists(data.ResourceName), + resource.TestCheckResourceAttr(data.ResourceName, "auto_patching.0.day_of_week", "Monday"), + resource.TestCheckResourceAttr(data.ResourceName, "auto_patching.0.maintenance_window_duration_in_minutes", "90"), + resource.TestCheckResourceAttr(data.ResourceName, "auto_patching.0.maintenance_window_starting_hour", "4"), + ), + }, + data.ImportStep(), + }, + }) +} + +func TestAccAzureRMMsSqlVirtualMachine_updateKeyVault(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_mssql_virtual_machine", "test") + value, err := uuid.GenerateUUID() + if err != nil { + t.Fatal(err) + } + + resource.Test(t, resource.TestCase{ + PreCheck: func() { acceptance.PreCheck(t) }, + Providers: acceptance.SupportedProviders, + CheckDestroy: testCheckAzureRMMsSqlVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMMsSqlVirtualMachine_withKeyVault(data, value), + Check: resource.ComposeTestCheckFunc( + resource.TestMatchResourceAttr(data.ResourceName, "key_vault_credential.0.name", regexp.MustCompile("/*:acctestkv")), + ), + }, + data.ImportStep("key_vault_credential.0.key_vault_url", "key_vault_credential.0.service_principal_name", "key_vault_credential.0.service_principal_secret"), + + { + Config: testAccAzureRMMsSqlVirtualMachine_withKeyVaultUpdated(data, value), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMMsSqlVirtualMachineExists(data.ResourceName), + resource.TestMatchResourceAttr(data.ResourceName, "key_vault_credential.0.name", regexp.MustCompile("/*:acctestkv2")), + ), + }, + data.ImportStep("key_vault_credential.0.key_vault_url", "key_vault_credential.0.service_principal_name", "key_vault_credential.0.service_principal_secret"), + }, + }) +} + +func testCheckAzureRMMsSqlVirtualMachineExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Sql Virtual Machine not found: %s", resourceName) + } + + id, err := parse.MssqlVmID(rs.Primary.ID) + if err != nil { + return err + } + + client := acceptance.AzureProvider.Meta().(*clients.Client).MSSQL.VirtualMachinesClient + ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext + + if resp, err := client.Get(ctx, id.ResourceGroup, id.Name, ""); err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: Sql Virtual Machine (Sql Virtual Machine Name %q / Resource Group %q) does not exist", id.Name, id.ResourceGroup) + } + return fmt.Errorf("Bad: Get on VirtualMachinesClient: %+v", err) + } + + return nil + } +} + +func testCheckAzureRMMsSqlVirtualMachineDestroy(s *terraform.State) error { + client := acceptance.AzureProvider.Meta().(*clients.Client).MSSQL.VirtualMachinesClient + ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_mssql_virtual_machine" { + continue + } + + id, err := parse.MssqlVmID(rs.Primary.ID) + if err != nil { + return err + } + + if resp, err := client.Get(ctx, id.ResourceGroup, id.Name, ""); err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Bad: Get on VirtualMachinesClient: %+v", err) + } + } + + return nil + } + + return nil +} + +func testAccAzureRMVirtualMachine_template(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-mssql-%[1]d" + location = "%[2]s" +} + +resource "azurerm_virtual_network" "test" { + name = "acctest-VN-%[1]d" + address_space = ["10.0.0.0/16"] + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name +} + +resource "azurerm_subnet" "test" { + name = "acctest-SN-%[1]d" + resource_group_name = azurerm_resource_group.test.name + virtual_network_name = azurerm_virtual_network.test.name + address_prefix = "10.0.0.0/24" +} + +resource "azurerm_subnet_network_security_group_association" "test" { + subnet_id = azurerm_subnet.test.id + network_security_group_id = azurerm_network_security_group.test.id +} + +resource "azurerm_public_ip" "vm" { + name = "acctest-PIP-%[1]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + allocation_method = "Dynamic" +} + +resource "azurerm_network_security_group" "test" { + name = "acctest-NSG-%[1]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name +} + +resource "azurerm_network_security_rule" "RDPRule" { + name = "RDPRule" + resource_group_name = azurerm_resource_group.test.name + priority = 1000 + direction = "Inbound" + access = "Allow" + protocol = "Tcp" + source_port_range = "*" + destination_port_range = 3389 + source_address_prefix = "167.220.255.0/25" + destination_address_prefix = "*" + network_security_group_name = azurerm_network_security_group.test.name +} + +resource "azurerm_network_security_rule" "MSSQLRule" { + name = "MSSQLRule" + resource_group_name = azurerm_resource_group.test.name + priority = 1001 + direction = "Inbound" + access = "Allow" + protocol = "Tcp" + source_port_range = "*" + destination_port_range = 1433 + source_address_prefix = "167.220.255.0/25" + destination_address_prefix = "*" + network_security_group_name = azurerm_network_security_group.test.name +} + +resource "azurerm_network_interface" "test" { + name = "acctest-NIC-%[1]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" + public_ip_address_id = azurerm_public_ip.vm.id + } +} + +resource "azurerm_virtual_machine" "test" { + name = "acctest-VM-%[1]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + network_interface_ids = [azurerm_network_interface.test.id] + vm_size = "Standard_F2s" + + storage_image_reference { + publisher = "MicrosoftSQLServer" + offer = "SQL2017-WS2016" + sku = "SQLDEV" + version = "latest" + } + + storage_os_disk { + name = "acctvm-%[1]dOSDisk" + caching = "ReadOnly" + create_option = "FromImage" + managed_disk_type = "Premium_LRS" + } + + os_profile { + computer_name = "winhost01" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_windows_config { + timezone = "Pacific Standard Time" + provision_vm_agent = true + enable_automatic_upgrades = true + } +} +`, data.RandomInteger, data.Locations.Primary) +} + +func testAccAzureRMMsSqlVirtualMachine_basic(data acceptance.TestData) string { + vmconfig := testAccAzureRMVirtualMachine_template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_mssql_virtual_machine" "test" { + virtual_machine_id = azurerm_virtual_machine.test.id + sql_license_type = "PAYG" +} +`, vmconfig) +} + +func testAccAzureRMMsSqlVirtualMachine_requiresImport(data acceptance.TestData) string { + template := testAccAzureRMMsSqlVirtualMachine_basic(data) + return fmt.Sprintf(` +%s + +resource "azurerm_mssql_virtual_machine" "import" { + virtual_machine_id = azurerm_mssql_virtual_machine.test.virtual_machine_id + sql_license_type = azurerm_mssql_virtual_machine.test.sql_license_type +} +`, template) +} + +func testAccAzureRMMsSqlVirtualMachine_complete(data acceptance.TestData) string { + vmconfig := testAccAzureRMVirtualMachine_template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_mssql_virtual_machine" "test" { + virtual_machine_id = azurerm_virtual_machine.test.id + sql_license_type = "PAYG" + r_services_enabled = true + sql_connectivity_port = 1433 + sql_connectivity_type = "PRIVATE" + sql_connectivity_update_password = "Password1234!" + sql_connectivity_update_username = "sqllogin" +} +`, vmconfig) +} + +func testAccAzureRMMsSqlVirtualMachine_update(data acceptance.TestData) string { + vmconfig := testAccAzureRMVirtualMachine_template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_mssql_virtual_machine" "test" { + virtual_machine_id = azurerm_virtual_machine.test.id + sql_license_type = "PAYG" + r_services_enabled = false + sql_connectivity_port = 1533 + sql_connectivity_type = "PUBLIC" + sql_connectivity_update_password = "Password12344321!" + sql_connectivity_update_username = "sqlloginupdate" +} +`, vmconfig) +} + +func testAccAzureRMMsSqlVirtualMachine_withAutoPatching(data acceptance.TestData) string { + vmconfig := testAccAzureRMVirtualMachine_template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_mssql_virtual_machine" "test" { + virtual_machine_id = azurerm_virtual_machine.test.id + sql_license_type = "PAYG" + + auto_patching { + day_of_week = "Sunday" + maintenance_window_duration_in_minutes = 60 + maintenance_window_starting_hour = 2 + } +} +`, vmconfig) +} + +func testAccAzureRMMsSqlVirtualMachine_withAutoPatchingUpdated(data acceptance.TestData) string { + vmconfig := testAccAzureRMVirtualMachine_template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_mssql_virtual_machine" "test" { + virtual_machine_id = azurerm_virtual_machine.test.id + sql_license_type = "PAYG" + + auto_patching { + day_of_week = "Monday" + maintenance_window_duration_in_minutes = 90 + maintenance_window_starting_hour = 4 + } +} +`, vmconfig) +} + +func testAccAzureRMMsSqlVirtualMachine_withKeyVault(data acceptance.TestData, value string) string { + vmconfig := testAccAzureRMVirtualMachine_template(data) + return fmt.Sprintf(` +%s + +data "azurerm_client_config" "current" {} + +resource "azurerm_key_vault" "test" { + name = "acckv-%[2]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + tenant_id = data.azurerm_client_config.current.tenant_id + + sku_name = "premium" + + access_policy { + tenant_id = data.azurerm_client_config.current.tenant_id + object_id = data.azurerm_client_config.current.object_id + + key_permissions = [ + "create", + "delete", + "get", + "update", + ] + + secret_permissions = [ + "get", + "delete", + "set", + ] + } + + tags = { + environment = "Production" + } +} + +resource "azurerm_key_vault_key" "generated" { + name = "key-%[2]d" + key_vault_id = azurerm_key_vault.test.id + key_type = "RSA" + key_size = 2048 + + key_opts = [ + "decrypt", + "encrypt", + "sign", + "unwrapKey", + "verify", + "wrapKey", + ] +} + +resource "azuread_application" "test" { + name = "acctestspa%[2]d" +} + +resource "azuread_service_principal" "test" { + application_id = azuread_application.test.application_id +} + +resource "azuread_service_principal_password" "test" { + service_principal_id = azuread_service_principal.test.id + value = "%s" + end_date = "2021-01-01T01:02:03Z" +} + +resource "azurerm_mssql_virtual_machine" "test" { + virtual_machine_id = azurerm_virtual_machine.test.id + sql_license_type = "PAYG" + key_vault_credential { + name = "acctestkv" + key_vault_url = azurerm_key_vault_key.generated.id + service_principal_name = azuread_service_principal.test.display_name + service_principal_secret = azuread_service_principal_password.test.value + } +} +`, vmconfig, data.RandomInteger, value) +} + +func testAccAzureRMMsSqlVirtualMachine_withKeyVaultUpdated(data acceptance.TestData, value string) string { + vmconfig := testAccAzureRMVirtualMachine_template(data) + return fmt.Sprintf(` +%s + +data "azurerm_client_config" "current" {} + +resource "azurerm_key_vault" "test" { + name = "acckv-%[2]d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + tenant_id = data.azurerm_client_config.current.tenant_id + + sku_name = "premium" + + access_policy { + tenant_id = data.azurerm_client_config.current.tenant_id + object_id = data.azurerm_client_config.current.object_id + + key_permissions = [ + "create", + "delete", + "get", + "update", + ] + + secret_permissions = [ + "get", + "delete", + "set", + ] + } + + tags = { + environment = "Production" + } +} + +resource "azurerm_key_vault_key" "generated" { + name = "key-%[2]d" + key_vault_id = azurerm_key_vault.test.id + key_type = "RSA" + key_size = 2048 + + key_opts = [ + "decrypt", + "encrypt", + "sign", + "unwrapKey", + "verify", + "wrapKey", + ] +} + +resource "azuread_application" "test" { + name = "acctestspa%[2]d" +} + +resource "azuread_service_principal" "test" { + application_id = azuread_application.test.application_id +} + +resource "azuread_service_principal_password" "test" { + service_principal_id = azuread_service_principal.test.id + value = "%s" + end_date = "2021-01-01T01:02:03Z" +} + +resource "azurerm_mssql_virtual_machine" "test" { + virtual_machine_id = azurerm_virtual_machine.test.id + sql_license_type = "PAYG" + key_vault_credential { + name = "acctestkv2" + key_vault_url = azurerm_key_vault_key.generated.id + service_principal_name = azuread_service_principal.test.display_name + service_principal_secret = azuread_service_principal_password.test.value + } +} +`, vmconfig, data.RandomInteger, value) +} diff --git a/azurerm/internal/services/mssql/validate/mssql_virtual_machine.go b/azurerm/internal/services/mssql/validate/mssql_virtual_machine.go new file mode 100644 index 000000000000..67ac85d9249c --- /dev/null +++ b/azurerm/internal/services/mssql/validate/mssql_virtual_machine.go @@ -0,0 +1,36 @@ +package validate + +import ( + "fmt" + "regexp" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/compute" +) + +func VMID(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) + return + } + + if _, err := compute.ParseVirtualMachineID(v); err != nil { + errors = append(errors, fmt.Errorf("Can not parse %q as a virtual machine id: %v", k, err)) + } + + return warnings, errors +} + +func MsSqlVMLoginUserName(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) + return + } + + if !regexp.MustCompile(`^[^\\/\"\[\]:|<>+=;,?\* .]{2,128}$`).MatchString(v) { + errors = append(errors, fmt.Errorf("%v cannot contain special characters '\\/\"[]:|<>+=;,?* .'", k)) + } + + return warnings, errors +} diff --git a/azurerm/internal/services/mssql/validate/mssql_virtual_machine_test.go b/azurerm/internal/services/mssql/validate/mssql_virtual_machine_test.go new file mode 100644 index 000000000000..e0a90decdc08 --- /dev/null +++ b/azurerm/internal/services/mssql/validate/mssql_virtual_machine_test.go @@ -0,0 +1,26 @@ +package validate + +import "testing" + +func TestMsSqlVMLoginUserName(t *testing.T) { + testCases := []struct { + input string + shouldError bool + }{ + {"dfasdlk", false}, + {"sdfs@ ", false}, + {"dfsjsiajfiweangfvnjaksdflaklsdjdjskfamlkcsdflamkldfklafamsdklfmlaksjfdkadklsfmklamdklsfakldsflamkslfmlkeamkldmfkamfmdkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk", true}, + {"60", false}, + {"7.d", true}, + {"u i", true}, + {"a", true}, + } + + for _, test := range testCases { + _, es := MsSqlVMLoginUserName(test.input, "name") + + if test.shouldError && len(es) == 0 { + t.Fatalf("Expected validating name %q to fail", test.input) + } + } +} diff --git a/examples/mssql/mssqlvm/main.tf b/examples/mssql/mssqlvm/main.tf new file mode 100644 index 000000000000..a45ea97a6987 --- /dev/null +++ b/examples/mssql/mssqlvm/main.tf @@ -0,0 +1,125 @@ +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "example" { + name = "${var.prefix}-resources" + location = var.location +} + +resource "azurerm_virtual_network" "example" { + name = "${var.prefix}-VN" + address_space = ["10.0.0.0/16"] + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name +} + +resource "azurerm_subnet" "example" { + name = "${var.prefix}-SN" + resource_group_name = azurerm_resource_group.example.name + virtual_network_name = azurerm_virtual_network.example.name + address_prefix = "10.0.0.0/24" +} + +resource "azurerm_subnet_network_security_group_association" "example" { + subnet_id = azurerm_subnet.example.id + network_security_group_id = azurerm_network_security_group.example.id +} + +resource "azurerm_public_ip" "vm" { + name = "${var.prefix}-PIP" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + allocation_method = "Dynamic" +} + +resource "azurerm_network_security_group" "example" { + name = "${var.prefix}-NSG" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name +} + +resource "azurerm_network_security_rule" "RDPRule" { + name = "RDPRule" + resource_group_name = azurerm_resource_group.example.name + priority = 1000 + direction = "Inbound" + access = "Allow" + protocol = "Tcp" + source_port_range = "*" + destination_port_range = 3389 + source_address_prefix = "167.220.255.0/25" + destination_address_prefix = "*" + network_security_group_name = azurerm_network_security_group.example.name +} + +resource "azurerm_network_security_rule" "MSSQLRule" { + name = "MSSQLRule" + resource_group_name = azurerm_resource_group.example.name + priority = 1001 + direction = "Inbound" + access = "Allow" + protocol = "Tcp" + source_port_range = "*" + destination_port_range = 1433 + source_address_prefix = "167.220.255.0/25" + destination_address_prefix = "*" + network_security_group_name = azurerm_network_security_group.example.name +} + +resource "azurerm_network_interface" "example" { + name = "${var.prefix}-NIC" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + + ip_configuration { + name = "exampleconfiguration1" + subnet_id = azurerm_subnet.example.id + private_ip_address_allocation = "Dynamic" + public_ip_address_id = azurerm_public_ip.vm.id + } +} + +resource "azurerm_network_interface_security_group_association" "example" { + network_interface_id = azurerm_network_interface.example.id + network_security_group_id = azurerm_network_security_group.example.id +} + +resource "azurerm_virtual_machine" "example" { + name = "${var.prefix}-VM" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + network_interface_ids = [azurerm_network_interface.example.id] + vm_size = "Standard_DS14_v2" + + storage_image_reference { + publisher = "MicrosoftSQLServer" + offer = "SQL2017-WS2016" + sku = "SQLDEV" + version = "laexample" + } + + storage_os_disk { + name = "${var.prefix}-OSDisk" + caching = "ReadOnly" + create_option = "FromImage" + managed_disk_type = "Premium_LRS" + } + + os_profile { + computer_name = "winhost01" + admin_username = "exampleadmin" + admin_password = "Password1234!" + } + + os_profile_windows_config { + timezone = "Pacific Standard Time" + provision_vm_agent = true + enable_automatic_upgrades = true + } +} + +resource "azurerm_mssql_virtual_machine" "example" { + virtual_machine_id = azurerm_virtual_machine.example.id + sql_license_type = "PAYG" +} diff --git a/examples/mssql/mssqlvm/variables.tf b/examples/mssql/mssqlvm/variables.tf new file mode 100644 index 000000000000..3579de3cb72c --- /dev/null +++ b/examples/mssql/mssqlvm/variables.tf @@ -0,0 +1,7 @@ +variable "location" { + description = "The Azure location where all resources in this example should be created." +} + +variable "prefix" { + description = "The prefix used for all resources used by this NetApp Account" +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/availabilitygrouplisteners.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/availabilitygrouplisteners.go new file mode 100644 index 000000000000..9d21e50c2891 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/availabilitygrouplisteners.go @@ -0,0 +1,400 @@ +package sqlvirtualmachine + +// 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/tracing" + "net/http" +) + +// AvailabilityGroupListenersClient is the the SQL virtual machine management API provides a RESTful set of web APIs +// that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API +// enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group +// listener. +type AvailabilityGroupListenersClient struct { + BaseClient +} + +// NewAvailabilityGroupListenersClient creates an instance of the AvailabilityGroupListenersClient client. +func NewAvailabilityGroupListenersClient(subscriptionID string) AvailabilityGroupListenersClient { + return NewAvailabilityGroupListenersClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewAvailabilityGroupListenersClientWithBaseURI creates an instance of the AvailabilityGroupListenersClient client +// using a custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign +// clouds, Azure stack). +func NewAvailabilityGroupListenersClientWithBaseURI(baseURI string, subscriptionID string) AvailabilityGroupListenersClient { + return AvailabilityGroupListenersClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates an availability group listener. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +// SQLVirtualMachineGroupName - name of the SQL virtual machine group. +// availabilityGroupListenerName - name of the availability group listener. +// parameters - the availability group listener. +func (client AvailabilityGroupListenersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string, availabilityGroupListenerName string, parameters AvailabilityGroupListener) (result AvailabilityGroupListenersCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilityGroupListenersClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, SQLVirtualMachineGroupName, availabilityGroupListenerName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client AvailabilityGroupListenersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string, availabilityGroupListenerName string, parameters AvailabilityGroupListener) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "availabilityGroupListenerName": autorest.Encode("path", availabilityGroupListenerName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "sqlVirtualMachineGroupName": autorest.Encode("path", SQLVirtualMachineGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}/availabilityGroupListeners/{availabilityGroupListenerName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client AvailabilityGroupListenersClient) CreateOrUpdateSender(req *http.Request) (future AvailabilityGroupListenersCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client AvailabilityGroupListenersClient) CreateOrUpdateResponder(resp *http.Response) (result AvailabilityGroupListener, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an availability group listener. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +// SQLVirtualMachineGroupName - name of the SQL virtual machine group. +// availabilityGroupListenerName - name of the availability group listener. +func (client AvailabilityGroupListenersClient) Delete(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string, availabilityGroupListenerName string) (result AvailabilityGroupListenersDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilityGroupListenersClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, SQLVirtualMachineGroupName, availabilityGroupListenerName) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client AvailabilityGroupListenersClient) DeletePreparer(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string, availabilityGroupListenerName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "availabilityGroupListenerName": autorest.Encode("path", availabilityGroupListenerName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "sqlVirtualMachineGroupName": autorest.Encode("path", SQLVirtualMachineGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}/availabilityGroupListeners/{availabilityGroupListenerName}", 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 AvailabilityGroupListenersClient) DeleteSender(req *http.Request) (future AvailabilityGroupListenersDeleteFuture, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + 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 AvailabilityGroupListenersClient) 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 an availability group listener. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +// SQLVirtualMachineGroupName - name of the SQL virtual machine group. +// availabilityGroupListenerName - name of the availability group listener. +func (client AvailabilityGroupListenersClient) Get(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string, availabilityGroupListenerName string) (result AvailabilityGroupListener, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilityGroupListenersClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, SQLVirtualMachineGroupName, availabilityGroupListenerName) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client AvailabilityGroupListenersClient) GetPreparer(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string, availabilityGroupListenerName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "availabilityGroupListenerName": autorest.Encode("path", availabilityGroupListenerName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "sqlVirtualMachineGroupName": autorest.Encode("path", SQLVirtualMachineGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}/availabilityGroupListeners/{availabilityGroupListenerName}", 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 AvailabilityGroupListenersClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client AvailabilityGroupListenersClient) GetResponder(resp *http.Response) (result AvailabilityGroupListener, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByGroup lists all availability group listeners in a SQL virtual machine group. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +// SQLVirtualMachineGroupName - name of the SQL virtual machine group. +func (client AvailabilityGroupListenersClient) ListByGroup(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string) (result AvailabilityGroupListenerListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilityGroupListenersClient.ListByGroup") + defer func() { + sc := -1 + if result.agllr.Response.Response != nil { + sc = result.agllr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByGroupNextResults + req, err := client.ListByGroupPreparer(ctx, resourceGroupName, SQLVirtualMachineGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersClient", "ListByGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByGroupSender(req) + if err != nil { + result.agllr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersClient", "ListByGroup", resp, "Failure sending request") + return + } + + result.agllr, err = client.ListByGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersClient", "ListByGroup", resp, "Failure responding to request") + } + + return +} + +// ListByGroupPreparer prepares the ListByGroup request. +func (client AvailabilityGroupListenersClient) ListByGroupPreparer(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "sqlVirtualMachineGroupName": autorest.Encode("path", SQLVirtualMachineGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}/availabilityGroupListeners", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByGroupSender sends the ListByGroup request. The method will close the +// http.Response Body if it receives an error. +func (client AvailabilityGroupListenersClient) ListByGroupSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByGroupResponder handles the response to the ListByGroup request. The method always +// closes the http.Response Body. +func (client AvailabilityGroupListenersClient) ListByGroupResponder(resp *http.Response) (result AvailabilityGroupListenerListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByGroupNextResults retrieves the next set of results, if any. +func (client AvailabilityGroupListenersClient) listByGroupNextResults(ctx context.Context, lastResults AvailabilityGroupListenerListResult) (result AvailabilityGroupListenerListResult, err error) { + req, err := lastResults.availabilityGroupListenerListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersClient", "listByGroupNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersClient", "listByGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersClient", "listByGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client AvailabilityGroupListenersClient) ListByGroupComplete(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string) (result AvailabilityGroupListenerListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilityGroupListenersClient.ListByGroup") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListByGroup(ctx, resourceGroupName, SQLVirtualMachineGroupName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/client.go new file mode 100644 index 000000000000..5966df261a9a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/client.go @@ -0,0 +1,54 @@ +// Package sqlvirtualmachine implements the Azure ARM Sqlvirtualmachine service API version 2017-03-01-preview. +// +// The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network +// & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a +// SQL virtual machine, SQL virtual machine group or availability group listener. +package sqlvirtualmachine + +// 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 Sqlvirtualmachine + DefaultBaseURI = "https://management.azure.com" +) + +// BaseClient is the base client for Sqlvirtualmachine. +type BaseClient struct { + autorest.Client + BaseURI string + SubscriptionID string +} + +// New creates an instance of the BaseClient client. +func New(subscriptionID string) BaseClient { + return NewWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWithBaseURI creates an instance of the BaseClient client using a custom endpoint. Use this when interacting with +// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { + return BaseClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + SubscriptionID: subscriptionID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/groups.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/groups.go new file mode 100644 index 000000000000..35d8dfbae7da --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/groups.go @@ -0,0 +1,579 @@ +package sqlvirtualmachine + +// 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/tracing" + "net/http" +) + +// GroupsClient is the the SQL virtual machine management API provides a RESTful set of web APIs that interact with +// Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to +// create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener. +type GroupsClient struct { + BaseClient +} + +// NewGroupsClient creates an instance of the GroupsClient client. +func NewGroupsClient(subscriptionID string) GroupsClient { + return NewGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewGroupsClientWithBaseURI creates an instance of the GroupsClient client using a custom endpoint. Use this when +// interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewGroupsClientWithBaseURI(baseURI string, subscriptionID string) GroupsClient { + return GroupsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates a SQL virtual machine group. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +// SQLVirtualMachineGroupName - name of the SQL virtual machine group. +// parameters - the SQL virtual machine group. +func (client GroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string, parameters Group) (result GroupsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, SQLVirtualMachineGroupName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client GroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string, parameters Group) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "sqlVirtualMachineGroupName": autorest.Encode("path", SQLVirtualMachineGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client GroupsClient) CreateOrUpdateSender(req *http.Request) (future GroupsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client GroupsClient) CreateOrUpdateResponder(resp *http.Response) (result Group, 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 SQL virtual machine group. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +// SQLVirtualMachineGroupName - name of the SQL virtual machine group. +func (client GroupsClient) Delete(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string) (result GroupsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, SQLVirtualMachineGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client GroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "sqlVirtualMachineGroupName": autorest.Encode("path", SQLVirtualMachineGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}", 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 GroupsClient) DeleteSender(req *http.Request) (future GroupsDeleteFuture, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + 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 GroupsClient) 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 SQL virtual machine group. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +// SQLVirtualMachineGroupName - name of the SQL virtual machine group. +func (client GroupsClient) Get(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string) (result Group, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, SQLVirtualMachineGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client GroupsClient) GetPreparer(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "sqlVirtualMachineGroupName": autorest.Encode("path", SQLVirtualMachineGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}", 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 GroupsClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client GroupsClient) GetResponder(resp *http.Response) (result Group, 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 SQL virtual machine groups in a subscription. +func (client GroupsClient) List(ctx context.Context) (result GroupListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.List") + defer func() { + sc := -1 + if result.glr.Response.Response != nil { + sc = result.glr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.glr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "List", resp, "Failure sending request") + return + } + + result.glr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client GroupsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups", 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 GroupsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client GroupsClient) ListResponder(resp *http.Response) (result GroupListResult, 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 GroupsClient) listNextResults(ctx context.Context, lastResults GroupListResult) (result GroupListResult, err error) { + req, err := lastResults.groupListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "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, "sqlvirtualmachine.GroupsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client GroupsClient) ListComplete(ctx context.Context) (result GroupListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx) + return +} + +// ListByResourceGroup gets all SQL virtual machine groups in a resource group. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +func (client GroupsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result GroupListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.glr.Response.Response != nil { + sc = result.glr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.glr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result.glr, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client GroupsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups", 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 GroupsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client GroupsClient) ListByResourceGroupResponder(resp *http.Response) (result GroupListResult, 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 GroupsClient) listByResourceGroupNextResults(ctx context.Context, lastResults GroupListResult) (result GroupListResult, err error) { + req, err := lastResults.groupListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "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, "sqlvirtualmachine.GroupsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client GroupsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result GroupListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) + return +} + +// Update updates SQL virtual machine group tags. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +// SQLVirtualMachineGroupName - name of the SQL virtual machine group. +// parameters - the SQL virtual machine group. +func (client GroupsClient) Update(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string, parameters GroupUpdate) (result GroupsUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupsClient.Update") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, SQLVirtualMachineGroupName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client GroupsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string, parameters GroupUpdate) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "sqlVirtualMachineGroupName": autorest.Encode("path", SQLVirtualMachineGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}", 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 GroupsClient) UpdateSender(req *http.Request) (future GroupsUpdateFuture, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + 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 GroupsClient) UpdateResponder(resp *http.Response) (result Group, 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/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/models.go new file mode 100644 index 000000000000..0983c33e0199 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/models.go @@ -0,0 +1,1732 @@ +package sqlvirtualmachine + +// 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" + "encoding/json" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/tracing" + "github.com/satori/go.uuid" + "net/http" +) + +// The package's fully qualified name. +const fqdn = "github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine" + +// BackupScheduleType enumerates the values for backup schedule type. +type BackupScheduleType string + +const ( + // Automated ... + Automated BackupScheduleType = "Automated" + // Manual ... + Manual BackupScheduleType = "Manual" +) + +// PossibleBackupScheduleTypeValues returns an array of possible values for the BackupScheduleType const type. +func PossibleBackupScheduleTypeValues() []BackupScheduleType { + return []BackupScheduleType{Automated, Manual} +} + +// ClusterConfiguration enumerates the values for cluster configuration. +type ClusterConfiguration string + +const ( + // Domainful ... + Domainful ClusterConfiguration = "Domainful" +) + +// PossibleClusterConfigurationValues returns an array of possible values for the ClusterConfiguration const type. +func PossibleClusterConfigurationValues() []ClusterConfiguration { + return []ClusterConfiguration{Domainful} +} + +// ClusterManagerType enumerates the values for cluster manager type. +type ClusterManagerType string + +const ( + // WSFC ... + WSFC ClusterManagerType = "WSFC" +) + +// PossibleClusterManagerTypeValues returns an array of possible values for the ClusterManagerType const type. +func PossibleClusterManagerTypeValues() []ClusterManagerType { + return []ClusterManagerType{WSFC} +} + +// ConnectivityType enumerates the values for connectivity type. +type ConnectivityType string + +const ( + // LOCAL ... + LOCAL ConnectivityType = "LOCAL" + // PRIVATE ... + PRIVATE ConnectivityType = "PRIVATE" + // PUBLIC ... + PUBLIC ConnectivityType = "PUBLIC" +) + +// PossibleConnectivityTypeValues returns an array of possible values for the ConnectivityType const type. +func PossibleConnectivityTypeValues() []ConnectivityType { + return []ConnectivityType{LOCAL, PRIVATE, PUBLIC} +} + +// DayOfWeek enumerates the values for day of week. +type DayOfWeek string + +const ( + // Friday ... + Friday DayOfWeek = "Friday" + // Monday ... + Monday DayOfWeek = "Monday" + // Saturday ... + Saturday DayOfWeek = "Saturday" + // Sunday ... + Sunday DayOfWeek = "Sunday" + // Thursday ... + Thursday DayOfWeek = "Thursday" + // Tuesday ... + Tuesday DayOfWeek = "Tuesday" + // Wednesday ... + Wednesday DayOfWeek = "Wednesday" +) + +// PossibleDayOfWeekValues returns an array of possible values for the DayOfWeek const type. +func PossibleDayOfWeekValues() []DayOfWeek { + return []DayOfWeek{Friday, Monday, Saturday, Sunday, Thursday, Tuesday, Wednesday} +} + +// DiskConfigurationType enumerates the values for disk configuration type. +type DiskConfigurationType string + +const ( + // ADD ... + ADD DiskConfigurationType = "ADD" + // EXTEND ... + EXTEND DiskConfigurationType = "EXTEND" + // NEW ... + NEW DiskConfigurationType = "NEW" +) + +// PossibleDiskConfigurationTypeValues returns an array of possible values for the DiskConfigurationType const type. +func PossibleDiskConfigurationTypeValues() []DiskConfigurationType { + return []DiskConfigurationType{ADD, EXTEND, NEW} +} + +// FullBackupFrequencyType enumerates the values for full backup frequency type. +type FullBackupFrequencyType string + +const ( + // Daily ... + Daily FullBackupFrequencyType = "Daily" + // Weekly ... + Weekly FullBackupFrequencyType = "Weekly" +) + +// PossibleFullBackupFrequencyTypeValues returns an array of possible values for the FullBackupFrequencyType const type. +func PossibleFullBackupFrequencyTypeValues() []FullBackupFrequencyType { + return []FullBackupFrequencyType{Daily, Weekly} +} + +// IdentityType enumerates the values for identity type. +type IdentityType string + +const ( + // SystemAssigned ... + SystemAssigned IdentityType = "SystemAssigned" +) + +// PossibleIdentityTypeValues returns an array of possible values for the IdentityType const type. +func PossibleIdentityTypeValues() []IdentityType { + return []IdentityType{SystemAssigned} +} + +// OperationOrigin enumerates the values for operation origin. +type OperationOrigin string + +const ( + // System ... + System OperationOrigin = "system" + // User ... + User OperationOrigin = "user" +) + +// PossibleOperationOriginValues returns an array of possible values for the OperationOrigin const type. +func PossibleOperationOriginValues() []OperationOrigin { + return []OperationOrigin{System, User} +} + +// ScaleType enumerates the values for scale type. +type ScaleType string + +const ( + // HA ... + HA ScaleType = "HA" +) + +// PossibleScaleTypeValues returns an array of possible values for the ScaleType const type. +func PossibleScaleTypeValues() []ScaleType { + return []ScaleType{HA} +} + +// SQLImageSku enumerates the values for sql image sku. +type SQLImageSku string + +const ( + // Developer ... + Developer SQLImageSku = "Developer" + // Enterprise ... + Enterprise SQLImageSku = "Enterprise" + // Express ... + Express SQLImageSku = "Express" + // Standard ... + Standard SQLImageSku = "Standard" + // Web ... + Web SQLImageSku = "Web" +) + +// PossibleSQLImageSkuValues returns an array of possible values for the SQLImageSku const type. +func PossibleSQLImageSkuValues() []SQLImageSku { + return []SQLImageSku{Developer, Enterprise, Express, Standard, Web} +} + +// SQLManagementMode enumerates the values for sql management mode. +type SQLManagementMode string + +const ( + // Full ... + Full SQLManagementMode = "Full" + // LightWeight ... + LightWeight SQLManagementMode = "LightWeight" + // NoAgent ... + NoAgent SQLManagementMode = "NoAgent" +) + +// PossibleSQLManagementModeValues returns an array of possible values for the SQLManagementMode const type. +func PossibleSQLManagementModeValues() []SQLManagementMode { + return []SQLManagementMode{Full, LightWeight, NoAgent} +} + +// SQLServerLicenseType enumerates the values for sql server license type. +type SQLServerLicenseType string + +const ( + // AHUB ... + AHUB SQLServerLicenseType = "AHUB" + // DR ... + DR SQLServerLicenseType = "DR" + // PAYG ... + PAYG SQLServerLicenseType = "PAYG" +) + +// PossibleSQLServerLicenseTypeValues returns an array of possible values for the SQLServerLicenseType const type. +func PossibleSQLServerLicenseTypeValues() []SQLServerLicenseType { + return []SQLServerLicenseType{AHUB, DR, PAYG} +} + +// SQLVMGroupImageSku enumerates the values for sqlvm group image sku. +type SQLVMGroupImageSku string + +const ( + // SQLVMGroupImageSkuDeveloper ... + SQLVMGroupImageSkuDeveloper SQLVMGroupImageSku = "Developer" + // SQLVMGroupImageSkuEnterprise ... + SQLVMGroupImageSkuEnterprise SQLVMGroupImageSku = "Enterprise" +) + +// PossibleSQLVMGroupImageSkuValues returns an array of possible values for the SQLVMGroupImageSku const type. +func PossibleSQLVMGroupImageSkuValues() []SQLVMGroupImageSku { + return []SQLVMGroupImageSku{SQLVMGroupImageSkuDeveloper, SQLVMGroupImageSkuEnterprise} +} + +// SQLWorkloadType enumerates the values for sql workload type. +type SQLWorkloadType string + +const ( + // DW ... + DW SQLWorkloadType = "DW" + // GENERAL ... + GENERAL SQLWorkloadType = "GENERAL" + // OLTP ... + OLTP SQLWorkloadType = "OLTP" +) + +// PossibleSQLWorkloadTypeValues returns an array of possible values for the SQLWorkloadType const type. +func PossibleSQLWorkloadTypeValues() []SQLWorkloadType { + return []SQLWorkloadType{DW, GENERAL, OLTP} +} + +// StorageWorkloadType enumerates the values for storage workload type. +type StorageWorkloadType string + +const ( + // StorageWorkloadTypeDW ... + StorageWorkloadTypeDW StorageWorkloadType = "DW" + // StorageWorkloadTypeGENERAL ... + StorageWorkloadTypeGENERAL StorageWorkloadType = "GENERAL" + // StorageWorkloadTypeOLTP ... + StorageWorkloadTypeOLTP StorageWorkloadType = "OLTP" +) + +// PossibleStorageWorkloadTypeValues returns an array of possible values for the StorageWorkloadType const type. +func PossibleStorageWorkloadTypeValues() []StorageWorkloadType { + return []StorageWorkloadType{StorageWorkloadTypeDW, StorageWorkloadTypeGENERAL, StorageWorkloadTypeOLTP} +} + +// AdditionalFeaturesServerConfigurations additional SQL Server feature settings. +type AdditionalFeaturesServerConfigurations struct { + // IsRServicesEnabled - Enable or disable R services (SQL 2016 onwards). + IsRServicesEnabled *bool `json:"isRServicesEnabled,omitempty"` +} + +// AutoBackupSettings configure backups for databases in your SQL virtual machine. +type AutoBackupSettings struct { + // Enable - Enable or disable autobackup on SQL virtual machine. + Enable *bool `json:"enable,omitempty"` + // EnableEncryption - Enable or disable encryption for backup on SQL virtual machine. + EnableEncryption *bool `json:"enableEncryption,omitempty"` + // RetentionPeriod - Retention period of backup: 1-30 days. + RetentionPeriod *int32 `json:"retentionPeriod,omitempty"` + // StorageAccountURL - Storage account url where backup will be taken to. + StorageAccountURL *string `json:"storageAccountUrl,omitempty"` + // StorageAccessKey - Storage account key where backup will be taken to. + StorageAccessKey *string `json:"storageAccessKey,omitempty"` + // Password - Password for encryption on backup. + Password *string `json:"password,omitempty"` + // BackupSystemDbs - Include or exclude system databases from auto backup. + BackupSystemDbs *bool `json:"backupSystemDbs,omitempty"` + // BackupScheduleType - Backup schedule type. Possible values include: 'Manual', 'Automated' + BackupScheduleType BackupScheduleType `json:"backupScheduleType,omitempty"` + // FullBackupFrequency - Frequency of full backups. In both cases, full backups begin during the next scheduled time window. Possible values include: 'Daily', 'Weekly' + FullBackupFrequency FullBackupFrequencyType `json:"fullBackupFrequency,omitempty"` + // FullBackupStartTime - Start time of a given day during which full backups can take place. 0-23 hours. + FullBackupStartTime *int32 `json:"fullBackupStartTime,omitempty"` + // FullBackupWindowHours - Duration of the time window of a given day during which full backups can take place. 1-23 hours. + FullBackupWindowHours *int32 `json:"fullBackupWindowHours,omitempty"` + // LogBackupFrequency - Frequency of log backups. 5-60 minutes. + LogBackupFrequency *int32 `json:"logBackupFrequency,omitempty"` +} + +// AutoPatchingSettings set a patching window during which Windows and SQL patches will be applied. +type AutoPatchingSettings struct { + // Enable - Enable or disable autopatching on SQL virtual machine. + Enable *bool `json:"enable,omitempty"` + // DayOfWeek - Day of week to apply the patch on. Possible values include: 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' + DayOfWeek DayOfWeek `json:"dayOfWeek,omitempty"` + // MaintenanceWindowStartingHour - Hour of the day when patching is initiated. Local VM time. + MaintenanceWindowStartingHour *int32 `json:"maintenanceWindowStartingHour,omitempty"` + // MaintenanceWindowDuration - Duration of patching. + MaintenanceWindowDuration *int32 `json:"maintenanceWindowDuration,omitempty"` +} + +// AvailabilityGroupListener a SQL Server availability group listener. +type AvailabilityGroupListener struct { + autorest.Response `json:"-"` + // AvailabilityGroupListenerProperties - Resource properties. + *AvailabilityGroupListenerProperties `json:"properties,omitempty"` + // ID - READ-ONLY; Resource ID. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for AvailabilityGroupListener. +func (agl AvailabilityGroupListener) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if agl.AvailabilityGroupListenerProperties != nil { + objectMap["properties"] = agl.AvailabilityGroupListenerProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for AvailabilityGroupListener struct. +func (agl *AvailabilityGroupListener) 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 availabilityGroupListenerProperties AvailabilityGroupListenerProperties + err = json.Unmarshal(*v, &availabilityGroupListenerProperties) + if err != nil { + return err + } + agl.AvailabilityGroupListenerProperties = &availabilityGroupListenerProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + agl.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + agl.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + agl.Type = &typeVar + } + } + } + + return nil +} + +// AvailabilityGroupListenerListResult a list of availability group listeners. +type AvailabilityGroupListenerListResult struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; Array of results. + Value *[]AvailabilityGroupListener `json:"value,omitempty"` + // NextLink - READ-ONLY; Link to retrieve next page of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// AvailabilityGroupListenerListResultIterator provides access to a complete listing of +// AvailabilityGroupListener values. +type AvailabilityGroupListenerListResultIterator struct { + i int + page AvailabilityGroupListenerListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *AvailabilityGroupListenerListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilityGroupListenerListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *AvailabilityGroupListenerListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter AvailabilityGroupListenerListResultIterator) 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 AvailabilityGroupListenerListResultIterator) Response() AvailabilityGroupListenerListResult { + 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 AvailabilityGroupListenerListResultIterator) Value() AvailabilityGroupListener { + if !iter.page.NotDone() { + return AvailabilityGroupListener{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the AvailabilityGroupListenerListResultIterator type. +func NewAvailabilityGroupListenerListResultIterator(page AvailabilityGroupListenerListResultPage) AvailabilityGroupListenerListResultIterator { + return AvailabilityGroupListenerListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (agllr AvailabilityGroupListenerListResult) IsEmpty() bool { + return agllr.Value == nil || len(*agllr.Value) == 0 +} + +// availabilityGroupListenerListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (agllr AvailabilityGroupListenerListResult) availabilityGroupListenerListResultPreparer(ctx context.Context) (*http.Request, error) { + if agllr.NextLink == nil || len(to.String(agllr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(agllr.NextLink))) +} + +// AvailabilityGroupListenerListResultPage contains a page of AvailabilityGroupListener values. +type AvailabilityGroupListenerListResultPage struct { + fn func(context.Context, AvailabilityGroupListenerListResult) (AvailabilityGroupListenerListResult, error) + agllr AvailabilityGroupListenerListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *AvailabilityGroupListenerListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/AvailabilityGroupListenerListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.agllr) + if err != nil { + return err + } + page.agllr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *AvailabilityGroupListenerListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page AvailabilityGroupListenerListResultPage) NotDone() bool { + return !page.agllr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page AvailabilityGroupListenerListResultPage) Response() AvailabilityGroupListenerListResult { + return page.agllr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page AvailabilityGroupListenerListResultPage) Values() []AvailabilityGroupListener { + if page.agllr.IsEmpty() { + return nil + } + return *page.agllr.Value +} + +// Creates a new instance of the AvailabilityGroupListenerListResultPage type. +func NewAvailabilityGroupListenerListResultPage(getNextPage func(context.Context, AvailabilityGroupListenerListResult) (AvailabilityGroupListenerListResult, error)) AvailabilityGroupListenerListResultPage { + return AvailabilityGroupListenerListResultPage{fn: getNextPage} +} + +// AvailabilityGroupListenerProperties the properties of an availability group listener. +type AvailabilityGroupListenerProperties struct { + // ProvisioningState - READ-ONLY; Provisioning state to track the async operation status. + ProvisioningState *string `json:"provisioningState,omitempty"` + // AvailabilityGroupName - Name of the availability group. + AvailabilityGroupName *string `json:"availabilityGroupName,omitempty"` + // LoadBalancerConfigurations - List of load balancer configurations for an availability group listener. + LoadBalancerConfigurations *[]LoadBalancerConfiguration `json:"loadBalancerConfigurations,omitempty"` + // CreateDefaultAvailabilityGroupIfNotExist - Create a default availability group if it does not exist. + CreateDefaultAvailabilityGroupIfNotExist *bool `json:"createDefaultAvailabilityGroupIfNotExist,omitempty"` + // Port - Listener port. + Port *int32 `json:"port,omitempty"` +} + +// AvailabilityGroupListenersCreateOrUpdateFuture an abstraction for monitoring and retrieving the results +// of a long-running operation. +type AvailabilityGroupListenersCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *AvailabilityGroupListenersCreateOrUpdateFuture) Result(client AvailabilityGroupListenersClient) (agl AvailabilityGroupListener, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sqlvirtualmachine.AvailabilityGroupListenersCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if agl.Response.Response, err = future.GetResult(sender); err == nil && agl.Response.Response.StatusCode != http.StatusNoContent { + agl, err = client.CreateOrUpdateResponder(agl.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersCreateOrUpdateFuture", "Result", agl.Response.Response, "Failure responding to request") + } + } + return +} + +// AvailabilityGroupListenersDeleteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type AvailabilityGroupListenersDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *AvailabilityGroupListenersDeleteFuture) Result(client AvailabilityGroupListenersClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.AvailabilityGroupListenersDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sqlvirtualmachine.AvailabilityGroupListenersDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// Group a SQL virtual machine group. +type Group struct { + autorest.Response `json:"-"` + // GroupProperties - Resource properties. + *GroupProperties `json:"properties,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Resource ID. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for Group. +func (g Group) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if g.GroupProperties != nil { + objectMap["properties"] = g.GroupProperties + } + if g.Location != nil { + objectMap["location"] = g.Location + } + if g.Tags != nil { + objectMap["tags"] = g.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Group struct. +func (g *Group) 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 groupProperties GroupProperties + err = json.Unmarshal(*v, &groupProperties) + if err != nil { + return err + } + g.GroupProperties = &groupProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + g.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + g.Tags = tags + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + g.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + g.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + g.Type = &typeVar + } + } + } + + return nil +} + +// GroupListResult a list of SQL virtual machine groups. +type GroupListResult struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; Array of results. + Value *[]Group `json:"value,omitempty"` + // NextLink - READ-ONLY; Link to retrieve next page of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// GroupListResultIterator provides access to a complete listing of Group values. +type GroupListResultIterator struct { + i int + page GroupListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *GroupListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *GroupListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter GroupListResultIterator) 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 GroupListResultIterator) Response() GroupListResult { + 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 GroupListResultIterator) Value() Group { + if !iter.page.NotDone() { + return Group{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the GroupListResultIterator type. +func NewGroupListResultIterator(page GroupListResultPage) GroupListResultIterator { + return GroupListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (glr GroupListResult) IsEmpty() bool { + return glr.Value == nil || len(*glr.Value) == 0 +} + +// groupListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (glr GroupListResult) groupListResultPreparer(ctx context.Context) (*http.Request, error) { + if glr.NextLink == nil || len(to.String(glr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(glr.NextLink))) +} + +// GroupListResultPage contains a page of Group values. +type GroupListResultPage struct { + fn func(context.Context, GroupListResult) (GroupListResult, error) + glr GroupListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *GroupListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GroupListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.glr) + if err != nil { + return err + } + page.glr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *GroupListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page GroupListResultPage) NotDone() bool { + return !page.glr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page GroupListResultPage) Response() GroupListResult { + return page.glr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page GroupListResultPage) Values() []Group { + if page.glr.IsEmpty() { + return nil + } + return *page.glr.Value +} + +// Creates a new instance of the GroupListResultPage type. +func NewGroupListResultPage(getNextPage func(context.Context, GroupListResult) (GroupListResult, error)) GroupListResultPage { + return GroupListResultPage{fn: getNextPage} +} + +// GroupProperties the properties of a SQL virtual machine group. +type GroupProperties struct { + // ProvisioningState - READ-ONLY; Provisioning state to track the async operation status. + ProvisioningState *string `json:"provisioningState,omitempty"` + // SQLImageOffer - SQL image offer. Examples may include SQL2016-WS2016, SQL2017-WS2016. + SQLImageOffer *string `json:"sqlImageOffer,omitempty"` + // SQLImageSku - SQL image sku. Possible values include: 'SQLVMGroupImageSkuDeveloper', 'SQLVMGroupImageSkuEnterprise' + SQLImageSku SQLVMGroupImageSku `json:"sqlImageSku,omitempty"` + // ScaleType - READ-ONLY; Scale type. Possible values include: 'HA' + ScaleType ScaleType `json:"scaleType,omitempty"` + // ClusterManagerType - READ-ONLY; Type of cluster manager: Windows Server Failover Cluster (WSFC), implied by the scale type of the group and the OS type. Possible values include: 'WSFC' + ClusterManagerType ClusterManagerType `json:"clusterManagerType,omitempty"` + // ClusterConfiguration - READ-ONLY; Cluster type. Possible values include: 'Domainful' + ClusterConfiguration ClusterConfiguration `json:"clusterConfiguration,omitempty"` + // WsfcDomainProfile - Cluster Active Directory domain profile. + WsfcDomainProfile *WsfcDomainProfile `json:"wsfcDomainProfile,omitempty"` +} + +// GroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type GroupsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *GroupsCreateOrUpdateFuture) Result(client GroupsClient) (g Group, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sqlvirtualmachine.GroupsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if g.Response.Response, err = future.GetResult(sender); err == nil && g.Response.Response.StatusCode != http.StatusNoContent { + g, err = client.CreateOrUpdateResponder(g.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsCreateOrUpdateFuture", "Result", g.Response.Response, "Failure responding to request") + } + } + return +} + +// GroupsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type GroupsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *GroupsDeleteFuture) Result(client GroupsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sqlvirtualmachine.GroupsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// GroupsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type GroupsUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *GroupsUpdateFuture) Result(client GroupsClient) (g Group, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sqlvirtualmachine.GroupsUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if g.Response.Response, err = future.GetResult(sender); err == nil && g.Response.Response.StatusCode != http.StatusNoContent { + g, err = client.UpdateResponder(g.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.GroupsUpdateFuture", "Result", g.Response.Response, "Failure responding to request") + } + } + return +} + +// GroupUpdate an update to a SQL virtual machine group. +type GroupUpdate struct { + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for GroupUpdate. +func (gu GroupUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if gu.Tags != nil { + objectMap["tags"] = gu.Tags + } + return json.Marshal(objectMap) +} + +// KeyVaultCredentialSettings configure your SQL virtual machine to be able to connect to the Azure Key +// Vault service. +type KeyVaultCredentialSettings struct { + // Enable - Enable or disable key vault credential setting. + Enable *bool `json:"enable,omitempty"` + // CredentialName - Credential name. + CredentialName *string `json:"credentialName,omitempty"` + // AzureKeyVaultURL - Azure Key Vault url. + AzureKeyVaultURL *string `json:"azureKeyVaultUrl,omitempty"` + // ServicePrincipalName - Service principal name to access key vault. + ServicePrincipalName *string `json:"servicePrincipalName,omitempty"` + // ServicePrincipalSecret - Service principal name secret to access key vault. + ServicePrincipalSecret *string `json:"servicePrincipalSecret,omitempty"` +} + +// ListResult a list of SQL virtual machines. +type ListResult struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; Array of results. + Value *[]SQLVirtualMachine `json:"value,omitempty"` + // NextLink - READ-ONLY; Link to retrieve next page of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ListResultIterator provides access to a complete listing of SQLVirtualMachine values. +type ListResultIterator struct { + i int + page ListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *ListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ListResultIterator) 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 ListResultIterator) Response() ListResult { + 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 ListResultIterator) Value() SQLVirtualMachine { + if !iter.page.NotDone() { + return SQLVirtualMachine{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ListResultIterator type. +func NewListResultIterator(page ListResultPage) ListResultIterator { + return ListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (lr ListResult) IsEmpty() bool { + return lr.Value == nil || len(*lr.Value) == 0 +} + +// listResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (lr ListResult) listResultPreparer(ctx context.Context) (*http.Request, error) { + if lr.NextLink == nil || len(to.String(lr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(lr.NextLink))) +} + +// ListResultPage contains a page of SQLVirtualMachine values. +type ListResultPage struct { + fn func(context.Context, ListResult) (ListResult, error) + lr ListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.lr) + if err != nil { + return err + } + page.lr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *ListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ListResultPage) NotDone() bool { + return !page.lr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ListResultPage) Response() ListResult { + return page.lr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ListResultPage) Values() []SQLVirtualMachine { + if page.lr.IsEmpty() { + return nil + } + return *page.lr.Value +} + +// Creates a new instance of the ListResultPage type. +func NewListResultPage(getNextPage func(context.Context, ListResult) (ListResult, error)) ListResultPage { + return ListResultPage{fn: getNextPage} +} + +// LoadBalancerConfiguration a load balancer configuration for an availability group listener. +type LoadBalancerConfiguration struct { + // PrivateIPAddress - Private IP address. + PrivateIPAddress *PrivateIPAddress `json:"privateIpAddress,omitempty"` + // PublicIPAddressResourceID - Resource id of the public IP. + PublicIPAddressResourceID *string `json:"publicIpAddressResourceId,omitempty"` + // LoadBalancerResourceID - Resource id of the load balancer. + LoadBalancerResourceID *string `json:"loadBalancerResourceId,omitempty"` + // ProbePort - Probe port. + ProbePort *int32 `json:"probePort,omitempty"` + // SQLVirtualMachineInstances - List of the SQL virtual machine instance resource id's that are enrolled into the availability group listener. + SQLVirtualMachineInstances *[]string `json:"sqlVirtualMachineInstances,omitempty"` +} + +// Operation SQL REST API operation definition. +type Operation struct { + // Name - READ-ONLY; The name of the operation being performed on this particular object. + Name *string `json:"name,omitempty"` + // Display - READ-ONLY; The localized display information for this particular operation / action. + Display *OperationDisplay `json:"display,omitempty"` + // Origin - READ-ONLY; The intended executor of the operation. Possible values include: 'User', 'System' + Origin OperationOrigin `json:"origin,omitempty"` + // Properties - READ-ONLY; Additional descriptions for the operation. + Properties map[string]interface{} `json:"properties"` +} + +// MarshalJSON is the custom marshaler for Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + return json.Marshal(objectMap) +} + +// OperationDisplay display metadata associated with the operation. +type OperationDisplay struct { + // Provider - READ-ONLY; The localized friendly form of the resource provider name. + Provider *string `json:"provider,omitempty"` + // Resource - READ-ONLY; The localized friendly form of the resource type related to this action/operation. + Resource *string `json:"resource,omitempty"` + // Operation - READ-ONLY; The localized friendly name for the operation. + Operation *string `json:"operation,omitempty"` + // Description - READ-ONLY; The localized friendly description for the operation. + Description *string `json:"description,omitempty"` +} + +// OperationListResult result of the request to list SQL operations. +type OperationListResult struct { + autorest.Response `json:"-"` + // Value - READ-ONLY; Array of results. + Value *[]Operation `json:"value,omitempty"` + // NextLink - READ-ONLY; Link to retrieve next page of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// OperationListResultIterator provides access to a complete listing of Operation values. +type OperationListResultIterator struct { + i int + page OperationListResultPage +} + +// NextWithContext advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *OperationListResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultIterator.NextWithContext") + defer func() { + sc := -1 + if iter.Response().Response.Response != nil { + sc = iter.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err = iter.page.NextWithContext(ctx) + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (iter *OperationListResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter OperationListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter OperationListResultIterator) Response() OperationListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter OperationListResultIterator) Value() Operation { + if !iter.page.NotDone() { + return Operation{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the OperationListResultIterator type. +func NewOperationListResultIterator(page OperationListResultPage) OperationListResultIterator { + return OperationListResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (olr OperationListResult) IsEmpty() bool { + return olr.Value == nil || len(*olr.Value) == 0 +} + +// operationListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (olr OperationListResult) operationListResultPreparer(ctx context.Context) (*http.Request, error) { + if olr.NextLink == nil || len(to.String(olr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(olr.NextLink))) +} + +// OperationListResultPage contains a page of Operation values. +type OperationListResultPage struct { + fn func(context.Context, OperationListResult) (OperationListResult, error) + olr OperationListResult +} + +// NextWithContext advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultPage.NextWithContext") + defer func() { + sc := -1 + if page.Response().Response.Response != nil { + sc = page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + next, err := page.fn(ctx, page.olr) + if err != nil { + return err + } + page.olr = next + return nil +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +// Deprecated: Use NextWithContext() instead. +func (page *OperationListResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page OperationListResultPage) NotDone() bool { + return !page.olr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page OperationListResultPage) Response() OperationListResult { + return page.olr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page OperationListResultPage) Values() []Operation { + if page.olr.IsEmpty() { + return nil + } + return *page.olr.Value +} + +// Creates a new instance of the OperationListResultPage type. +func NewOperationListResultPage(getNextPage func(context.Context, OperationListResult) (OperationListResult, error)) OperationListResultPage { + return OperationListResultPage{fn: getNextPage} +} + +// PrivateIPAddress a private IP address bound to the availability group listener. +type PrivateIPAddress struct { + // IPAddress - Private IP address bound to the availability group listener. + IPAddress *string `json:"ipAddress,omitempty"` + // SubnetResourceID - Subnet used to include private IP. + SubnetResourceID *string `json:"subnetResourceId,omitempty"` +} + +// Properties the SQL virtual machine properties. +type Properties struct { + // VirtualMachineResourceID - ARM Resource id of underlying virtual machine created from SQL marketplace image. + VirtualMachineResourceID *string `json:"virtualMachineResourceId,omitempty"` + // ProvisioningState - READ-ONLY; Provisioning state to track the async operation status. + ProvisioningState *string `json:"provisioningState,omitempty"` + // SQLImageOffer - SQL image offer. Examples include SQL2016-WS2016, SQL2017-WS2016. + SQLImageOffer *string `json:"sqlImageOffer,omitempty"` + // SQLServerLicenseType - SQL Server license type. Possible values include: 'PAYG', 'AHUB', 'DR' + SQLServerLicenseType SQLServerLicenseType `json:"sqlServerLicenseType,omitempty"` + // SQLManagement - SQL Server Management type. Possible values include: 'Full', 'LightWeight', 'NoAgent' + SQLManagement SQLManagementMode `json:"sqlManagement,omitempty"` + // SQLImageSku - SQL Server edition type. Possible values include: 'Developer', 'Express', 'Standard', 'Enterprise', 'Web' + SQLImageSku SQLImageSku `json:"sqlImageSku,omitempty"` + // SQLVirtualMachineGroupResourceID - ARM resource id of the SQL virtual machine group this SQL virtual machine is or will be part of. + SQLVirtualMachineGroupResourceID *string `json:"sqlVirtualMachineGroupResourceId,omitempty"` + // WsfcDomainCredentials - Domain credentials for setting up Windows Server Failover Cluster for SQL availability group. + WsfcDomainCredentials *WsfcDomainCredentials `json:"wsfcDomainCredentials,omitempty"` + // AutoPatchingSettings - Auto patching settings for applying critical security updates to SQL virtual machine. + AutoPatchingSettings *AutoPatchingSettings `json:"autoPatchingSettings,omitempty"` + // AutoBackupSettings - Auto backup settings for SQL Server. + AutoBackupSettings *AutoBackupSettings `json:"autoBackupSettings,omitempty"` + // KeyVaultCredentialSettings - Key vault credential settings. + KeyVaultCredentialSettings *KeyVaultCredentialSettings `json:"keyVaultCredentialSettings,omitempty"` + // ServerConfigurationsManagementSettings - SQL Server configuration management settings. + ServerConfigurationsManagementSettings *ServerConfigurationsManagementSettings `json:"serverConfigurationsManagementSettings,omitempty"` + // StorageConfigurationSettings - Storage Configuration Settings. + StorageConfigurationSettings *StorageConfigurationSettings `json:"storageConfigurationSettings,omitempty"` +} + +// ProxyResource ARM proxy resource. +type ProxyResource struct { + // ID - READ-ONLY; Resource ID. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` +} + +// Resource ARM resource. +type Resource struct { + // ID - READ-ONLY; Resource ID. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` +} + +// ResourceIdentity azure Active Directory identity configuration for a resource. +type ResourceIdentity struct { + // PrincipalID - READ-ONLY; The Azure Active Directory principal id. + PrincipalID *uuid.UUID `json:"principalId,omitempty"` + // Type - The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory principal for the resource. Possible values include: 'SystemAssigned' + Type IdentityType `json:"type,omitempty"` + // TenantID - READ-ONLY; The Azure Active Directory tenant id. + TenantID *uuid.UUID `json:"tenantId,omitempty"` +} + +// ServerConfigurationsManagementSettings set the connectivity, storage and workload settings. +type ServerConfigurationsManagementSettings struct { + // SQLConnectivityUpdateSettings - SQL connectivity type settings. + SQLConnectivityUpdateSettings *SQLConnectivityUpdateSettings `json:"sqlConnectivityUpdateSettings,omitempty"` + // SQLWorkloadTypeUpdateSettings - SQL workload type settings. + SQLWorkloadTypeUpdateSettings *SQLWorkloadTypeUpdateSettings `json:"sqlWorkloadTypeUpdateSettings,omitempty"` + // SQLStorageUpdateSettings - SQL storage update settings. + SQLStorageUpdateSettings *SQLStorageUpdateSettings `json:"sqlStorageUpdateSettings,omitempty"` + // AdditionalFeaturesServerConfigurations - Additional SQL feature settings. + AdditionalFeaturesServerConfigurations *AdditionalFeaturesServerConfigurations `json:"additionalFeaturesServerConfigurations,omitempty"` +} + +// SQLConnectivityUpdateSettings set the access level and network port settings for SQL Server. +type SQLConnectivityUpdateSettings struct { + // ConnectivityType - SQL Server connectivity option. Possible values include: 'LOCAL', 'PRIVATE', 'PUBLIC' + ConnectivityType ConnectivityType `json:"connectivityType,omitempty"` + // Port - SQL Server port. + Port *int32 `json:"port,omitempty"` + // SQLAuthUpdateUserName - SQL Server sysadmin login to create. + SQLAuthUpdateUserName *string `json:"sqlAuthUpdateUserName,omitempty"` + // SQLAuthUpdatePassword - SQL Server sysadmin login password. + SQLAuthUpdatePassword *string `json:"sqlAuthUpdatePassword,omitempty"` +} + +// SQLStorageSettings set disk storage settings for SQL Server. +type SQLStorageSettings struct { + // Luns - Logical Unit Numbers for the disks. + Luns *[]int32 `json:"luns,omitempty"` + // DefaultFilePath - SQL Server default file path + DefaultFilePath *string `json:"defaultFilePath,omitempty"` +} + +// SQLStorageUpdateSettings set disk storage settings for SQL Server. +type SQLStorageUpdateSettings struct { + // DiskCount - Virtual machine disk count. + DiskCount *int32 `json:"diskCount,omitempty"` + // StartingDeviceID - Device id of the first disk to be updated. + StartingDeviceID *int32 `json:"startingDeviceId,omitempty"` + // DiskConfigurationType - Disk configuration to apply to SQL Server. Possible values include: 'NEW', 'EXTEND', 'ADD' + DiskConfigurationType DiskConfigurationType `json:"diskConfigurationType,omitempty"` +} + +// SQLVirtualMachine a SQL virtual machine. +type SQLVirtualMachine struct { + autorest.Response `json:"-"` + // Identity - Azure Active Directory identity of the server. + Identity *ResourceIdentity `json:"identity,omitempty"` + // Properties - Resource properties. + *Properties `json:"properties,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Resource ID. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for SQLVirtualMachine. +func (svm SQLVirtualMachine) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if svm.Identity != nil { + objectMap["identity"] = svm.Identity + } + if svm.Properties != nil { + objectMap["properties"] = svm.Properties + } + if svm.Location != nil { + objectMap["location"] = svm.Location + } + if svm.Tags != nil { + objectMap["tags"] = svm.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for SQLVirtualMachine struct. +func (svm *SQLVirtualMachine) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "identity": + if v != nil { + var identity ResourceIdentity + err = json.Unmarshal(*v, &identity) + if err != nil { + return err + } + svm.Identity = &identity + } + case "properties": + if v != nil { + var properties Properties + err = json.Unmarshal(*v, &properties) + if err != nil { + return err + } + svm.Properties = &properties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + svm.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + svm.Tags = tags + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + svm.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + svm.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + svm.Type = &typeVar + } + } + } + + return nil +} + +// SQLVirtualMachinesCreateOrUpdateFutureType an abstraction for monitoring and retrieving the results of a +// long-running operation. +type SQLVirtualMachinesCreateOrUpdateFutureType struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *SQLVirtualMachinesCreateOrUpdateFutureType) Result(client SQLVirtualMachinesClient) (svm SQLVirtualMachine, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesCreateOrUpdateFutureType", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sqlvirtualmachine.SQLVirtualMachinesCreateOrUpdateFutureType") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if svm.Response.Response, err = future.GetResult(sender); err == nil && svm.Response.Response.StatusCode != http.StatusNoContent { + svm, err = client.CreateOrUpdateResponder(svm.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesCreateOrUpdateFutureType", "Result", svm.Response.Response, "Failure responding to request") + } + } + return +} + +// SQLVirtualMachinesDeleteFutureType an abstraction for monitoring and retrieving the results of a +// long-running operation. +type SQLVirtualMachinesDeleteFutureType struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *SQLVirtualMachinesDeleteFutureType) Result(client SQLVirtualMachinesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesDeleteFutureType", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sqlvirtualmachine.SQLVirtualMachinesDeleteFutureType") + return + } + ar.Response = future.Response() + return +} + +// SQLVirtualMachinesUpdateFutureType an abstraction for monitoring and retrieving the results of a +// long-running operation. +type SQLVirtualMachinesUpdateFutureType struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *SQLVirtualMachinesUpdateFutureType) Result(client SQLVirtualMachinesClient) (svm SQLVirtualMachine, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesUpdateFutureType", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("sqlvirtualmachine.SQLVirtualMachinesUpdateFutureType") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if svm.Response.Response, err = future.GetResult(sender); err == nil && svm.Response.Response.StatusCode != http.StatusNoContent { + svm, err = client.UpdateResponder(svm.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesUpdateFutureType", "Result", svm.Response.Response, "Failure responding to request") + } + } + return +} + +// SQLWorkloadTypeUpdateSettings set workload type to optimize storage for SQL Server. +type SQLWorkloadTypeUpdateSettings struct { + // SQLWorkloadType - SQL Server workload type. Possible values include: 'GENERAL', 'OLTP', 'DW' + SQLWorkloadType SQLWorkloadType `json:"sqlWorkloadType,omitempty"` +} + +// StorageConfigurationSettings storage Configurations for SQL Data, Log and TempDb. +type StorageConfigurationSettings struct { + // SQLDataSettings - SQL Server Data Storage Settings. + SQLDataSettings *SQLStorageSettings `json:"sqlDataSettings,omitempty"` + // SQLLogSettings - SQL Server Log Storage Settings. + SQLLogSettings *SQLStorageSettings `json:"sqlLogSettings,omitempty"` + // SQLTempDbSettings - SQL Server TempDb Storage Settings. + SQLTempDbSettings *SQLStorageSettings `json:"sqlTempDbSettings,omitempty"` + // DiskConfigurationType - Disk configuration to apply to SQL Server. Possible values include: 'NEW', 'EXTEND', 'ADD' + DiskConfigurationType DiskConfigurationType `json:"diskConfigurationType,omitempty"` + // StorageWorkloadType - Storage workload type. Possible values include: 'StorageWorkloadTypeGENERAL', 'StorageWorkloadTypeOLTP', 'StorageWorkloadTypeDW' + StorageWorkloadType StorageWorkloadType `json:"storageWorkloadType,omitempty"` +} + +// TrackedResource ARM tracked top level resource. +type TrackedResource struct { + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` + // ID - READ-ONLY; Resource ID. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; Resource name. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; Resource type. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for TrackedResource. +func (tr TrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if tr.Location != nil { + objectMap["location"] = tr.Location + } + if tr.Tags != nil { + objectMap["tags"] = tr.Tags + } + return json.Marshal(objectMap) +} + +// Update an update to a SQL virtual machine. +type Update struct { + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Update. +func (u Update) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if u.Tags != nil { + objectMap["tags"] = u.Tags + } + return json.Marshal(objectMap) +} + +// WsfcDomainCredentials domain credentials for setting up Windows Server Failover Cluster for SQL +// availability group. +type WsfcDomainCredentials struct { + // ClusterBootstrapAccountPassword - Cluster bootstrap account password. + ClusterBootstrapAccountPassword *string `json:"clusterBootstrapAccountPassword,omitempty"` + // ClusterOperatorAccountPassword - Cluster operator account password. + ClusterOperatorAccountPassword *string `json:"clusterOperatorAccountPassword,omitempty"` + // SQLServiceAccountPassword - SQL service account password. + SQLServiceAccountPassword *string `json:"sqlServiceAccountPassword,omitempty"` +} + +// WsfcDomainProfile active Directory account details to operate Windows Server Failover Cluster. +type WsfcDomainProfile struct { + // DomainFqdn - Fully qualified name of the domain. + DomainFqdn *string `json:"domainFqdn,omitempty"` + // OuPath - Organizational Unit path in which the nodes and cluster will be present. + OuPath *string `json:"ouPath,omitempty"` + // ClusterBootstrapAccount - Account name used for creating cluster (at minimum needs permissions to 'Create Computer Objects' in domain). + ClusterBootstrapAccount *string `json:"clusterBootstrapAccount,omitempty"` + // ClusterOperatorAccount - Account name used for operating cluster i.e. will be part of administrators group on all the participating virtual machines in the cluster. + ClusterOperatorAccount *string `json:"clusterOperatorAccount,omitempty"` + // SQLServiceAccount - Account name under which SQL service will run on all participating SQL virtual machines in the cluster. + SQLServiceAccount *string `json:"sqlServiceAccount,omitempty"` + // FileShareWitnessPath - Optional path for fileshare witness. + FileShareWitnessPath *string `json:"fileShareWitnessPath,omitempty"` + // StorageAccountURL - Fully qualified ARM resource id of the witness storage account. + StorageAccountURL *string `json:"storageAccountUrl,omitempty"` + // StorageAccountPrimaryKey - Primary key of the witness storage account. + StorageAccountPrimaryKey *string `json:"storageAccountPrimaryKey,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/operations.go new file mode 100644 index 000000000000..e6306b684c0a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/operations.go @@ -0,0 +1,149 @@ +package sqlvirtualmachine + +// 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/tracing" + "net/http" +) + +// OperationsClient is the the SQL virtual machine management API provides a RESTful set of web APIs that interact with +// Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to +// create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener. +type OperationsClient struct { + BaseClient +} + +// NewOperationsClient creates an instance of the OperationsClient client. +func NewOperationsClient(subscriptionID string) OperationsClient { + return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client using a custom endpoint. Use this +// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). +func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { + return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List lists all of the available SQL Rest API operations. +func (client OperationsClient) List(ctx context.Context) (result OperationListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") + defer func() { + sc := -1 + if result.olr.Response.Response != nil { + sc = result.olr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.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, "sqlvirtualmachine.OperationsClient", "List", resp, "Failure sending request") + return + } + + result.olr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.OperationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.SqlVirtualMachine/operations"), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) { + err = autorest.Respond( + resp, + 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(ctx context.Context, lastResults OperationListResult) (result OperationListResult, err error) { + req, err := lastResults.operationListResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "sqlvirtualmachine.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, "sqlvirtualmachine.OperationsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.OperationsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client OperationsClient) ListComplete(ctx context.Context) (result OperationListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/sqlvirtualmachines.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/sqlvirtualmachines.go new file mode 100644 index 000000000000..7566aecb60c7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/sqlvirtualmachines.go @@ -0,0 +1,700 @@ +package sqlvirtualmachine + +// 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/tracing" + "net/http" +) + +// SQLVirtualMachinesClient is the the SQL virtual machine management API provides a RESTful set of web APIs that +// interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables +// users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group +// listener. +type SQLVirtualMachinesClient struct { + BaseClient +} + +// NewSQLVirtualMachinesClient creates an instance of the SQLVirtualMachinesClient client. +func NewSQLVirtualMachinesClient(subscriptionID string) SQLVirtualMachinesClient { + return NewSQLVirtualMachinesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewSQLVirtualMachinesClientWithBaseURI creates an instance of the SQLVirtualMachinesClient client using a custom +// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure +// stack). +func NewSQLVirtualMachinesClientWithBaseURI(baseURI string, subscriptionID string) SQLVirtualMachinesClient { + return SQLVirtualMachinesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates a SQL virtual machine. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +// SQLVirtualMachineName - name of the SQL virtual machine. +// parameters - the SQL virtual machine. +func (client SQLVirtualMachinesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, SQLVirtualMachineName string, parameters SQLVirtualMachine) (result SQLVirtualMachinesCreateOrUpdateFutureType, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SQLVirtualMachinesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, SQLVirtualMachineName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client SQLVirtualMachinesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, SQLVirtualMachineName string, parameters SQLVirtualMachine) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "sqlVirtualMachineName": autorest.Encode("path", SQLVirtualMachineName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/{sqlVirtualMachineName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client SQLVirtualMachinesClient) CreateOrUpdateSender(req *http.Request) (future SQLVirtualMachinesCreateOrUpdateFutureType, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client SQLVirtualMachinesClient) CreateOrUpdateResponder(resp *http.Response) (result SQLVirtualMachine, 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 SQL virtual machine. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +// SQLVirtualMachineName - name of the SQL virtual machine. +func (client SQLVirtualMachinesClient) Delete(ctx context.Context, resourceGroupName string, SQLVirtualMachineName string) (result SQLVirtualMachinesDeleteFutureType, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SQLVirtualMachinesClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, SQLVirtualMachineName) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client SQLVirtualMachinesClient) DeletePreparer(ctx context.Context, resourceGroupName string, SQLVirtualMachineName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "sqlVirtualMachineName": autorest.Encode("path", SQLVirtualMachineName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/{sqlVirtualMachineName}", 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 SQLVirtualMachinesClient) DeleteSender(req *http.Request) (future SQLVirtualMachinesDeleteFutureType, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + 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 SQLVirtualMachinesClient) 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 SQL virtual machine. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +// SQLVirtualMachineName - name of the SQL virtual machine. +// expand - the child resources to include in the response. +func (client SQLVirtualMachinesClient) Get(ctx context.Context, resourceGroupName string, SQLVirtualMachineName string, expand string) (result SQLVirtualMachine, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SQLVirtualMachinesClient.Get") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetPreparer(ctx, resourceGroupName, SQLVirtualMachineName, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client SQLVirtualMachinesClient) GetPreparer(ctx context.Context, resourceGroupName string, SQLVirtualMachineName string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "sqlVirtualMachineName": autorest.Encode("path", SQLVirtualMachineName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/{sqlVirtualMachineName}", 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 SQLVirtualMachinesClient) GetSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client SQLVirtualMachinesClient) GetResponder(resp *http.Response) (result SQLVirtualMachine, 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 SQL virtual machines in a subscription. +func (client SQLVirtualMachinesClient) List(ctx context.Context) (result ListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SQLVirtualMachinesClient.List") + defer func() { + sc := -1 + if result.lr.Response.Response != nil { + sc = result.lr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.lr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "List", resp, "Failure sending request") + return + } + + result.lr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client SQLVirtualMachinesClient) ListPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines", 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 SQLVirtualMachinesClient) ListSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client SQLVirtualMachinesClient) ListResponder(resp *http.Response) (result ListResult, 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 SQLVirtualMachinesClient) listNextResults(ctx context.Context, lastResults ListResult) (result ListResult, err error) { + req, err := lastResults.listResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "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, "sqlvirtualmachine.SQLVirtualMachinesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client SQLVirtualMachinesClient) ListComplete(ctx context.Context) (result ListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SQLVirtualMachinesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx) + return +} + +// ListByResourceGroup gets all SQL virtual machines in a resource group. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +func (client SQLVirtualMachinesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SQLVirtualMachinesClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.lr.Response.Response != nil { + sc = result.lr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.lr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result.lr, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client SQLVirtualMachinesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines", 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 SQLVirtualMachinesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client SQLVirtualMachinesClient) ListByResourceGroupResponder(resp *http.Response) (result ListResult, 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 SQLVirtualMachinesClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListResult) (result ListResult, err error) { + req, err := lastResults.listResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "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, "sqlvirtualmachine.SQLVirtualMachinesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client SQLVirtualMachinesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SQLVirtualMachinesClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) + return +} + +// ListBySQLVMGroup gets the list of sql virtual machines in a SQL virtual machine group. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +// SQLVirtualMachineGroupName - name of the SQL virtual machine group. +func (client SQLVirtualMachinesClient) ListBySQLVMGroup(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string) (result ListResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SQLVirtualMachinesClient.ListBySQLVMGroup") + defer func() { + sc := -1 + if result.lr.Response.Response != nil { + sc = result.lr.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listBySQLVMGroupNextResults + req, err := client.ListBySQLVMGroupPreparer(ctx, resourceGroupName, SQLVirtualMachineGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "ListBySQLVMGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySQLVMGroupSender(req) + if err != nil { + result.lr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "ListBySQLVMGroup", resp, "Failure sending request") + return + } + + result.lr, err = client.ListBySQLVMGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "ListBySQLVMGroup", resp, "Failure responding to request") + } + + return +} + +// ListBySQLVMGroupPreparer prepares the ListBySQLVMGroup request. +func (client SQLVirtualMachinesClient) ListBySQLVMGroupPreparer(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "sqlVirtualMachineGroupName": autorest.Encode("path", SQLVirtualMachineGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}/sqlVirtualMachines", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBySQLVMGroupSender sends the ListBySQLVMGroup request. The method will close the +// http.Response Body if it receives an error. +func (client SQLVirtualMachinesClient) ListBySQLVMGroupSender(req *http.Request) (*http.Response, error) { + return client.Send(req, azure.DoRetryWithRegistration(client.Client)) +} + +// ListBySQLVMGroupResponder handles the response to the ListBySQLVMGroup request. The method always +// closes the http.Response Body. +func (client SQLVirtualMachinesClient) ListBySQLVMGroupResponder(resp *http.Response) (result ListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBySQLVMGroupNextResults retrieves the next set of results, if any. +func (client SQLVirtualMachinesClient) listBySQLVMGroupNextResults(ctx context.Context, lastResults ListResult) (result ListResult, err error) { + req, err := lastResults.listResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "listBySQLVMGroupNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySQLVMGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "listBySQLVMGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySQLVMGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "listBySQLVMGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySQLVMGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client SQLVirtualMachinesClient) ListBySQLVMGroupComplete(ctx context.Context, resourceGroupName string, SQLVirtualMachineGroupName string) (result ListResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SQLVirtualMachinesClient.ListBySQLVMGroup") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListBySQLVMGroup(ctx, resourceGroupName, SQLVirtualMachineGroupName) + return +} + +// Update updates a SQL virtual machine. +// Parameters: +// resourceGroupName - name of the resource group that contains the resource. You can obtain this value from +// the Azure Resource Manager API or the portal. +// SQLVirtualMachineName - name of the SQL virtual machine. +// parameters - the SQL virtual machine. +func (client SQLVirtualMachinesClient) Update(ctx context.Context, resourceGroupName string, SQLVirtualMachineName string, parameters Update) (result SQLVirtualMachinesUpdateFutureType, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SQLVirtualMachinesClient.Update") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, SQLVirtualMachineName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "Update", nil, "Failure preparing request") + return + } + + result, err = client.UpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "sqlvirtualmachine.SQLVirtualMachinesClient", "Update", result.Response(), "Failure sending request") + return + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client SQLVirtualMachinesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, SQLVirtualMachineName string, parameters Update) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "sqlVirtualMachineName": autorest.Encode("path", SQLVirtualMachineName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/{sqlVirtualMachineName}", 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 SQLVirtualMachinesClient) UpdateSender(req *http.Request) (future SQLVirtualMachinesUpdateFutureType, err error) { + var resp *http.Response + resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) + 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 SQLVirtualMachinesClient) UpdateResponder(resp *http.Response) (result SQLVirtualMachine, 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/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/version.go new file mode 100644 index 000000000000..c836cadd73d8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine/version.go @@ -0,0 +1,30 @@ +package sqlvirtualmachine + +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 + " sqlvirtualmachine/2017-03-01-preview" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return version.Number +} diff --git a/vendor/modules.txt b/vendor/modules.txt index b21d01281da5..a1eb218d76de 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -68,6 +68,7 @@ github.com/Azure/azure-sdk-for-go/services/preview/security/mgmt/v1.0/security github.com/Azure/azure-sdk-for-go/services/preview/servicebus/mgmt/2018-01-01-preview/servicebus github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2017-03-01-preview/sql github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql +github.com/Azure/azure-sdk-for-go/services/preview/sqlvirtualmachine/mgmt/2017-03-01-preview/sqlvirtualmachine github.com/Azure/azure-sdk-for-go/services/privatedns/mgmt/2018-09-01/privatedns github.com/Azure/azure-sdk-for-go/services/provisioningservices/mgmt/2018-01-22/iothub github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices diff --git a/website/azurerm.erb b/website/azurerm.erb index 65a57c6cdd94..c7eecd4da903 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -1202,6 +1202,10 @@ azurerm_mssql_elasticpool +