diff --git a/builder/azure/dtl/TestVirtualMachineDeployment05.approved.txt b/builder/azure/dtl/TestVirtualMachineDeployment05.approved.txt new file mode 100644 index 000000000..31532ddbe --- /dev/null +++ b/builder/azure/dtl/TestVirtualMachineDeployment05.approved.txt @@ -0,0 +1,118 @@ +{ + "$schema": "http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json", + "contentVersion": "1.0.0.0", + "parameters": { + "adminPassword": { + "type": "string" + }, + "adminUsername": { + "type": "string" + }, + "dnsNameForPublicIP": { + "type": "string" + }, + "osDiskName": { + "type": "string" + }, + "storageAccountBlobEndpoint": { + "type": "string" + }, + "vmName": { + "type": "string" + }, + "vmSize": { + "type": "string" + } + }, + "resources": [ + { + "apiVersion": "[variables('apiVersion')]", + "dependsOn": [], + "location": "[variables('location')]", + "name": "[variables('nicName')]", + "properties": { + "ipConfigurations": [ + { + "name": "ipconfig", + "properties": { + "privateIPAllocationMethod": "Dynamic", + "subnet": { + "id": "[variables('subnetRef')]" + } + } + } + ] + }, + "type": "Microsoft.Network/networkInterfaces" + }, + { + "apiVersion": "[variables('apiVersion')]", + "dependsOn": [ + "[concat('Microsoft.Network/networkInterfaces/', variables('nicName'))]" + ], + "location": "[variables('location')]", + "name": "[parameters('vmName')]", + "properties": { + "diagnosticsProfile": { + "bootDiagnostics": { + "enabled": false + } + }, + "hardwareProfile": { + "vmSize": "[parameters('vmSize')]" + }, + "networkProfile": { + "networkInterfaces": [ + { + "id": "[resourceId('Microsoft.Network/networkInterfaces', variables('nicName'))]" + } + ] + }, + "osProfile": { + "adminPassword": "[parameters('adminPassword')]", + "adminUsername": "[parameters('adminUsername')]", + "computerName": "[parameters('vmName')]", + "linuxConfiguration": { + "ssh": { + "publicKeys": [ + { + "keyData": "", + "path": "[variables('sshKeyPath')]" + } + ] + } + } + }, + "storageProfile": { + "osDisk": { + "caching": "ReadWrite", + "createOption": "FromImage", + "image": { + "uri": "https://localhost/custom.vhd" + }, + "name": "[parameters('osDiskName')]", + "osType": "Linux", + "vhd": { + "uri": "[concat(parameters('storageAccountBlobEndpoint'),variables('vmStorageAccountContainerName'),'/', parameters('osDiskName'),'.vhd')]" + } + } + } + }, + "type": "Microsoft.Compute/virtualMachines" + } + ], + "variables": { + "addressPrefix": "10.0.0.0/16", + "apiVersion": "2015-06-15", + "location": "[resourceGroup().location]", + "publicIPAddressType": "Dynamic", + "sshKeyPath": "[concat('/home/',parameters('adminUsername'),'/.ssh/authorized_keys')]", + "subnetAddressPrefix": "10.0.0.0/24", + "subnetName": "ignore", + "subnetRef": "[concat(variables('vnetID'),'/subnets/',variables('subnetName'))]", + "virtualNetworkName": "ignore", + "virtualNetworkResourceGroup": "ignore", + "vmStorageAccountContainerName": "images", + "vnetID": "[resourceId(variables('virtualNetworkResourceGroup'), 'Microsoft.Network/virtualNetworks', variables('virtualNetworkName'))]" + } +} \ No newline at end of file diff --git a/builder/azure/dtl/WindowsMixAndMatch.json b/builder/azure/dtl/WindowsMixAndMatch.json new file mode 100644 index 000000000..1457d4a48 --- /dev/null +++ b/builder/azure/dtl/WindowsMixAndMatch.json @@ -0,0 +1,65 @@ +{ + "variables": { + "client_id": "{{env `client_id`}}", + "client_secret": "{{env `client_secret`}}", + "tenant_id": "{{env `tenant_id`}}", + "subscription_id": "{{env `subscription_id`}}", + "lab_name": "NewpackerRG", + "resource_group_name": "NewPackerRG", + "vm_name": "win21" + }, + "builders": [ + { + "type": "azure-dtl", + "client_id": "{{user `client_id`}}", + "client_secret": "{{user `client_secret`}}", + "tenant_id": "{{user `tenant_id`}}", + "subscription_id": "{{user `subscription_id`}}", + "managed_image_resource_group_name": "NewPackerRG", + "managed_image_name": "PackerImage2", + "os_type": "Windows", + "image_publisher": "MicrosoftWindowsDesktop", + "image_offer": "Windows-10", + "image_sku": "19h1-ent", + "azure_tags": { + "dept": "Engineering", + "task": "Image deployment" + }, + "dtl_artifacts": [ + { + "artifact_name": "windows-7zip" + }, + { + "artifact_name": "windows-mongodb" + } + ], + "lab_name": "{{user `lab_name`}}", + "vm_name": "{{user `vm_name`}}", + "lab_virtual_network_name": "dtlnewpackerrg", + "lab_resource_group_name": "{{user `resource_group_name`}}", + "lab_subnet_name": "dtlnewpackerrgSubnet", + "location": "Central US", + "vm_size": "Standard_DS2_v2" + } + ], + "provisioners": [ + { + "type": "azure-dtlartifact", + "client_id": "{{user `client_id`}}", + "client_secret": "{{user `client_secret`}}", + "tenant_id": "{{user `tenant_id`}}", + "subscription_id": "{{user `subscription_id`}}", + "lab_name": "{{user `lab_name`}}", + "resource_group_name": "{{user `resource_group_name`}}", + "vm_name": "{{user `vm_name`}}", + "dtl_artifacts": [ + { + "artifact_name": "windows-chrome" + }, + { + "artifact_name": "windows-azurepowershell" + } + ] + } + ] +} \ No newline at end of file diff --git a/builder/azure/dtl/WindowsSimple.json b/builder/azure/dtl/WindowsSimple.json new file mode 100644 index 000000000..446c41c33 --- /dev/null +++ b/builder/azure/dtl/WindowsSimple.json @@ -0,0 +1,37 @@ +{ + "variables": { + "client_id": "{{env `client_id`}}", + "client_secret": "{{env `client_secret`}}", + "tenant_id": "{{env `tenant_id`}}", + "subscription_id": "{{env `subscription_id`}}", + "lab_name": "NewpackerRG", + "resource_group_name": "NewPackerRG", + "vm_name": "win18" + }, + "builders": [ + { + "type": "azure-dtl", + "client_id": "{{user `client_id`}}", + "client_secret": "{{user `client_secret`}}", + "tenant_id": "{{user `tenant_id`}}", + "subscription_id": "{{user `subscription_id`}}", + "managed_image_resource_group_name": "NewPackerRG", + "managed_image_name": "PackerImage2", + "os_type": "Windows", + "image_publisher": "MicrosoftWindowsDesktop", + "image_offer": "Windows-10", + "image_sku": "19h1-ent", + "azure_tags": { + "dept": "Engineering", + "task": "Image deployment" + }, + "lab_name": "{{user `lab_name`}}", + "vm_name": "{{user `vm_name`}}", + "lab_virtual_network_name": "dtlnewpackerrg", + "lab_resource_group_name": "{{user `resource_group_name`}}", + "lab_subnet_name": "dtlnewpackerrgSubnet", + "location": "Central US", + "vm_size": "Standard_DS2_v2" + } + ] +} \ No newline at end of file diff --git a/builder/azure/dtl/acceptancetest.json b/builder/azure/dtl/acceptancetest.json new file mode 100644 index 000000000..d1618e00d --- /dev/null +++ b/builder/azure/dtl/acceptancetest.json @@ -0,0 +1,72 @@ +{ + "$schema": "http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "name": { + "type": "string", + "defaultValue": "packer-acceptance-test" + }, + "regionId": { + "type": "string", + "defaultValue": "southcentralus" + } + }, + "resources": [ + { + "apiVersion": "2018-10-15-preview", + "name": "[parameters('name')]", + "type": "Microsoft.DevTestLab/labs", + "location": "[parameters('regionId')]", + "tags": { + "env": "packer" + }, + "properties": { + "labStorageType": "Premium" + }, + "resources": [ + { + "apiVersion": "2018-10-15-preview", + "name": "LabVmsShutdown", + "location": "[parameters('regionId')]", + "type": "schedules", + "dependsOn": [ + "[resourceId('Microsoft.DevTestLab/labs', parameters('name'))]" + ], + "properties": { + "status": "Enabled", + "timeZoneId": "Pacific Standard Time", + "dailyRecurrence": { + "time": "1900" + }, + "taskType": "LabVmsShutdownTask", + "notificationSettings": { + "status": "Disabled", + "timeInMinutes": 30 + } + } + }, + { + "apiVersion": "2018-10-15-preview", + "name": "[concat('Dtl', parameters('name'))]", + "type": "virtualNetworks", + "location": "[parameters('regionId')]", + "dependsOn": [ + "[resourceId('Microsoft.DevTestLab/labs', parameters('name'))]" + ] + }, + { + "apiVersion": "2018-10-15-preview", + "name": "Public Environment Repo", + "type": "artifactSources", + "location": "[parameters('regionId')]", + "dependsOn": [ + "[resourceId('Microsoft.DevTestLab/labs', parameters('name'))]" + ], + "properties": { + "status": "Enabled" + } + } + ] + } + ] +} \ No newline at end of file diff --git a/builder/azure/dtl/artifact.go b/builder/azure/dtl/artifact.go new file mode 100644 index 000000000..0035e2d00 --- /dev/null +++ b/builder/azure/dtl/artifact.go @@ -0,0 +1,199 @@ +package dtl + +import ( + "bytes" + "fmt" + "net/url" + "path" + "strings" +) + +const ( + BuilderId = "Azure.ResourceManagement.VMImage" +) + +type AdditionalDiskArtifact struct { + AdditionalDiskUri string + AdditionalDiskUriReadOnlySas string +} + +type Artifact struct { + // OS type: Linux, Windows + OSType string + + // VHD + StorageAccountLocation string + OSDiskUri string + TemplateUri string + OSDiskUriReadOnlySas string + TemplateUriReadOnlySas string + + // Managed Image + ManagedImageResourceGroupName string + ManagedImageName string + ManagedImageLocation string + ManagedImageId string + ManagedImageOSDiskSnapshotName string + ManagedImageDataDiskSnapshotPrefix string + + // Additional Disks + AdditionalDisks *[]AdditionalDiskArtifact +} + +func NewManagedImageArtifact(osType, resourceGroup, name, location, id string) (*Artifact, error) { + return &Artifact{ + ManagedImageResourceGroupName: resourceGroup, + ManagedImageName: name, + ManagedImageLocation: location, + ManagedImageId: id, + OSType: osType, + }, nil +} + +func NewArtifact(template *CaptureTemplate, getSasUrl func(name string) string, osType string) (*Artifact, error) { + if template == nil { + return nil, fmt.Errorf("nil capture template") + } + + if len(template.Resources) != 1 { + return nil, fmt.Errorf("malformed capture template, expected one resource") + } + + vhdUri, err := url.Parse(template.Resources[0].Properties.StorageProfile.OSDisk.Image.Uri) + if err != nil { + return nil, err + } + + templateUri, err := storageUriToTemplateUri(vhdUri) + if err != nil { + return nil, err + } + + var additional_disks *[]AdditionalDiskArtifact + if template.Resources[0].Properties.StorageProfile.DataDisks != nil { + data_disks := make([]AdditionalDiskArtifact, len(template.Resources[0].Properties.StorageProfile.DataDisks)) + for i, additionaldisk := range template.Resources[0].Properties.StorageProfile.DataDisks { + additionalVhdUri, err := url.Parse(additionaldisk.Image.Uri) + if err != nil { + return nil, err + } + data_disks[i].AdditionalDiskUri = additionalVhdUri.String() + data_disks[i].AdditionalDiskUriReadOnlySas = getSasUrl(getStorageUrlPath(additionalVhdUri)) + } + additional_disks = &data_disks + } + + return &Artifact{ + OSType: osType, + OSDiskUri: vhdUri.String(), + OSDiskUriReadOnlySas: getSasUrl(getStorageUrlPath(vhdUri)), + TemplateUri: templateUri.String(), + TemplateUriReadOnlySas: getSasUrl(getStorageUrlPath(templateUri)), + + AdditionalDisks: additional_disks, + + StorageAccountLocation: template.Resources[0].Location, + }, nil +} + +func getStorageUrlPath(u *url.URL) string { + parts := strings.Split(u.Path, "/") + return strings.Join(parts[3:], "/") +} + +func storageUriToTemplateUri(su *url.URL) (*url.URL, error) { + // packer-osDisk.4085bb15-3644-4641-b9cd-f575918640b4.vhd -> 4085bb15-3644-4641-b9cd-f575918640b4 + filename := path.Base(su.Path) + parts := strings.Split(filename, ".") + + if len(parts) < 3 { + return nil, fmt.Errorf("malformed URL") + } + + // packer-osDisk.4085bb15-3644-4641-b9cd-f575918640b4.vhd -> packer + prefixParts := strings.Split(parts[0], "-") + prefix := strings.Join(prefixParts[:len(prefixParts)-1], "-") + + templateFilename := fmt.Sprintf("%s-vmTemplate.%s.json", prefix, parts[1]) + + // https://storage.blob.core.windows.net/system/Microsoft.Compute/Images/images/packer-osDisk.4085bb15-3644-4641-b9cd-f575918640b4.vhd" + // -> + // https://storage.blob.core.windows.net/system/Microsoft.Compute/Images/images/packer-vmTemplate.4085bb15-3644-4641-b9cd-f575918640b4.json" + return url.Parse(strings.Replace(su.String(), filename, templateFilename, 1)) +} + +func (a *Artifact) isManagedImage() bool { + return a.ManagedImageResourceGroupName != "" +} + +func (*Artifact) BuilderId() string { + return BuilderId +} + +func (*Artifact) Files() []string { + return []string{} +} + +func (a *Artifact) Id() string { + if a.OSDiskUri != "" { + return a.OSDiskUri + } + return a.ManagedImageId +} + +func (a *Artifact) State(name string) interface{} { + switch name { + case "atlas.artifact.metadata": + return a.stateAtlasMetadata() + default: + return nil + } +} + +func (a *Artifact) String() string { + var buf bytes.Buffer + + buf.WriteString(fmt.Sprintf("%s:\n\n", a.BuilderId())) + buf.WriteString(fmt.Sprintf("OSType: %s\n", a.OSType)) + if a.isManagedImage() { + buf.WriteString(fmt.Sprintf("ManagedImageResourceGroupName: %s\n", a.ManagedImageResourceGroupName)) + buf.WriteString(fmt.Sprintf("ManagedImageName: %s\n", a.ManagedImageName)) + buf.WriteString(fmt.Sprintf("ManagedImageId: %s\n", a.ManagedImageId)) + buf.WriteString(fmt.Sprintf("ManagedImageLocation: %s\n", a.ManagedImageLocation)) + if a.ManagedImageOSDiskSnapshotName != "" { + buf.WriteString(fmt.Sprintf("ManagedImageOSDiskSnapshotName: %s\n", a.ManagedImageOSDiskSnapshotName)) + } + if a.ManagedImageDataDiskSnapshotPrefix != "" { + buf.WriteString(fmt.Sprintf("ManagedImageDataDiskSnapshotPrefix: %s\n", a.ManagedImageDataDiskSnapshotPrefix)) + } + } else { + buf.WriteString(fmt.Sprintf("StorageAccountLocation: %s\n", a.StorageAccountLocation)) + buf.WriteString(fmt.Sprintf("OSDiskUri: %s\n", a.OSDiskUri)) + buf.WriteString(fmt.Sprintf("OSDiskUriReadOnlySas: %s\n", a.OSDiskUriReadOnlySas)) + buf.WriteString(fmt.Sprintf("TemplateUri: %s\n", a.TemplateUri)) + buf.WriteString(fmt.Sprintf("TemplateUriReadOnlySas: %s\n", a.TemplateUriReadOnlySas)) + if a.AdditionalDisks != nil { + for i, additionaldisk := range *a.AdditionalDisks { + buf.WriteString(fmt.Sprintf("AdditionalDiskUri (datadisk-%d): %s\n", i+1, additionaldisk.AdditionalDiskUri)) + buf.WriteString(fmt.Sprintf("AdditionalDiskUriReadOnlySas (datadisk-%d): %s\n", i+1, additionaldisk.AdditionalDiskUriReadOnlySas)) + } + } + } + + return buf.String() +} + +func (*Artifact) Destroy() error { + return nil +} + +func (a *Artifact) stateAtlasMetadata() interface{} { + metadata := make(map[string]string) + metadata["StorageAccountLocation"] = a.StorageAccountLocation + metadata["OSDiskUri"] = a.OSDiskUri + metadata["OSDiskUriReadOnlySas"] = a.OSDiskUriReadOnlySas + metadata["TemplateUri"] = a.TemplateUri + metadata["TemplateUriReadOnlySas"] = a.TemplateUriReadOnlySas + + return metadata +} diff --git a/builder/azure/dtl/azure_client.go b/builder/azure/dtl/azure_client.go new file mode 100644 index 000000000..eefc89d45 --- /dev/null +++ b/builder/azure/dtl/azure_client.go @@ -0,0 +1,211 @@ +package dtl + +import ( + "encoding/json" + "fmt" + "math" + "net/http" + "os" + "strconv" + "time" + + "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute" + newCompute "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-03-01/compute" + dtl "github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl" + "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-01-01/network" + "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-02-01/resources" + armStorage "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2017-10-01/storage" + "github.com/Azure/azure-sdk-for-go/storage" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/adal" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/packer/builder/azure/common" + "github.com/hashicorp/packer/helper/useragent" +) + +const ( + EnvPackerLogAzureMaxLen = "PACKER_LOG_AZURE_MAXLEN" +) + +type AzureClient struct { + storage.BlobStorageClient + resources.DeploymentsClient + resources.DeploymentOperationsClient + resources.GroupsClient + network.PublicIPAddressesClient + network.InterfacesClient + network.SubnetsClient + network.VirtualNetworksClient + compute.ImagesClient + compute.VirtualMachinesClient + common.VaultClient + armStorage.AccountsClient + compute.DisksClient + compute.SnapshotsClient + newCompute.GalleryImageVersionsClient + newCompute.GalleryImagesClient + + InspectorMaxLength int + Template *CaptureTemplate + LastError azureErrorResponse + VaultClientDelete common.VaultClient + DtlLabsClient dtl.LabsClient + DtlVirtualMachineClient dtl.VirtualMachinesClient + DtlEnvironmentsClient dtl.EnvironmentsClient + DtlCustomImageClient dtl.CustomImagesClient + DtlVirtualNetworksClient dtl.VirtualNetworksClient +} + +func getCaptureResponse(body string) *CaptureTemplate { + var operation CaptureOperation + err := json.Unmarshal([]byte(body), &operation) + if err != nil { + return nil + } + + if operation.Properties != nil && operation.Properties.Output != nil { + return operation.Properties.Output + } + + return nil +} + +// HACK(chrboum): This method is a hack. It was written to work around this issue +// (https://github.com/Azure/azure-sdk-for-go/issues/307) and to an extent this +// issue (https://github.com/Azure/azure-rest-api-specs/issues/188). +// +// Capturing a VM is a long running operation that requires polling. There are +// couple different forms of polling, and the end result of a poll operation is +// discarded by the SDK. It is expected that any discarded data can be re-fetched, +// so discarding it has minimal impact. Unfortunately, there is no way to re-fetch +// the template returned by a capture call that I am aware of. +// +// If the second issue were fixed the VM ID would be included when GET'ing a VM. The +// VM ID could be used to locate the captured VHD, and captured template. +// Unfortunately, the VM ID is not included so this method cannot be used either. +// +// This code captures the template and saves it to the client (the AzureClient type). +// It expects that the capture API is called only once, or rather you only care that the +// last call's value is important because subsequent requests are not persisted. There +// is no care given to multiple threads writing this value because for our use case +// it does not matter. +func templateCapture(client *AzureClient) autorest.RespondDecorator { + return func(r autorest.Responder) autorest.Responder { + return autorest.ResponderFunc(func(resp *http.Response) error { + body, bodyString := handleBody(resp.Body, math.MaxInt64) + resp.Body = body + + captureTemplate := getCaptureResponse(bodyString) + if captureTemplate != nil { + client.Template = captureTemplate + } + + return r.Respond(resp) + }) + } +} + +func errorCapture(client *AzureClient) autorest.RespondDecorator { + return func(r autorest.Responder) autorest.Responder { + return autorest.ResponderFunc(func(resp *http.Response) error { + body, bodyString := handleBody(resp.Body, math.MaxInt64) + resp.Body = body + + errorResponse := newAzureErrorResponse(bodyString) + if errorResponse != nil { + client.LastError = *errorResponse + } + + return r.Respond(resp) + }) + } +} + +// WAITING(chrboum): I have logged https://github.com/Azure/azure-sdk-for-go/issues/311 to get this +// method included in the SDK. It has been accepted, and I'll cut over to the official way +// once it ships. +func byConcatDecorators(decorators ...autorest.RespondDecorator) autorest.RespondDecorator { + return func(r autorest.Responder) autorest.Responder { + return autorest.DecorateResponder(r, decorators...) + } +} + +func NewAzureClient(subscriptionID, resourceGroupName string, + cloud *azure.Environment, SharedGalleryTimeout time.Duration, PollingDuration time.Duration, + servicePrincipalToken *adal.ServicePrincipalToken) (*AzureClient, error) { + + var azureClient = &AzureClient{} + + maxlen := getInspectorMaxLength() + + azureClient.DtlVirtualMachineClient = dtl.NewVirtualMachinesClientWithBaseURI(cloud.ResourceManagerEndpoint, subscriptionID) + azureClient.DtlVirtualMachineClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) + azureClient.DtlVirtualMachineClient.RequestInspector = withInspection(maxlen) + azureClient.DtlVirtualMachineClient.ResponseInspector = byConcatDecorators(byInspecting(maxlen), templateCapture(azureClient), errorCapture(azureClient)) + azureClient.DtlVirtualMachineClient.UserAgent = fmt.Sprintf("%s %s", useragent.String(), azureClient.DtlVirtualMachineClient.UserAgent) + azureClient.DtlVirtualMachineClient.Client.PollingDuration = PollingDuration + + azureClient.DtlEnvironmentsClient = dtl.NewEnvironmentsClientWithBaseURI(cloud.ResourceManagerEndpoint, subscriptionID) + azureClient.DtlEnvironmentsClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) + azureClient.DtlEnvironmentsClient.RequestInspector = withInspection(maxlen) + azureClient.DtlEnvironmentsClient.ResponseInspector = byConcatDecorators(byInspecting(maxlen), templateCapture(azureClient), errorCapture(azureClient)) + azureClient.DtlEnvironmentsClient.UserAgent = fmt.Sprintf("%s %s", useragent.String(), azureClient.DtlEnvironmentsClient.UserAgent) + azureClient.DtlEnvironmentsClient.Client.PollingDuration = PollingDuration + + azureClient.DtlLabsClient = dtl.NewLabsClientWithBaseURI(cloud.ResourceManagerEndpoint, subscriptionID) + azureClient.DtlLabsClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) + azureClient.DtlLabsClient.RequestInspector = withInspection(maxlen) + azureClient.DtlLabsClient.ResponseInspector = byConcatDecorators(byInspecting(maxlen), templateCapture(azureClient), errorCapture(azureClient)) + azureClient.DtlLabsClient.UserAgent = fmt.Sprintf("%s %s", useragent.String(), azureClient.DtlLabsClient.UserAgent) + azureClient.DtlLabsClient.Client.PollingDuration = PollingDuration + + azureClient.DtlCustomImageClient = dtl.NewCustomImagesClientWithBaseURI(cloud.ResourceManagerEndpoint, subscriptionID) + azureClient.DtlCustomImageClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) + azureClient.DtlCustomImageClient.RequestInspector = withInspection(maxlen) + azureClient.DtlCustomImageClient.ResponseInspector = byConcatDecorators(byInspecting(maxlen), templateCapture(azureClient), errorCapture(azureClient)) + azureClient.DtlCustomImageClient.UserAgent = fmt.Sprintf("%s %s", useragent.String(), azureClient.DtlCustomImageClient.UserAgent) + azureClient.DtlCustomImageClient.PollingDuration = autorest.DefaultPollingDuration + azureClient.DtlCustomImageClient.Client.PollingDuration = PollingDuration + + azureClient.DtlVirtualNetworksClient = dtl.NewVirtualNetworksClientWithBaseURI(cloud.ResourceManagerEndpoint, subscriptionID) + azureClient.DtlVirtualNetworksClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) + azureClient.DtlVirtualNetworksClient.RequestInspector = withInspection(maxlen) + azureClient.DtlVirtualNetworksClient.ResponseInspector = byConcatDecorators(byInspecting(maxlen), templateCapture(azureClient), errorCapture(azureClient)) + azureClient.DtlVirtualNetworksClient.UserAgent = fmt.Sprintf("%s %s", useragent.String(), azureClient.DtlVirtualNetworksClient.UserAgent) + azureClient.DtlVirtualNetworksClient.Client.PollingDuration = PollingDuration + + azureClient.GalleryImageVersionsClient = newCompute.NewGalleryImageVersionsClientWithBaseURI(cloud.ResourceManagerEndpoint, subscriptionID) + azureClient.GalleryImageVersionsClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) + azureClient.GalleryImageVersionsClient.RequestInspector = withInspection(maxlen) + azureClient.GalleryImageVersionsClient.ResponseInspector = byConcatDecorators(byInspecting(maxlen), errorCapture(azureClient)) + azureClient.GalleryImageVersionsClient.UserAgent = fmt.Sprintf("%s %s", useragent.String(), azureClient.GalleryImageVersionsClient.UserAgent) + azureClient.GalleryImageVersionsClient.Client.PollingDuration = SharedGalleryTimeout + azureClient.GalleryImageVersionsClient.Client.PollingDuration = PollingDuration + + azureClient.GalleryImagesClient = newCompute.NewGalleryImagesClientWithBaseURI(cloud.ResourceManagerEndpoint, subscriptionID) + azureClient.GalleryImagesClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) + azureClient.GalleryImagesClient.RequestInspector = withInspection(maxlen) + azureClient.GalleryImagesClient.ResponseInspector = byConcatDecorators(byInspecting(maxlen), errorCapture(azureClient)) + azureClient.GalleryImagesClient.UserAgent = fmt.Sprintf("%s %s", useragent.String(), azureClient.GalleryImagesClient.UserAgent) + azureClient.GalleryImagesClient.Client.PollingDuration = PollingDuration + + return azureClient, nil +} + +func getInspectorMaxLength() int64 { + value, ok := os.LookupEnv(EnvPackerLogAzureMaxLen) + if !ok { + return math.MaxInt64 + } + + i, err := strconv.ParseInt(value, 10, 64) + if err != nil { + return 0 + } + + if i < 0 { + return 0 + } + + return i +} diff --git a/builder/azure/dtl/azure_error_response.go b/builder/azure/dtl/azure_error_response.go new file mode 100644 index 000000000..2d92f101e --- /dev/null +++ b/builder/azure/dtl/azure_error_response.go @@ -0,0 +1,63 @@ +package dtl + +import ( + "bytes" + "encoding/json" + "fmt" +) + +type azureErrorDetails struct { + Code string `json:"code"` + Message string `json:"message"` + Details []azureErrorDetails `json:"details"` +} + +type azureErrorResponse struct { + ErrorDetails azureErrorDetails `json:"error"` +} + +func newAzureErrorResponse(s string) *azureErrorResponse { + var errorResponse azureErrorResponse + err := json.Unmarshal([]byte(s), &errorResponse) + if err == nil { + return &errorResponse + } + + return nil +} + +func (e *azureErrorDetails) isEmpty() bool { + return e.Code == "" +} + +func (e *azureErrorResponse) Error() string { + var buf bytes.Buffer + //buf.WriteString("-=-=- ERROR -=-=-") + formatAzureErrorResponse(e.ErrorDetails, &buf, "") + //buf.WriteString("-=-=- ERROR -=-=-") + return buf.String() +} + +// format a Azure Error Response by recursing through the JSON structure. +// +// Errors may contain nested errors, which are JSON documents that have been +// serialized and escaped. Keep following this nesting all the way down... +func formatAzureErrorResponse(error azureErrorDetails, buf *bytes.Buffer, indent string) { + if error.isEmpty() { + return + } + + buf.WriteString(fmt.Sprintf("ERROR: %s-> %s : %s\n", indent, error.Code, error.Message)) + for _, x := range error.Details { + newIndent := fmt.Sprintf("%s ", indent) + + var aer azureErrorResponse + err := json.Unmarshal([]byte(x.Message), &aer) + if err == nil { + buf.WriteString(fmt.Sprintf("ERROR: %s-> %s\n", newIndent, x.Code)) + formatAzureErrorResponse(aer.ErrorDetails, buf, newIndent) + } else { + buf.WriteString(fmt.Sprintf("ERROR: %s-> %s : %s\n", newIndent, x.Code, x.Message)) + } + } +} diff --git a/builder/azure/dtl/azure_error_response_test.TestAzureErrorNestedShouldFormat.approved.txt b/builder/azure/dtl/azure_error_response_test.TestAzureErrorNestedShouldFormat.approved.txt new file mode 100644 index 000000000..39d4deeec --- /dev/null +++ b/builder/azure/dtl/azure_error_response_test.TestAzureErrorNestedShouldFormat.approved.txt @@ -0,0 +1,4 @@ +ERROR: -> DeploymentFailed : At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/arm-debug for usage details. +ERROR: -> BadRequest +ERROR: -> InvalidRequestFormat : Cannot parse the request. +ERROR: -> InvalidJson : Error converting value "playground" to type 'Microsoft.WindowsAzure.Networking.Nrp.Frontend.Contract.Csm.Public.IpAllocationMethod'. Path 'properties.publicIPAllocationMethod', line 1, position 130. diff --git a/builder/azure/dtl/azure_error_response_test.TestAzureErrorSimpleShouldFormat.approved.txt b/builder/azure/dtl/azure_error_response_test.TestAzureErrorSimpleShouldFormat.approved.txt new file mode 100644 index 000000000..4b4834c62 --- /dev/null +++ b/builder/azure/dtl/azure_error_response_test.TestAzureErrorSimpleShouldFormat.approved.txt @@ -0,0 +1 @@ +ERROR: -> ResourceNotFound : The Resource 'Microsoft.Compute/images/PackerUbuntuImage' under resource group 'packer-test00' was not found. diff --git a/builder/azure/dtl/azure_error_response_test.go b/builder/azure/dtl/azure_error_response_test.go new file mode 100644 index 000000000..bc8a82f15 --- /dev/null +++ b/builder/azure/dtl/azure_error_response_test.go @@ -0,0 +1,77 @@ +package dtl + +import ( + "strings" + "testing" + + approvaltests "github.com/approvals/go-approval-tests" + "github.com/hashicorp/packer/common/json" +) + +const AzureErrorSimple = `{"error":{"code":"ResourceNotFound","message":"The Resource 'Microsoft.Compute/images/PackerUbuntuImage' under resource group 'packer-test00' was not found."}}` +const AzureErrorNested = `{"status":"Failed","error":{"code":"DeploymentFailed","message":"At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/arm-debug for usage details.","details":[{"code":"BadRequest","message":"{\r\n \"error\": {\r\n \"code\": \"InvalidRequestFormat\",\r\n \"message\": \"Cannot parse the request.\",\r\n \"details\": [\r\n {\r\n \"code\": \"InvalidJson\",\r\n \"message\": \"Error converting value \\\"playground\\\" to type 'Microsoft.WindowsAzure.Networking.Nrp.Frontend.Contract.Csm.Public.IpAllocationMethod'. Path 'properties.publicIPAllocationMethod', line 1, position 130.\"\r\n }\r\n ]\r\n }\r\n}"}]}}` + +func TestAzureErrorSimpleShouldUnmarshal(t *testing.T) { + var azureErrorResponse azureErrorResponse + err := json.Unmarshal([]byte(AzureErrorSimple), &azureErrorResponse) + if err != nil { + t.Fatal(err) + } + + if azureErrorResponse.ErrorDetails.Code != "ResourceNotFound" { + t.Errorf("Error.Code") + } + if azureErrorResponse.ErrorDetails.Message != "The Resource 'Microsoft.Compute/images/PackerUbuntuImage' under resource group 'packer-test00' was not found." { + t.Errorf("Error.Message") + } +} + +func TestAzureErrorNestedShouldUnmarshal(t *testing.T) { + var azureError azureErrorResponse + err := json.Unmarshal([]byte(AzureErrorNested), &azureError) + if err != nil { + t.Fatal(err) + } + + if azureError.ErrorDetails.Code != "DeploymentFailed" { + t.Errorf("Error.Code") + } + if !strings.HasPrefix(azureError.ErrorDetails.Message, "At least one resource deployment operation failed") { + t.Errorf("Error.Message") + } +} + +func TestAzureErrorEmptyShouldFormat(t *testing.T) { + var aer azureErrorResponse + s := aer.Error() + + if s != "" { + t.Fatalf("Expected \"\", but got %s", aer.Error()) + } +} + +func TestAzureErrorSimpleShouldFormat(t *testing.T) { + var azureErrorResponse azureErrorResponse + err := json.Unmarshal([]byte(AzureErrorSimple), &azureErrorResponse) + if err != nil { + t.Fatal(err) + } + + err = approvaltests.VerifyString(t, azureErrorResponse.Error()) + if err != nil { + t.Fatal(err) + } +} + +func TestAzureErrorNestedShouldFormat(t *testing.T) { + var azureErrorResponse azureErrorResponse + err := json.Unmarshal([]byte(AzureErrorNested), &azureErrorResponse) + if err != nil { + t.Fatal(err) + } + + err = approvaltests.VerifyString(t, azureErrorResponse.Error()) + if err != nil { + t.Fatal(err) + } +} diff --git a/builder/azure/dtl/builder.go b/builder/azure/dtl/builder.go new file mode 100644 index 000000000..272fcfa65 --- /dev/null +++ b/builder/azure/dtl/builder.go @@ -0,0 +1,368 @@ +package dtl + +import ( + "context" + "errors" + "fmt" + "log" + "os" + "runtime" + "strings" + + dtl "github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl" + + "github.com/Azure/go-autorest/autorest/adal" + "github.com/dgrijalva/jwt-go" + "github.com/hashicorp/hcl/v2/hcldec" + packerAzureCommon "github.com/hashicorp/packer/builder/azure/common" + "github.com/hashicorp/packer/builder/azure/common/constants" + "github.com/hashicorp/packer/builder/azure/common/lin" + packerCommon "github.com/hashicorp/packer/common" + "github.com/hashicorp/packer/helper/communicator" + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" +) + +type Builder struct { + config *Config + stateBag multistep.StateBag + runner multistep.Runner +} + +const ( + DefaultSasBlobContainer = "system/Microsoft.Compute" + DefaultSecretName = "packerKeyVaultSecret" +) + +func (b *Builder) ConfigSpec() hcldec.ObjectSpec { return b.config.FlatMapstructure().HCL2Spec() } + +func (b *Builder) Prepare(raws ...interface{}) ([]string, []string, error) { + c, warnings, errs := newConfig(raws...) + if errs != nil { + return nil, warnings, errs + } + + b.config = c + + b.stateBag = new(multistep.BasicStateBag) + b.configureStateBag(b.stateBag) + b.setTemplateParameters(b.stateBag) + + return nil, warnings, errs +} + +func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) { + + ui.Say("Running builder ...") + + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + // FillParameters function captures authType and sets defaults. + err := b.config.ClientConfig.FillParameters() + if err != nil { + return nil, err + } + + log.Print(":: Configuration") + packerAzureCommon.DumpConfig(b.config, func(s string) { log.Print(s) }) + + b.stateBag.Put("hook", hook) + b.stateBag.Put(constants.Ui, ui) + + spnCloud, err := b.getServicePrincipalToken(ui.Say) + if err != nil { + return nil, err + } + + ui.Message("Creating Azure Resource Manager (ARM) client ...") + azureClient, err := NewAzureClient( + b.config.ClientConfig.SubscriptionID, + b.config.LabResourceGroupName, + b.config.ClientConfig.CloudEnvironment(), + b.config.SharedGalleryTimeout, + b.config.PollingDurationTimeout, + spnCloud) + + if err != nil { + return nil, err + } + + resolver := newResourceResolver(azureClient) + if err := resolver.Resolve(b.config); err != nil { + return nil, err + } + if b.config.ClientConfig.ObjectID == "" { + b.config.ClientConfig.ObjectID = getObjectIdFromToken(ui, spnCloud) + } else { + ui.Message("You have provided Object_ID which is no longer needed, azure packer builder determines this dynamically from the authentication token") + } + + if b.config.ClientConfig.ObjectID == "" && b.config.OSType != constants.Target_Linux { + return nil, fmt.Errorf("could not determine the ObjectID for the user, which is required for Windows builds") + } + + if b.config.isManagedImage() { + // If a managed image already exists it cannot be overwritten. We need to delete it if the user has provided -force flag + _, err = azureClient.DtlCustomImageClient.Get(ctx, b.config.ManagedImageResourceGroupName, b.config.LabName, b.config.ManagedImageName, "") + + if err == nil { + if b.config.PackerForce { + ui.Say(fmt.Sprintf("the managed image named %s already exists, but deleting it due to -force flag", b.config.ManagedImageName)) + f, err := azureClient.DtlCustomImageClient.Delete(ctx, b.config.ManagedImageResourceGroupName, b.config.LabName, b.config.ManagedImageName) + if err == nil { + err = f.WaitForCompletionRef(ctx, azureClient.DtlCustomImageClient.Client) + } + if err != nil { + return nil, fmt.Errorf("failed to delete the managed image named %s : %s", b.config.ManagedImageName, azureClient.LastError.Error()) + } + } else { + return nil, fmt.Errorf("the managed image named %s already exists in the resource group %s, use the -force option to automatically delete it.", b.config.ManagedImageName, b.config.ManagedImageResourceGroupName) + } + } + + } else { + // User is not using Managed Images to build, warning message here that this path is being deprecated + ui.Error("Warning: You are using Azure Packer Builder to create VHDs which is being deprecated, consider using Managed Images. Learn more http://aka.ms/packermanagedimage") + } + + b.config.validateLocationZoneResiliency(ui.Say) + + b.setRuntimeParameters(b.stateBag) + b.setTemplateParameters(b.stateBag) + var steps []multistep.Step + + deploymentName := b.stateBag.Get(constants.ArmDeploymentName).(string) + + // For Managed Images, validate that Shared Gallery Image exists before publishing to SIG + if b.config.isManagedImage() && b.config.SharedGalleryDestination.SigDestinationGalleryName != "" { + _, err = azureClient.GalleryImagesClient.Get(ctx, b.config.SharedGalleryDestination.SigDestinationResourceGroup, b.config.SharedGalleryDestination.SigDestinationGalleryName, b.config.SharedGalleryDestination.SigDestinationImageName) + if err != nil { + return nil, fmt.Errorf("The Shared Gallery Image to which to publish the managed image version to does not exist in the resource group %s", b.config.SharedGalleryDestination.SigDestinationResourceGroup) + } + // SIG requires that replication regions include the region in which the Managed Image resides + managedImageLocation := normalizeAzureRegion(b.stateBag.Get(constants.ArmLocation).(string)) + foundMandatoryReplicationRegion := false + var normalizedReplicationRegions []string + for _, region := range b.config.SharedGalleryDestination.SigDestinationReplicationRegions { + // change region to lower-case and strip spaces + normalizedRegion := normalizeAzureRegion(region) + normalizedReplicationRegions = append(normalizedReplicationRegions, normalizedRegion) + if strings.EqualFold(normalizedRegion, managedImageLocation) { + foundMandatoryReplicationRegion = true + continue + } + } + if foundMandatoryReplicationRegion == false { + b.config.SharedGalleryDestination.SigDestinationReplicationRegions = append(normalizedReplicationRegions, managedImageLocation) + } + b.stateBag.Put(constants.ArmManagedImageSharedGalleryReplicationRegions, b.config.SharedGalleryDestination.SigDestinationReplicationRegions) + } + + // Find the lab location + lab, err := azureClient.DtlLabsClient.Get(ctx, b.config.LabResourceGroupName, b.config.LabName, "") + if err != nil { + return nil, fmt.Errorf("Unable to fetch the Lab %s information in %s resource group", b.config.LabName, b.config.LabResourceGroupName) + } + + b.config.Location = *lab.Location + + if b.config.LabVirtualNetworkName == "" || b.config.LabSubnetName == "" { + virtualNetowrk, subnet, err := b.getSubnetInformation(ctx, ui, *azureClient) + + if err != nil { + return nil, err + } + b.config.LabVirtualNetworkName = *virtualNetowrk + b.config.LabSubnetName = *subnet + + ui.Message(fmt.Sprintf("No lab network information provided. Using %s Virtual network and %s subnet for Virtual Machine creation", b.config.LabVirtualNetworkName, b.config.LabSubnetName)) + } + + if b.config.OSType == constants.Target_Linux { + steps = []multistep.Step{ + NewStepDeployTemplate(azureClient, ui, b.config, deploymentName, GetVirtualMachineDeployment), + &communicator.StepConnectSSH{ + Config: &b.config.Comm, + Host: lin.SSHHost, + SSHConfig: b.config.Comm.SSHConfigFunc(), + }, + &packerCommon.StepProvision{}, + &packerCommon.StepCleanupTempKeys{ + Comm: &b.config.Comm, + }, + NewStepPowerOffCompute(azureClient, ui, b.config), + NewStepCaptureImage(azureClient, ui, b.config), + NewStepPublishToSharedImageGallery(azureClient, ui, b.config), + NewStepDeleteVirtualMachine(azureClient, ui, b.config), + } + } else if b.config.OSType == constants.Target_Windows { + steps = []multistep.Step{ + NewStepDeployTemplate(azureClient, ui, b.config, deploymentName, GetVirtualMachineDeployment), + &StepSaveWinRMPassword{ + Password: b.config.tmpAdminPassword, + BuildName: b.config.PackerBuildName, + }, + &communicator.StepConnectWinRM{ + Config: &b.config.Comm, + Host: func(stateBag multistep.StateBag) (string, error) { + return stateBag.Get(constants.SSHHost).(string), nil + }, + WinRMConfig: func(multistep.StateBag) (*communicator.WinRMConfig, error) { + return &communicator.WinRMConfig{ + Username: b.config.UserName, + Password: b.config.tmpAdminPassword, + }, nil + }, + }, + &packerCommon.StepProvision{}, + NewStepPowerOffCompute(azureClient, ui, b.config), + NewStepCaptureImage(azureClient, ui, b.config), + NewStepPublishToSharedImageGallery(azureClient, ui, b.config), + NewStepDeleteVirtualMachine(azureClient, ui, b.config), + } + } else { + return nil, fmt.Errorf("Builder does not support the os_type '%s'", b.config.OSType) + } + + if b.config.PackerDebug { + ui.Message(fmt.Sprintf("temp admin user: '%s'", b.config.UserName)) + ui.Message(fmt.Sprintf("temp admin password: '%s'", b.config.Password)) + + if len(b.config.Comm.SSHPrivateKey) != 0 { + debugKeyPath := fmt.Sprintf("%s-%s.pem", b.config.PackerBuildName, b.config.tmpComputeName) + ui.Message(fmt.Sprintf("temp ssh key: %s", debugKeyPath)) + + b.writeSSHPrivateKey(ui, debugKeyPath) + } + } + + b.runner = packerCommon.NewRunner(steps, b.config.PackerConfig, ui) + b.runner.Run(ctx, b.stateBag) + + // Report any errors. + if rawErr, ok := b.stateBag.GetOk(constants.Error); ok { + return nil, rawErr.(error) + } + + // If we were interrupted or cancelled, then just exit. + if _, ok := b.stateBag.GetOk(multistep.StateCancelled); ok { + return nil, errors.New("Build was cancelled.") + } + + if _, ok := b.stateBag.GetOk(multistep.StateHalted); ok { + return nil, errors.New("Build was halted.") + } + + if b.config.isManagedImage() { + managedImageID := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/images/%s", b.config.ClientConfig.SubscriptionID, b.config.ManagedImageResourceGroupName, b.config.ManagedImageName) + return NewManagedImageArtifact(b.config.OSType, b.config.ManagedImageResourceGroupName, b.config.ManagedImageName, b.config.Location, managedImageID) + } + return &Artifact{}, nil +} + +func (b *Builder) writeSSHPrivateKey(ui packer.Ui, debugKeyPath string) { + f, err := os.Create(debugKeyPath) + if err != nil { + ui.Say(fmt.Sprintf("Error saving debug key: %s", err)) + } + defer f.Close() + + // Write the key out + if _, err := f.Write(b.config.Comm.SSHPrivateKey); err != nil { + ui.Say(fmt.Sprintf("Error saving debug key: %s", err)) + return + } + + // Chmod it so that it is SSH ready + if runtime.GOOS != "windows" { + if err := f.Chmod(0600); err != nil { + ui.Say(fmt.Sprintf("Error setting permissions of debug key: %s", err)) + } + } +} + +func (b *Builder) configureStateBag(stateBag multistep.StateBag) { + stateBag.Put(constants.AuthorizedKey, b.config.sshAuthorizedKey) + + stateBag.Put(constants.ArmTags, b.config.AzureTags) + stateBag.Put(constants.ArmComputeName, b.config.tmpComputeName) + stateBag.Put(constants.ArmDeploymentName, b.config.tmpDeploymentName) + stateBag.Put(constants.ArmKeyVaultName, b.config.tmpKeyVaultName) + stateBag.Put(constants.ArmNicName, b.config.tmpNicName) + stateBag.Put(constants.ArmPublicIPAddressName, b.config.tmpPublicIPAddressName) + if b.config.tmpResourceGroupName != "" { + stateBag.Put(constants.ArmResourceGroupName, b.config.tmpResourceGroupName) + stateBag.Put(constants.ArmIsExistingResourceGroup, false) + } else { + stateBag.Put(constants.ArmIsExistingResourceGroup, true) + } + + stateBag.Put(constants.ArmIsManagedImage, b.config.isManagedImage()) + stateBag.Put(constants.ArmManagedImageResourceGroupName, b.config.ManagedImageResourceGroupName) + stateBag.Put(constants.ArmManagedImageName, b.config.ManagedImageName) + if b.config.isManagedImage() && b.config.SharedGalleryDestination.SigDestinationGalleryName != "" { + stateBag.Put(constants.ArmManagedImageSigPublishResourceGroup, b.config.SharedGalleryDestination.SigDestinationResourceGroup) + stateBag.Put(constants.ArmManagedImageSharedGalleryName, b.config.SharedGalleryDestination.SigDestinationGalleryName) + stateBag.Put(constants.ArmManagedImageSharedGalleryImageName, b.config.SharedGalleryDestination.SigDestinationImageName) + stateBag.Put(constants.ArmManagedImageSharedGalleryImageVersion, b.config.SharedGalleryDestination.SigDestinationImageVersion) + stateBag.Put(constants.ArmManagedImageSubscription, b.config.ClientConfig.SubscriptionID) + } +} + +// Parameters that are only known at runtime after querying Azure. +func (b *Builder) setRuntimeParameters(stateBag multistep.StateBag) { + stateBag.Put(constants.ArmLocation, b.config.Location) + stateBag.Put(constants.ArmManagedImageLocation, b.config.Location) +} + +func (b *Builder) setTemplateParameters(stateBag multistep.StateBag) { + stateBag.Put(constants.ArmVirtualMachineCaptureParameters, b.config.toVirtualMachineCaptureParameters()) +} + +func (b *Builder) getServicePrincipalToken(say func(string)) (*adal.ServicePrincipalToken, error) { + return b.config.ClientConfig.GetServicePrincipalToken(say, b.config.ClientConfig.CloudEnvironment().ResourceManagerEndpoint) +} + +func (b *Builder) getSubnetInformation(ctx context.Context, ui packer.Ui, azClient AzureClient) (*string, *string, error) { + num := int32(10) + virtualNetworkPage, err := azClient.DtlVirtualNetworksClient.List(ctx, b.config.LabResourceGroupName, b.config.LabName, "", "", &num, "") + + if err != nil { + return nil, nil, fmt.Errorf("Error retrieving Virtual networks in Resourcegroup %s", b.config.LabResourceGroupName) + } + + virtualNetworks := virtualNetworkPage.Values() + for _, virtualNetwork := range virtualNetworks { + for _, subnetOverride := range *virtualNetwork.SubnetOverrides { + // Check if the Subnet is allowed to create VMs having Public IP + if subnetOverride.UseInVMCreationPermission == dtl.Allow && subnetOverride.UsePublicIPAddressPermission == dtl.Allow { + // Return Virtual Network Name and Subnet Name + // Since we cannot query the Usage information from DTL network we cannot know the current remaining capacity. + // TODO (vaangadi) : Fix this to query the subnets that actually have space to create VM. + return virtualNetwork.Name, subnetOverride.LabSubnetName, nil + } + } + } + return nil, nil, fmt.Errorf("No available Subnet with available space in resource group %s", b.config.LabResourceGroupName) +} + +func getObjectIdFromToken(ui packer.Ui, token *adal.ServicePrincipalToken) string { + claims := jwt.MapClaims{} + var p jwt.Parser + + var err error + + _, _, err = p.ParseUnverified(token.OAuthToken(), claims) + + if err != nil { + ui.Error(fmt.Sprintf("Failed to parse the token,Error: %s", err.Error())) + return "" + } + return claims["oid"].(string) + +} + +func normalizeAzureRegion(name string) string { + return strings.ToLower(strings.Replace(name, " ", "", -1)) +} diff --git a/builder/azure/dtl/builder_acc_test.go b/builder/azure/dtl/builder_acc_test.go new file mode 100644 index 000000000..2255319c5 --- /dev/null +++ b/builder/azure/dtl/builder_acc_test.go @@ -0,0 +1,142 @@ +package dtl + +// these tests require the following variables to be set, +// although some test will only use a subset: +// +// * ARM_CLIENT_ID +// * ARM_CLIENT_SECRET +// * ARM_SUBSCRIPTION_ID +// * ARM_OBJECT_ID +// +// The subscription in question should have a resource group +// called "packer-acceptance-test" in "South Central US" region. +// This also requires a Devtest lab to be created with "packer-acceptance-test" +// name in "South Central US region. This can be achieved using the following +// az cli commands " +// az group create --name packer-acceptance-test --location "South Central US" +// az deployment group create \ +// --name ExampleDeployment \ +// --resource-group packer-acceptance-test \ +// --template-file acceptancetest.json \ + +// In addition, the PACKER_ACC variable should also be set to +// a non-empty value to enable Packer acceptance tests and the +// options "-v -timeout 90m" should be provided to the test +// command, e.g.: +// go test -v -timeout 90m -run TestBuilderAcc_.* + +import ( + "testing" + + builderT "github.com/hashicorp/packer/helper/builder/testing" +) + +const DeviceLoginAcceptanceTest = "DEVICELOGIN_TEST" + +func TestBuilderAcc_ManagedDisk_Windows(t *testing.T) { + builderT.Test(t, builderT.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Builder: &Builder{}, + Template: testBuilderAccManagedDiskWindows, + }) +} +func TestBuilderAcc_ManagedDisk_Linux_Artifacts(t *testing.T) { + builderT.Test(t, builderT.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Builder: &Builder{}, + Template: testBuilderAccManagedDiskLinux, + }) +} + +func testAccPreCheck(*testing.T) {} + +const testBuilderAccManagedDiskWindows = ` +{ + "variables": { + "client_id": "{{env ` + "`ARM_CLIENT_ID`" + `}}", + "client_secret": "{{env ` + "`ARM_CLIENT_SECRET`" + `}}", + "subscription_id": "{{env ` + "`ARM_SUBSCRIPTION_ID`" + `}}", + "tenant_id": "{{env ` + "`ARM_TENANT_ID`" + `}}" + }, + "builders": [{ + "type": "test", + + "client_id": "{{user ` + "`client_id`" + `}}", + "client_secret": "{{user ` + "`client_secret`" + `}}", + "subscription_id": "{{user ` + "`subscription_id`" + `}}", + "tenant_id": "{{user ` + "`tenant_id`" + `}}", + + "lab_name": "packer-acceptance-test", + "lab_resource_group_name": "packer-acceptance-test", + "lab_virtual_network_name": "dtlpacker-acceptance-test", + + "managed_image_resource_group_name": "packer-acceptance-test", + "managed_image_name": "testBuilderAccManagedDiskWindows-{{timestamp}}", + + "os_type": "Windows", + "image_publisher": "MicrosoftWindowsServer", + "image_offer": "WindowsServer", + "image_sku": "2012-R2-Datacenter", + + "communicator": "winrm", + "winrm_use_ssl": "true", + "winrm_insecure": "true", + "winrm_timeout": "3m", + "winrm_username": "packer", + + "location": "South Central US", + "vm_size": "Standard_DS2_v2" + }] +} +` + +const testBuilderAccManagedDiskLinux = ` +{ + "variables": { + "client_id": "{{env ` + "`ARM_CLIENT_ID`" + `}}", + "client_secret": "{{env ` + "`ARM_CLIENT_SECRET`" + `}}", + "subscription_id": "{{env ` + "`ARM_SUBSCRIPTION_ID`" + `}}", + "tenant_id": "{{env ` + "`ARM_TENANT_ID`" + `}}" + }, + "builders": [{ + "type": "test", + + "client_id": "{{user ` + "`client_id`" + `}}", + "client_secret": "{{user ` + "`client_secret`" + `}}", + "subscription_id": "{{user ` + "`subscription_id`" + `}}", + + "lab_name": "packer-acceptance-test", + "lab_resource_group_name": "packer-acceptance-test", + "lab_virtual_network_name": "dtlpacker-acceptance-test", + + "managed_image_resource_group_name": "packer-acceptance-test", + "managed_image_name": "testBuilderAccManagedDiskLinux-{{timestamp}}", + + "os_type": "Linux", + "image_publisher": "Canonical", + "image_offer": "UbuntuServer", + "image_sku": "16.04-LTS", + + "location": "South Central US", + "vm_size": "Standard_DS2_v2", + + + "dtl_artifacts": [{ + "artifact_name": "linux-apt-package", + "parameters" : [{ + "name": "packages", + "value": "vim" + }, + { + "name":"update", + "value": "true" + }, + { + "name": "options", + "value": "--fix-broken" + }] + }] + + }] +} +` diff --git a/builder/azure/dtl/builder_test.go b/builder/azure/dtl/builder_test.go new file mode 100644 index 000000000..5120ebd40 --- /dev/null +++ b/builder/azure/dtl/builder_test.go @@ -0,0 +1,33 @@ +package dtl + +import ( + "testing" + + "github.com/hashicorp/packer/builder/azure/common/constants" +) + +func TestStateBagShouldBePopulatedExpectedValues(t *testing.T) { + var testSubject = &Builder{} + _, _, err := testSubject.Prepare(getDtlBuilderConfiguration(), getPackerConfiguration()) + if err != nil { + t.Fatalf("failed to prepare: %s", err) + } + + var expectedStateBagKeys = []string{ + constants.AuthorizedKey, + + constants.ArmTags, + constants.ArmComputeName, + constants.ArmDeploymentName, + constants.ArmNicName, + constants.ArmResourceGroupName, + constants.ArmVirtualMachineCaptureParameters, + constants.ArmPublicIPAddressName, + } + + for _, v := range expectedStateBagKeys { + if _, ok := testSubject.stateBag.GetOk(v); ok == false { + t.Errorf("Expected the builder's state bag to contain '%s', but it did not.", v) + } + } +} diff --git a/builder/azure/dtl/capture_template.go b/builder/azure/dtl/capture_template.go new file mode 100644 index 000000000..4f9cb7716 --- /dev/null +++ b/builder/azure/dtl/capture_template.go @@ -0,0 +1,84 @@ +package dtl + +type CaptureTemplateParameter struct { + Type string `json:"type"` + DefaultValue string `json:"defaultValue,omitempty"` +} + +type CaptureHardwareProfile struct { + VMSize string `json:"vmSize"` +} + +type CaptureUri struct { + Uri string `json:"uri"` +} + +type CaptureDisk struct { + OSType string `json:"osType"` + Name string `json:"name"` + Image CaptureUri `json:"image"` + Vhd CaptureUri `json:"vhd"` + CreateOption string `json:"createOption"` + Caching string `json:"caching"` +} + +type CaptureStorageProfile struct { + OSDisk CaptureDisk `json:"osDisk"` + DataDisks []CaptureDisk `json:"dataDisks"` +} + +type CaptureOSProfile struct { + ComputerName string `json:"computerName"` + AdminUsername string `json:"adminUsername"` + AdminPassword string `json:"adminPassword"` +} + +type CaptureNetworkInterface struct { + Id string `json:"id"` +} + +type CaptureNetworkProfile struct { + NetworkInterfaces []CaptureNetworkInterface `json:"networkInterfaces"` +} + +type CaptureBootDiagnostics struct { + Enabled bool `json:"enabled"` +} + +type CaptureDiagnosticProfile struct { + BootDiagnostics CaptureBootDiagnostics `json:"bootDiagnostics"` +} + +type CaptureProperties struct { + HardwareProfile CaptureHardwareProfile `json:"hardwareProfile"` + StorageProfile CaptureStorageProfile `json:"storageProfile"` + OSProfile CaptureOSProfile `json:"osProfile"` + NetworkProfile CaptureNetworkProfile `json:"networkProfile"` + DiagnosticsProfile CaptureDiagnosticProfile `json:"diagnosticsProfile"` + ProvisioningState int `json:"provisioningState"` +} + +type CaptureResources struct { + ApiVersion string `json:"apiVersion"` + Name string `json:"name"` + Type string `json:"type"` + Location string `json:"location"` + Properties CaptureProperties `json:"properties"` +} + +type CaptureTemplate struct { + Schema string `json:"$schema"` + ContentVersion string `json:"contentVersion"` + Parameters map[string]CaptureTemplateParameter `json:"parameters"` + Resources []CaptureResources `json:"resources"` +} + +type CaptureOperationProperties struct { + Output *CaptureTemplate `json:"output"` +} + +type CaptureOperation struct { + OperationId string `json:"operationId"` + Status string `json:"status"` + Properties *CaptureOperationProperties `json:"properties"` +} diff --git a/builder/azure/dtl/capture_template_test.go b/builder/azure/dtl/capture_template_test.go new file mode 100644 index 000000000..20e0d5ac9 --- /dev/null +++ b/builder/azure/dtl/capture_template_test.go @@ -0,0 +1,272 @@ +package dtl + +import ( + "encoding/json" + "testing" +) + +var captureTemplate01 = `{ + "operationId": "ac1c7c38-a591-41b3-89bd-ea39fceace1b", + "status": "Succeeded", + "startTime": "2016-04-04T21:07:25.2900874+00:00", + "endTime": "2016-04-04T21:07:26.4776321+00:00", + "properties": { + "output": { + "$schema": "http://schema.management.azure.com/schemas/2014-04-01-preview/VM_IP.json", + "contentVersion": "1.0.0.0", + "parameters": { + "vmName": { + "type": "string" + }, + "vmSize": { + "type": "string", + "defaultValue": "Standard_A2" + }, + "adminUserName": { + "type": "string" + }, + "adminPassword": { + "type": "securestring" + }, + "networkInterfaceId": { + "type": "string" + } + }, + "resources": [ + { + "apiVersion": "2015-06-15", + "properties": { + "hardwareProfile": { + "vmSize": "[parameters('vmSize')]" + }, + "storageProfile": { + "osDisk": { + "osType": "Linux", + "name": "packer-osDisk.32118633-6dc9-449f-83b6-a7d2983bec14.vhd", + "createOption": "FromImage", + "image": { + "uri": "http://storage.blob.core.windows.net/system/Microsoft.Compute/Images/images/packer-osDisk.32118633-6dc9-449f-83b6-a7d2983bec14.vhd" + }, + "vhd": { + "uri": "http://storage.blob.core.windows.net/vmcontainerce1a1b75-f480-47cb-8e6e-55142e4a5f68/osDisk.ce1a1b75-f480-47cb-8e6e-55142e4a5f68.vhd" + }, + "caching": "ReadWrite" + }, + "dataDisks": [ + { + "lun": 0, + "name": "packer-datadisk-0.32118633-6dc9-449f-83b6-a7d2983bec14.vhd", + "createOption": "Empty", + "image": { + "uri": "http://storage.blob.core.windows.net/system/Microsoft.Compute/Images/images/packer-datadisk-0.32118633-6dc9-449f-83b6-a7d2983bec14.vhd" + }, + "vhd": { + "uri": "http://storage.blob.core.windows.net/vmcontainerce1a1b75-f480-47cb-8e6e-55142e4a5f68/datadisk-0.ce1a1b75-f480-47cb-8e6e-55142e4a5f68.vhd" + }, + "caching": "ReadWrite" + }, + { + "lun": 1, + "name": "packer-datadisk-1.32118633-6dc9-449f-83b6-a7d2983bec14.vhd", + "createOption": "Empty", + "image": { + "uri": "http://storage.blob.core.windows.net/system/Microsoft.Compute/Images/images/packer-datadisk-1.32118633-6dc9-449f-83b6-a7d2983bec14.vhd" + }, + "vhd": { + "uri": "http://storage.blob.core.windows.net/vmcontainerce1a1b75-f480-47cb-8e6e-55142e4a5f68/datadisk-1.ce1a1b75-f480-47cb-8e6e-55142e4a5f68.vhd" + }, + "caching": "ReadWrite" + } + ] + }, + "osProfile": { + "computerName": "[parameters('vmName')]", + "adminUsername": "[parameters('adminUsername')]", + "adminPassword": "[parameters('adminPassword')]" + }, + "networkProfile": { + "networkInterfaces": [ + { + "id": "[parameters('networkInterfaceId')]" + } + ] + }, + "diagnosticsProfile": { + "bootDiagnostics": { + "enabled": false + } + }, + "provisioningState": 0 + }, + "name": "[parameters('vmName')]", + "type": "Microsoft.Compute/virtualMachines", + "location": "southcentralus" + } + ] + } + } +}` + +var captureTemplate02 = `{ + "operationId": "ac1c7c38-a591-41b3-89bd-ea39fceace1b", + "status": "Succeeded", + "startTime": "2016-04-04T21:07:25.2900874+00:00", + "endTime": "2016-04-04T21:07:26.4776321+00:00" +}` + +func TestCaptureParseJson(t *testing.T) { + var operation CaptureOperation + err := json.Unmarshal([]byte(captureTemplate01), &operation) + if err != nil { + t.Fatalf("failed to the sample capture operation: %s", err) + } + + testSubject := operation.Properties.Output + if testSubject.Schema != "http://schema.management.azure.com/schemas/2014-04-01-preview/VM_IP.json" { + t.Errorf("Schema's value was unexpected: %s", testSubject.Schema) + } + if testSubject.ContentVersion != "1.0.0.0" { + t.Errorf("ContentVersion's value was unexpected: %s", testSubject.ContentVersion) + } + + // == Parameters ==================================== + if len(testSubject.Parameters) != 5 { + t.Fatalf("expected parameters to have 5 keys, but got %d", len(testSubject.Parameters)) + } + if _, ok := testSubject.Parameters["vmName"]; !ok { + t.Errorf("Parameters['vmName'] was an expected parameters, but it did not exist") + } + if testSubject.Parameters["vmName"].Type != "string" { + t.Errorf("Parameters['vmName'].Type == 'string', but got '%s'", testSubject.Parameters["vmName"].Type) + } + if _, ok := testSubject.Parameters["vmSize"]; !ok { + t.Errorf("Parameters['vmSize'] was an expected parameters, but it did not exist") + } + if testSubject.Parameters["vmSize"].Type != "string" { + t.Errorf("Parameters['vmSize'].Type == 'string', but got '%s'", testSubject.Parameters["vmSize"]) + } + if testSubject.Parameters["vmSize"].DefaultValue != "Standard_A2" { + t.Errorf("Parameters['vmSize'].DefaultValue == 'string', but got '%s'", testSubject.Parameters["vmSize"].DefaultValue) + } + + // == Resources ===================================== + if len(testSubject.Resources) != 1 { + t.Fatalf("expected resources to have length 1, but got %d", len(testSubject.Resources)) + } + if testSubject.Resources[0].Name != "[parameters('vmName')]" { + t.Errorf("Resources[0].Name's value was unexpected: %s", testSubject.Resources[0].Name) + } + if testSubject.Resources[0].Type != "Microsoft.Compute/virtualMachines" { + t.Errorf("Resources[0].Type's value was unexpected: %s", testSubject.Resources[0].Type) + } + if testSubject.Resources[0].Location != "southcentralus" { + t.Errorf("Resources[0].Location's value was unexpected: %s", testSubject.Resources[0].Location) + } + + // == Resources/Properties ===================================== + if testSubject.Resources[0].Properties.ProvisioningState != 0 { + t.Errorf("Resources[0].Properties.ProvisioningState's value was unexpected: %d", testSubject.Resources[0].Properties.ProvisioningState) + } + + // == Resources/Properties/HardwareProfile ====================== + hardwareProfile := testSubject.Resources[0].Properties.HardwareProfile + if hardwareProfile.VMSize != "[parameters('vmSize')]" { + t.Errorf("Resources[0].Properties.HardwareProfile.VMSize's value was unexpected: %s", hardwareProfile.VMSize) + } + + // == Resources/Properties/StorageProfile/OSDisk ================ + osDisk := testSubject.Resources[0].Properties.StorageProfile.OSDisk + if osDisk.OSType != "Linux" { + t.Errorf("Resources[0].Properties.StorageProfile.OSDisk.OSDisk's value was unexpected: %s", osDisk.OSType) + } + if osDisk.Name != "packer-osDisk.32118633-6dc9-449f-83b6-a7d2983bec14.vhd" { + t.Errorf("Resources[0].Properties.StorageProfile.OSDisk.Name's value was unexpected: %s", osDisk.Name) + } + if osDisk.CreateOption != "FromImage" { + t.Errorf("Resources[0].Properties.StorageProfile.OSDisk.CreateOption's value was unexpected: %s", osDisk.CreateOption) + } + if osDisk.Image.Uri != "http://storage.blob.core.windows.net/system/Microsoft.Compute/Images/images/packer-osDisk.32118633-6dc9-449f-83b6-a7d2983bec14.vhd" { + t.Errorf("Resources[0].Properties.StorageProfile.OSDisk.Image.Uri's value was unexpected: %s", osDisk.Image.Uri) + } + if osDisk.Vhd.Uri != "http://storage.blob.core.windows.net/vmcontainerce1a1b75-f480-47cb-8e6e-55142e4a5f68/osDisk.ce1a1b75-f480-47cb-8e6e-55142e4a5f68.vhd" { + t.Errorf("Resources[0].Properties.StorageProfile.OSDisk.Vhd.Uri's value was unexpected: %s", osDisk.Vhd.Uri) + } + if osDisk.Caching != "ReadWrite" { + t.Errorf("Resources[0].Properties.StorageProfile.OSDisk.Caching's value was unexpected: %s", osDisk.Caching) + } + + // == Resources/Properties/StorageProfile/DataDisks ================ + dataDisks := testSubject.Resources[0].Properties.StorageProfile.DataDisks + if len(dataDisks) != 2 { + t.Errorf("Resources[0].Properties.StorageProfile.DataDisks, 2 disks expected but was: %d", len(dataDisks)) + } + if dataDisks[0].Name != "packer-datadisk-0.32118633-6dc9-449f-83b6-a7d2983bec14.vhd" { + t.Errorf("Resources[0].Properties.StorageProfile.dataDisks[0].Name's value was unexpected: %s", dataDisks[0].Name) + } + if dataDisks[0].CreateOption != "Empty" { + t.Errorf("Resources[0].Properties.StorageProfile.dataDisks[0].CreateOption's value was unexpected: %s", dataDisks[0].CreateOption) + } + if dataDisks[0].Image.Uri != "http://storage.blob.core.windows.net/system/Microsoft.Compute/Images/images/packer-datadisk-0.32118633-6dc9-449f-83b6-a7d2983bec14.vhd" { + t.Errorf("Resources[0].Properties.StorageProfile.dataDisks[0].Image.Uri's value was unexpected: %s", dataDisks[0].Image.Uri) + } + if dataDisks[0].Vhd.Uri != "http://storage.blob.core.windows.net/vmcontainerce1a1b75-f480-47cb-8e6e-55142e4a5f68/datadisk-0.ce1a1b75-f480-47cb-8e6e-55142e4a5f68.vhd" { + t.Errorf("Resources[0].Properties.StorageProfile.dataDisks[0].Vhd.Uri's value was unexpected: %s", dataDisks[0].Vhd.Uri) + } + if dataDisks[0].Caching != "ReadWrite" { + t.Errorf("Resources[0].Properties.StorageProfile.dataDisks[0].Caching's value was unexpected: %s", dataDisks[0].Caching) + } + if dataDisks[1].Name != "packer-datadisk-1.32118633-6dc9-449f-83b6-a7d2983bec14.vhd" { + t.Errorf("Resources[0].Properties.StorageProfile.dataDisks[1].Name's value was unexpected: %s", dataDisks[1].Name) + } + if dataDisks[1].CreateOption != "Empty" { + t.Errorf("Resources[0].Properties.StorageProfile.dataDisks[1].CreateOption's value was unexpected: %s", dataDisks[1].CreateOption) + } + if dataDisks[1].Image.Uri != "http://storage.blob.core.windows.net/system/Microsoft.Compute/Images/images/packer-datadisk-1.32118633-6dc9-449f-83b6-a7d2983bec14.vhd" { + t.Errorf("Resources[0].Properties.StorageProfile.dataDisks[1].Image.Uri's value was unexpected: %s", dataDisks[1].Image.Uri) + } + if dataDisks[1].Vhd.Uri != "http://storage.blob.core.windows.net/vmcontainerce1a1b75-f480-47cb-8e6e-55142e4a5f68/datadisk-1.ce1a1b75-f480-47cb-8e6e-55142e4a5f68.vhd" { + t.Errorf("Resources[0].Properties.StorageProfile.dataDisks[1].Vhd.Uri's value was unexpected: %s", dataDisks[1].Vhd.Uri) + } + if dataDisks[1].Caching != "ReadWrite" { + t.Errorf("Resources[0].Properties.StorageProfile.dataDisks[1].Caching's value was unexpected: %s", dataDisks[1].Caching) + } + + // == Resources/Properties/OSProfile ============================ + osProfile := testSubject.Resources[0].Properties.OSProfile + if osProfile.AdminPassword != "[parameters('adminPassword')]" { + t.Errorf("Resources[0].Properties.OSProfile.AdminPassword's value was unexpected: %s", osProfile.AdminPassword) + } + if osProfile.AdminUsername != "[parameters('adminUsername')]" { + t.Errorf("Resources[0].Properties.OSProfile.AdminUsername's value was unexpected: %s", osProfile.AdminUsername) + } + if osProfile.ComputerName != "[parameters('vmName')]" { + t.Errorf("Resources[0].Properties.OSProfile.ComputerName's value was unexpected: %s", osProfile.ComputerName) + } + + // == Resources/Properties/NetworkProfile ======================= + networkProfile := testSubject.Resources[0].Properties.NetworkProfile + if len(networkProfile.NetworkInterfaces) != 1 { + t.Errorf("Count of Resources[0].Properties.NetworkProfile.NetworkInterfaces was expected to be 1, but go %d", len(networkProfile.NetworkInterfaces)) + } + if networkProfile.NetworkInterfaces[0].Id != "[parameters('networkInterfaceId')]" { + t.Errorf("Resources[0].Properties.NetworkProfile.NetworkInterfaces[0].Id's value was unexpected: %s", networkProfile.NetworkInterfaces[0].Id) + } + + // == Resources/Properties/DiagnosticsProfile =================== + diagnosticsProfile := testSubject.Resources[0].Properties.DiagnosticsProfile + if diagnosticsProfile.BootDiagnostics.Enabled != false { + t.Errorf("Resources[0].Properties.DiagnosticsProfile.BootDiagnostics.Enabled's value was unexpected: %t", diagnosticsProfile.BootDiagnostics.Enabled) + } +} + +func TestCaptureEmptyOperationJson(t *testing.T) { + var operation CaptureOperation + err := json.Unmarshal([]byte(captureTemplate02), &operation) + if err != nil { + t.Fatalf("failed to the sample capture operation: %s", err) + } + + if operation.Properties != nil { + t.Errorf("JSON contained no properties, but value was not nil: %+v", operation.Properties) + } +} diff --git a/builder/azure/dtl/config.go b/builder/azure/dtl/config.go new file mode 100644 index 000000000..be18d8dbc --- /dev/null +++ b/builder/azure/dtl/config.go @@ -0,0 +1,764 @@ +//go:generate struct-markdown +//go:generate mapstructure-to-hcl2 -type Config,SharedImageGallery,SharedImageGalleryDestination,DtlArtifact,ArtifactParameter + +package dtl + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "encoding/base64" + "encoding/json" + "fmt" + "math/big" + "regexp" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute" + "github.com/Azure/go-autorest/autorest/to" + "github.com/masterzen/winrm" + + "github.com/hashicorp/packer/builder/azure/common/client" + "github.com/hashicorp/packer/builder/azure/common/constants" + + "github.com/hashicorp/packer/builder/azure/pkcs12" + "github.com/hashicorp/packer/common" + "github.com/hashicorp/packer/helper/communicator" + "github.com/hashicorp/packer/helper/config" + "github.com/hashicorp/packer/packer" + "github.com/hashicorp/packer/template/interpolate" + + "golang.org/x/crypto/ssh" +) + +const ( + DefaultImageVersion = "latest" + DefaultUserName = "packer" + DefaultPrivateVirtualNetworkWithPublicIp = false + DefaultVMSize = "Standard_A1" +) + +const ( + // https://docs.microsoft.com/en-us/azure/architecture/best-practices/naming-conventions#naming-rules-and-restrictions + // Regular expressions in Go are not expressive enough, such that the regular expression returned by Azure + // can be used (no backtracking). + // + // -> ^[^_\W][\w-._]{0,79}(? + // + // "shared_image_gallery_destination": { + // "resource_group": "ResourceGroup", + // "gallery_name": "GalleryName", + // "image_name": "ImageName", + // "image_version": "1.0.0", + // "replication_regions": ["regionA", "regionB", "regionC"] + // } + // "managed_image_name": "TargetImageName", + // "managed_image_resource_group_name": "TargetResourceGroup" + SharedGalleryDestination SharedImageGalleryDestination `mapstructure:"shared_image_gallery_destination"` + + // How long to wait for an image to be published to the shared image + // gallery before timing out. If your Packer build is failing on the + // Publishing to Shared Image Gallery step with the error `Original Error: + // context deadline exceeded`, but the image is present when you check your + // Azure dashboard, then you probably need to increase this timeout from + // its default of "60m" (valid time units include `s` for seconds, `m` for + // minutes, and `h` for hours.) + SharedGalleryTimeout time.Duration `mapstructure:"shared_image_gallery_timeout"` + + // PublisherName for your base image. See + // [documentation](https://azure.microsoft.com/en-us/documentation/articles/resource-groups-vm-searching/) + // for details. + // + // CLI example `az vm image list-publishers --location westus` + ImagePublisher string `mapstructure:"image_publisher"` + // Offer for your base image. See + // [documentation](https://azure.microsoft.com/en-us/documentation/articles/resource-groups-vm-searching/) + // for details. + // + // CLI example + // `az vm image list-offers --location westus --publisher Canonical` + ImageOffer string `mapstructure:"image_offer"` + // SKU for your base image. See + // [documentation](https://azure.microsoft.com/en-us/documentation/articles/resource-groups-vm-searching/) + // for details. + // + // CLI example + // `az vm image list-skus --location westus --publisher Canonical --offer UbuntuServer` + ImageSku string `mapstructure:"image_sku"` + // Specify a specific version of an OS to boot from. + // Defaults to `latest`. There may be a difference in versions available + // across regions due to image synchronization latency. To ensure a consistent + // version across regions set this value to one that is available in all + // regions where you are deploying. + // + // CLI example + // `az vm image list --location westus --publisher Canonical --offer UbuntuServer --sku 16.04.0-LTS --all` + ImageVersion string `mapstructure:"image_version"` + // Specify a custom VHD to use. If this value is set, do + // not set image_publisher, image_offer, image_sku, or image_version. + ImageUrl string `mapstructure:"image_url"` + + // Specify the source managed image's resource group used to use. If this + // value is set, do not set image\_publisher, image\_offer, image\_sku, or + // image\_version. If this value is set, the value + // `custom_managed_image_name` must also be set. See + // [documentation](https://docs.microsoft.com/en-us/azure/storage/storage-managed-disks-overview#images) + // to learn more about managed images. + CustomManagedImageResourceGroupName string `mapstructure:"custom_managed_image_resource_group_name"` + // Specify the source managed image's name to use. If this value is set, do + // not set image\_publisher, image\_offer, image\_sku, or image\_version. + // If this value is set, the value + // `custom_managed_image_resource_group_name` must also be set. See + // [documentation](https://docs.microsoft.com/en-us/azure/storage/storage-managed-disks-overview#images) + // to learn more about managed images. + CustomManagedImageName string `mapstructure:"custom_managed_image_name"` + customManagedImageID string + + Location string `mapstructure:"location"` + // Size of the VM used for building. This can be changed when you deploy a + // VM from your VHD. See + // [pricing](https://azure.microsoft.com/en-us/pricing/details/virtual-machines/) + // information. Defaults to `Standard_A1`. + // + // CLI example `az vm list-sizes --location westus` + VMSize string `mapstructure:"vm_size"` + // Specify the managed image resource group name where the result of the + // Packer build will be saved. The resource group must already exist. If + // this value is set, the value managed_image_name must also be set. See + // documentation to learn more about managed images. + ManagedImageResourceGroupName string `mapstructure:"managed_image_resource_group_name"` + // Specify the managed image name where the result of the Packer build will + // be saved. The image name must not exist ahead of time, and will not be + // overwritten. If this value is set, the value + // managed_image_resource_group_name must also be set. See documentation to + // learn more about managed images. + ManagedImageName string `mapstructure:"managed_image_name"` + // Specify the storage account + // type for a managed image. Valid values are Standard_LRS and Premium_LRS. + // The default is Standard_LRS. + ManagedImageStorageAccountType string `mapstructure:"managed_image_storage_account_type" required:"false"` + managedImageStorageAccountType compute.StorageAccountTypes + + // the user can define up to 15 + // tags. Tag names cannot exceed 512 characters, and tag values cannot exceed + // 256 characters. Tags are applied to every resource deployed by a Packer + // build, i.e. Resource Group, VM, NIC, VNET, Public IP, KeyVault, etc. + AzureTags map[string]*string `mapstructure:"azure_tags" required:"false"` + + // Used for creating images from Marketplace images. Please refer to + // [Deploy an image with Marketplace + // terms](https://aka.ms/azuremarketplaceapideployment) for more details. + // Not all Marketplace images support programmatic deployment, and support + // is controlled by the image publisher. + // Plan_id is a string with unique identifier for the plan associated with images. + // Ex plan_id="1-12ab" + PlanID string `mapstructure:"plan_id" required:"false"` + + // The default PollingDuration for azure is 15mins, this property will override + // that value. See [Azure DefaultPollingDuration](https://godoc.org/github.com/Azure/go-autorest/autorest#pkg-constants) + // If your Packer build is failing on the + // ARM deployment step with the error `Original Error: + // context deadline exceeded`, then you probably need to increase this timeout from + // its default of "15m" (valid time units include `s` for seconds, `m` for + // minutes, and `h` for hours.) + PollingDurationTimeout time.Duration `mapstructure:"polling_duration_timeout" required:"false"` + // If either Linux or Windows is specified Packer will + // automatically configure authentication credentials for the provisioned + // machine. For Linux this configures an SSH authorized key. For Windows + // this configures a WinRM certificate. + OSType string `mapstructure:"os_type" required:"false"` + // Specify the size of the OS disk in GB + // (gigabytes). Values of zero or less than zero are ignored. + OSDiskSizeGB int32 `mapstructure:"os_disk_size_gb" required:"false"` + + // The size(s) of any additional hard disks for the VM in gigabytes. If + // this is not specified then the VM will only contain an OS disk. The + // number of additional disks and maximum size of a disk depends on the + // configuration of your VM. See + // [Windows](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/about-disks-and-vhds) + // or + // [Linux](https://docs.microsoft.com/en-us/azure/virtual-machines/linux/about-disks-and-vhds) + // for more information. + // + + // For Managed build the final artifacts are included in the managed image. + // The additional disk will have the same storage account type as the OS + // disk, as specified with the `managed_image_storage_account_type` + // setting. + AdditionalDiskSize []int32 `mapstructure:"disk_additional_size" required:"false"` + // Specify the disk caching type. Valid values + // are None, ReadOnly, and ReadWrite. The default value is ReadWrite. + DiskCachingType string `mapstructure:"disk_caching_type" required:"false"` + diskCachingType compute.CachingTypes + + // DTL values + StorageType string `mapstructure:"storage_type"` + LabVirtualNetworkName string `mapstructure:"lab_virtual_network_name"` + LabName string `mapstructure:"lab_name"` + LabSubnetName string `mapstructure:"lab_subnet_name"` + LabResourceGroupName string `mapstructure:"lab_resource_group_name"` + + DtlArtifacts []DtlArtifact `mapstructure:"dtl_artifacts"` + VMName string `mapstructure:"vm_name"` + + // Runtime Values + UserName string + Password string + tmpAdminPassword string + tmpCertificatePassword string + tmpResourceGroupName string + tmpComputeName string + tmpNicName string + tmpPublicIPAddressName string + tmpDeploymentName string + tmpKeyVaultName string + tmpOSDiskName string + tmpSubnetName string + tmpVirtualNetworkName string + VMCreationResourceGroup string + tmpFQDN string + + // Authentication with the VM via SSH + sshAuthorizedKey string + + // Authentication with the VM via WinRM + winrmCertificate string + winrmPassword string + + Comm communicator.Config `mapstructure:",squash"` + ctx interpolate.Context +} + +type keyVaultCertificate struct { + Data string `json:"data"` + DataType string `json:"dataType"` + Password string `json:"password,omitempty"` +} + +func (c *Config) isManagedImage() bool { + return c.ManagedImageName != "" +} + +func (c *Config) toVirtualMachineCaptureParameters() *compute.VirtualMachineCaptureParameters { + return &compute.VirtualMachineCaptureParameters{ + DestinationContainerName: &c.CaptureContainerName, + VhdPrefix: &c.CaptureNamePrefix, + OverwriteVhds: to.BoolPtr(false), + } +} + +func (c *Config) createCertificate() (string, string, error) { + privateKey, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + err = fmt.Errorf("Failed to Generate Private Key: %s", err) + return "", "", err + } + + host := fmt.Sprintf("%s.centralus.cloudapp.azure.com", c.tmpComputeName) + notBefore := time.Now() + notAfter := notBefore.Add(24 * time.Hour) + + serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) + if err != nil { + err = fmt.Errorf("Failed to Generate Serial Number: %v", err) + return "", "", err + } + + template := x509.Certificate{ + SerialNumber: serialNumber, + Issuer: pkix.Name{ + CommonName: host, + }, + Subject: pkix.Name{ + CommonName: host, + }, + NotBefore: notBefore, + NotAfter: notAfter, + + KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + } + + derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey) + if err != nil { + err = fmt.Errorf("Failed to Create Certificate: %s", err) + return "", "", err + } + + pfxBytes, err := pkcs12.Encode(derBytes, privateKey, c.tmpCertificatePassword) + if err != nil { + err = fmt.Errorf("Failed to encode certificate as PFX: %s", err) + return "", "", err + } + + keyVaultDescription := keyVaultCertificate{ + Data: base64.StdEncoding.EncodeToString(pfxBytes), + DataType: "pfx", + Password: c.tmpCertificatePassword, + } + + bytes, err := json.Marshal(keyVaultDescription) + if err != nil { + err = fmt.Errorf("Failed to marshal key vault description: %s", err) + return "", "", err + } + + certifcatePassowrd := base64.StdEncoding.EncodeToString([]byte(c.tmpCertificatePassword)) + return base64.StdEncoding.EncodeToString(bytes), certifcatePassowrd, nil +} + +func newConfig(raws ...interface{}) (*Config, []string, error) { + var c Config + c.ctx.Funcs = TemplateFuncs + err := config.Decode(&c, &config.DecodeOpts{ + Interpolate: true, + InterpolateContext: &c.ctx, + }, raws...) + + if err != nil { + return nil, nil, err + } + + provideDefaultValues(&c) + setRuntimeValues(&c) + setUserNamePassword(&c) + err = c.ClientConfig.SetDefaultValues() + if err != nil { + return nil, nil, err + } + + // NOTE: if the user did not specify a communicator, then default to both + // SSH and WinRM. This is for backwards compatibility because the code did + // not specifically force the user to set a communicator. + if c.Comm.Type == "" || strings.EqualFold(c.Comm.Type, "ssh") { + err = setSshValues(&c) + if err != nil { + return nil, nil, err + } + } + + //For DTL, communication is done by installing Mandatory public artifact "windows-winrm" + if c.Comm.Type == "" || strings.EqualFold(c.Comm.Type, "winrm") { + err = setWinRMCertificate(&c) + if err != nil { + return nil, nil, err + } + } + + var errs *packer.MultiError + errs = packer.MultiErrorAppend(errs, c.Comm.Prepare(&c.ctx)...) + + c.ClientConfig.Validate(errs) + + assertRequiredParametersSet(&c, errs) + assertTagProperties(&c, errs) + if errs != nil && len(errs.Errors) > 0 { + return nil, nil, errs + } + + return &c, nil, nil +} + +func setSshValues(c *Config) error { + if c.Comm.SSHTimeout == 0 { + c.Comm.SSHTimeout = 20 * time.Minute + } + + if c.Comm.SSHPrivateKeyFile != "" { + privateKeyBytes, err := c.Comm.ReadSSHPrivateKeyFile() + if err != nil { + return err + } + signer, err := ssh.ParsePrivateKey(privateKeyBytes) + if err != nil { + return err + } + + publicKey := signer.PublicKey() + c.sshAuthorizedKey = fmt.Sprintf("%s %s packer Azure Deployment%s", + publicKey.Type(), + base64.StdEncoding.EncodeToString(publicKey.Marshal()), + time.Now().Format(time.RFC3339)) + c.Comm.SSHPrivateKey = privateKeyBytes + + } else { + sshKeyPair, err := NewOpenSshKeyPair() + if err != nil { + return err + } + + c.sshAuthorizedKey = sshKeyPair.AuthorizedKey() + c.Comm.SSHPrivateKey = sshKeyPair.PrivateKey() + } + + return nil +} + +func setWinRMCertificate(c *Config) error { + c.Comm.WinRMTransportDecorator = + func() winrm.Transporter { + return &winrm.ClientNTLM{} + } + + cert, password, err := c.createCertificate() + + c.winrmCertificate = cert + c.winrmPassword = password + + return err +} + +func setRuntimeValues(c *Config) { + var tempName = NewTempName(c) + + c.tmpAdminPassword = tempName.AdminPassword + packer.LogSecretFilter.Set(c.tmpAdminPassword) + + c.tmpCertificatePassword = tempName.CertificatePassword + c.tmpComputeName = tempName.ComputeName + + c.tmpDeploymentName = tempName.DeploymentName + if c.LabResourceGroupName == "" { + c.tmpResourceGroupName = tempName.ResourceGroupName + } else { + c.tmpResourceGroupName = c.LabResourceGroupName + } + c.tmpNicName = tempName.NicName + c.tmpPublicIPAddressName = tempName.PublicIPAddressName + c.tmpOSDiskName = tempName.OSDiskName + c.tmpSubnetName = tempName.SubnetName + c.tmpVirtualNetworkName = tempName.VirtualNetworkName + c.tmpKeyVaultName = tempName.KeyVaultName +} + +func setUserNamePassword(c *Config) { + if c.Comm.SSHUsername == "" { + c.Comm.SSHUsername = DefaultUserName + } + + c.UserName = c.Comm.SSHUsername + + if c.Comm.SSHPassword != "" { + c.Password = c.Comm.SSHPassword + } else { + c.Password = c.tmpAdminPassword + } +} + +func provideDefaultValues(c *Config) { + if c.VMSize == "" { + c.VMSize = DefaultVMSize + } + + if c.ManagedImageStorageAccountType == "" { + c.managedImageStorageAccountType = compute.StorageAccountTypesStandardLRS + } + + if c.DiskCachingType == "" { + c.diskCachingType = compute.CachingTypesReadWrite + } + + if c.ImagePublisher != "" && c.ImageVersion == "" { + c.ImageVersion = DefaultImageVersion + } +} + +func assertTagProperties(c *Config, errs *packer.MultiError) { + if len(c.AzureTags) > 15 { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("a max of 15 tags are supported, but %d were provided", len(c.AzureTags))) + } + + for k, v := range c.AzureTags { + if len(k) > 512 { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("the tag name %q exceeds (%d) the 512 character limit", k, len(k))) + } + if len(*v) > 256 { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("the tag name %q exceeds (%d) the 256 character limit", *v, len(*v))) + } + } +} + +func assertRequiredParametersSet(c *Config, errs *packer.MultiError) { + c.ClientConfig.Validate(errs) + + ///////////////////////////////////////////// + // Capture + if c.CaptureContainerName == "" && c.ManagedImageName == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("A capture_container_name or managed_image_name must be specified")) + } + + if c.CaptureNamePrefix == "" && c.ManagedImageResourceGroupName == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("A capture_name_prefix or managed_image_resource_group_name must be specified")) + } + + if (c.CaptureNamePrefix != "" || c.CaptureContainerName != "") && (c.ManagedImageResourceGroupName != "" || c.ManagedImageName != "") { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("Either a VHD or a managed image can be built, but not both. Please specify either capture_container_name and capture_name_prefix or managed_image_resource_group_name and managed_image_name.")) + } + + if c.CaptureContainerName != "" { + if !reCaptureContainerName.MatchString(c.CaptureContainerName) { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("A capture_container_name must satisfy the regular expression %q.", reCaptureContainerName.String())) + } + + if strings.HasSuffix(c.CaptureContainerName, "-") { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("A capture_container_name must not end with a hyphen, e.g. '-'.")) + } + + if strings.Contains(c.CaptureContainerName, "--") { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("A capture_container_name must not contain consecutive hyphens, e.g. '--'.")) + } + + if c.CaptureNamePrefix == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("A capture_name_prefix must be specified")) + } + + if !reCaptureNamePrefix.MatchString(c.CaptureNamePrefix) { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("A capture_name_prefix must satisfy the regular expression %q.", reCaptureNamePrefix.String())) + } + + if strings.HasSuffix(c.CaptureNamePrefix, "-") || strings.HasSuffix(c.CaptureNamePrefix, ".") { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("A capture_name_prefix must not end with a hyphen or period.")) + } + } + + if c.LabResourceGroupName == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("The settings lab_resource_group_name needs to be defined.")) + } + + ///////////////////////////////////////////// + // Compute + toInt := func(b bool) int { + if b { + return 1 + } else { + return 0 + } + } + + isImageUrl := c.ImageUrl != "" + isCustomManagedImage := c.CustomManagedImageName != "" || c.CustomManagedImageResourceGroupName != "" + isSharedGallery := c.SharedGallery.GalleryName != "" + isPlatformImage := c.ImagePublisher != "" || c.ImageOffer != "" || c.ImageSku != "" + + countSourceInputs := toInt(isImageUrl) + toInt(isCustomManagedImage) + toInt(isPlatformImage) + toInt(isSharedGallery) + + if countSourceInputs > 1 { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("Specify either a VHD (image_url), Image Reference (image_publisher, image_offer, image_sku), a Managed Disk (custom_managed_disk_image_name, custom_managed_disk_resource_group_name), or a Shared Gallery Image (shared_image_gallery)")) + } + + if isImageUrl && c.ManagedImageResourceGroupName != "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("A managed image must be created from a managed image, it cannot be created from a VHD.")) + } + + if c.SharedGallery.GalleryName != "" { + if c.SharedGallery.Subscription == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("A shared_image_gallery.subscription must be specified")) + } + if c.SharedGallery.ResourceGroup == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("A shared_image_gallery.resource_group must be specified")) + } + if c.SharedGallery.ImageName == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("A shared_image_gallery.image_name must be specified")) + } + if c.CaptureContainerName != "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("VHD Target [capture_container_name] is not supported when using Shared Image Gallery as source. Use managed_image_resource_group_name instead.")) + } + if c.CaptureNamePrefix != "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("VHD Target [capture_name_prefix] is not supported when using Shared Image Gallery as source. Use managed_image_name instead.")) + } + } else if c.ImageUrl == "" && c.CustomManagedImageName == "" { + if c.ImagePublisher == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("An image_publisher must be specified")) + } + if c.ImageOffer == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("An image_offer must be specified")) + } + if c.ImageSku == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("An image_sku must be specified")) + } + } else if c.ImageUrl == "" && c.ImagePublisher == "" { + if c.CustomManagedImageResourceGroupName == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("An custom_managed_image_resource_group_name must be specified")) + } + if c.CustomManagedImageName == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("A custom_managed_image_name must be specified")) + } + if c.ManagedImageResourceGroupName == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("An managed_image_resource_group_name must be specified")) + } + if c.ManagedImageName == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("An managed_image_name must be specified")) + } + } else { + if c.ImagePublisher != "" || c.ImageOffer != "" || c.ImageSku != "" || c.ImageVersion != "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("An image_url must not be specified if image_publisher, image_offer, image_sku, or image_version is specified")) + } + } + + if c.ManagedImageResourceGroupName != "" { + if ok, err := assertResourceGroupName(c.ManagedImageResourceGroupName, "managed_image_resource_group_name"); !ok { + errs = packer.MultiErrorAppend(errs, err) + } + } + + if c.ManagedImageName != "" { + if ok, err := assertManagedImageName(c.ManagedImageName, "managed_image_name"); !ok { + errs = packer.MultiErrorAppend(errs, err) + } + } + + if c.LabVirtualNetworkName == "" && c.LabResourceGroupName != "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("If lab_resource_group_name is specified, so must lab_virtual_network_name")) + } + if c.LabVirtualNetworkName == "" && c.LabSubnetName != "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("If virtual_network_subnet_name is specified, so must lab_virtual_network_name")) + } + + ///////////////////////////////////////////// + // Polling Duration Timeout + if c.PollingDurationTimeout == 0 { + // In the sdk, the default is 15 m. + c.PollingDurationTimeout = 15 * time.Minute + } + + ///////////////////////////////////////////// + // OS + if strings.EqualFold(c.OSType, constants.Target_Linux) { + c.OSType = constants.Target_Linux + } else if strings.EqualFold(c.OSType, constants.Target_Windows) { + c.OSType = constants.Target_Windows + } else if c.OSType == "" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("An os_type must be specified")) + } else { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("The os_type %q is invalid", c.OSType)) + } + + switch c.ManagedImageStorageAccountType { + case "", string(compute.StorageAccountTypesStandardLRS): + c.managedImageStorageAccountType = compute.StorageAccountTypesStandardLRS + case string(compute.StorageAccountTypesPremiumLRS): + c.managedImageStorageAccountType = compute.StorageAccountTypesPremiumLRS + default: + errs = packer.MultiErrorAppend(errs, fmt.Errorf("The managed_image_storage_account_type %q is invalid", c.ManagedImageStorageAccountType)) + } + // Errs check to make the linter happy. + if errs != nil { + return + } +} + +func assertManagedImageName(name, setting string) (bool, error) { + if !isValidAzureName(reManagedDiskName, name) { + return false, fmt.Errorf("The setting %s must match the regular expression %q, and not end with a '-' or '.'.", setting, validManagedDiskName) + } + return true, nil +} + +func assertResourceGroupName(rgn, setting string) (bool, error) { + if !isValidAzureName(reResourceGroupName, rgn) { + return false, fmt.Errorf("The setting %s must match the regular expression %q, and not end with a '-' or '.'.", setting, validResourceGroupNameRe) + } + return true, nil +} + +func isValidAzureName(re *regexp.Regexp, rgn string) bool { + return re.Match([]byte(rgn)) && + !strings.HasSuffix(rgn, ".") && + !strings.HasSuffix(rgn, "-") +} + +func (c *Config) validateLocationZoneResiliency(say func(s string)) { + // Docs on regions that support Availibility Zones: + // https://docs.microsoft.com/en-us/azure/availability-zones/az-overview#regions-that-support-availability-zones + // Query technical names for locations: + // az account list-locations --query '[].name' -o tsv + + var zones = make(map[string]struct{}) + zones["westeurope"] = struct{}{} + zones["centralus"] = struct{}{} + zones["eastus2"] = struct{}{} + zones["francecentral"] = struct{}{} + zones["northeurope"] = struct{}{} + zones["southeastasia"] = struct{}{} + zones["westus2"] = struct{}{} + + if _, ok := zones[c.Location]; !ok { + say(fmt.Sprintf("WARNING: Zone resiliency may not be supported in %s, checkout the docs at https://docs.microsoft.com/en-us/azure/availability-zones/", c.Location)) + } +} diff --git a/builder/azure/dtl/config.hcl2spec.go b/builder/azure/dtl/config.hcl2spec.go new file mode 100644 index 000000000..c3028106a --- /dev/null +++ b/builder/azure/dtl/config.hcl2spec.go @@ -0,0 +1,326 @@ +// Code generated by "mapstructure-to-hcl2 -type Config,SharedImageGallery,SharedImageGalleryDestination,DtlArtifact,ArtifactParameter"; DO NOT EDIT. +package dtl + +import ( + "github.com/hashicorp/hcl/v2/hcldec" + "github.com/zclconf/go-cty/cty" +) + +// FlatArtifactParameter is an auto-generated flat version of ArtifactParameter. +// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. +type FlatArtifactParameter struct { + Name *string `mapstructure:"name" cty:"name"` + Value *string `mapstructure:"value" cty:"value"` + Type *string `mapstructure:"type" cty:"type"` +} + +// FlatMapstructure returns a new FlatArtifactParameter. +// FlatArtifactParameter is an auto-generated flat version of ArtifactParameter. +// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up. +func (*ArtifactParameter) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } { + return new(FlatArtifactParameter) +} + +// HCL2Spec returns the hcl spec of a ArtifactParameter. +// This spec is used by HCL to read the fields of ArtifactParameter. +// The decoded values from this spec will then be applied to a FlatArtifactParameter. +func (*FlatArtifactParameter) HCL2Spec() map[string]hcldec.Spec { + s := map[string]hcldec.Spec{ + "name": &hcldec.AttrSpec{Name: "name", Type: cty.String, Required: false}, + "value": &hcldec.AttrSpec{Name: "value", Type: cty.String, Required: false}, + "type": &hcldec.AttrSpec{Name: "type", Type: cty.String, Required: false}, + } + return s +} + +// FlatConfig is an auto-generated flat version of Config. +// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. +type FlatConfig struct { + PackerBuildName *string `mapstructure:"packer_build_name" cty:"packer_build_name"` + PackerBuilderType *string `mapstructure:"packer_builder_type" cty:"packer_builder_type"` + PackerDebug *bool `mapstructure:"packer_debug" cty:"packer_debug"` + PackerForce *bool `mapstructure:"packer_force" cty:"packer_force"` + PackerOnError *string `mapstructure:"packer_on_error" cty:"packer_on_error"` + PackerUserVars map[string]string `mapstructure:"packer_user_variables" cty:"packer_user_variables"` + PackerSensitiveVars []string `mapstructure:"packer_sensitive_variables" cty:"packer_sensitive_variables"` + CloudEnvironmentName *string `mapstructure:"cloud_environment_name" required:"false" cty:"cloud_environment_name"` + ClientID *string `mapstructure:"client_id" cty:"client_id"` + ClientSecret *string `mapstructure:"client_secret" cty:"client_secret"` + ClientCertPath *string `mapstructure:"client_cert_path" cty:"client_cert_path"` + ClientJWT *string `mapstructure:"client_jwt" cty:"client_jwt"` + ObjectID *string `mapstructure:"object_id" cty:"object_id"` + TenantID *string `mapstructure:"tenant_id" required:"false" cty:"tenant_id"` + SubscriptionID *string `mapstructure:"subscription_id" cty:"subscription_id"` + CaptureNamePrefix *string `mapstructure:"capture_name_prefix" cty:"capture_name_prefix"` + CaptureContainerName *string `mapstructure:"capture_container_name" cty:"capture_container_name"` + SharedGallery *FlatSharedImageGallery `mapstructure:"shared_image_gallery" cty:"shared_image_gallery"` + SharedGalleryDestination *FlatSharedImageGalleryDestination `mapstructure:"shared_image_gallery_destination" cty:"shared_image_gallery_destination"` + SharedGalleryTimeout *string `mapstructure:"shared_image_gallery_timeout" cty:"shared_image_gallery_timeout"` + ImagePublisher *string `mapstructure:"image_publisher" cty:"image_publisher"` + ImageOffer *string `mapstructure:"image_offer" cty:"image_offer"` + ImageSku *string `mapstructure:"image_sku" cty:"image_sku"` + ImageVersion *string `mapstructure:"image_version" cty:"image_version"` + ImageUrl *string `mapstructure:"image_url" cty:"image_url"` + CustomManagedImageResourceGroupName *string `mapstructure:"custom_managed_image_resource_group_name" cty:"custom_managed_image_resource_group_name"` + CustomManagedImageName *string `mapstructure:"custom_managed_image_name" cty:"custom_managed_image_name"` + Location *string `mapstructure:"location" cty:"location"` + VMSize *string `mapstructure:"vm_size" cty:"vm_size"` + ManagedImageResourceGroupName *string `mapstructure:"managed_image_resource_group_name" cty:"managed_image_resource_group_name"` + ManagedImageName *string `mapstructure:"managed_image_name" cty:"managed_image_name"` + ManagedImageStorageAccountType *string `mapstructure:"managed_image_storage_account_type" required:"false" cty:"managed_image_storage_account_type"` + AzureTags map[string]*string `mapstructure:"azure_tags" required:"false" cty:"azure_tags"` + PlanID *string `mapstructure:"plan_id" required:"false" cty:"plan_id"` + PollingDurationTimeout *string `mapstructure:"polling_duration_timeout" required:"false" cty:"polling_duration_timeout"` + OSType *string `mapstructure:"os_type" required:"false" cty:"os_type"` + OSDiskSizeGB *int32 `mapstructure:"os_disk_size_gb" required:"false" cty:"os_disk_size_gb"` + AdditionalDiskSize []int32 `mapstructure:"disk_additional_size" required:"false" cty:"disk_additional_size"` + DiskCachingType *string `mapstructure:"disk_caching_type" required:"false" cty:"disk_caching_type"` + StorageType *string `mapstructure:"storage_type" cty:"storage_type"` + LabVirtualNetworkName *string `mapstructure:"lab_virtual_network_name" cty:"lab_virtual_network_name"` + LabName *string `mapstructure:"lab_name" cty:"lab_name"` + LabSubnetName *string `mapstructure:"lab_subnet_name" cty:"lab_subnet_name"` + LabResourceGroupName *string `mapstructure:"lab_resource_group_name" cty:"lab_resource_group_name"` + DtlArtifacts []FlatDtlArtifact `mapstructure:"dtl_artifacts" cty:"dtl_artifacts"` + VMName *string `mapstructure:"vm_name" cty:"vm_name"` + UserName *string `cty:"user_name"` + Password *string `cty:"password"` + VMCreationResourceGroup *string `cty:"vm_creation_resource_group"` + Type *string `mapstructure:"communicator" cty:"communicator"` + PauseBeforeConnect *string `mapstructure:"pause_before_connecting" cty:"pause_before_connecting"` + SSHHost *string `mapstructure:"ssh_host" cty:"ssh_host"` + SSHPort *int `mapstructure:"ssh_port" cty:"ssh_port"` + SSHUsername *string `mapstructure:"ssh_username" cty:"ssh_username"` + SSHPassword *string `mapstructure:"ssh_password" cty:"ssh_password"` + SSHKeyPairName *string `mapstructure:"ssh_keypair_name" cty:"ssh_keypair_name"` + SSHTemporaryKeyPairName *string `mapstructure:"temporary_key_pair_name" cty:"temporary_key_pair_name"` + SSHClearAuthorizedKeys *bool `mapstructure:"ssh_clear_authorized_keys" cty:"ssh_clear_authorized_keys"` + SSHPrivateKeyFile *string `mapstructure:"ssh_private_key_file" cty:"ssh_private_key_file"` + SSHPty *bool `mapstructure:"ssh_pty" cty:"ssh_pty"` + SSHTimeout *string `mapstructure:"ssh_timeout" cty:"ssh_timeout"` + SSHAgentAuth *bool `mapstructure:"ssh_agent_auth" cty:"ssh_agent_auth"` + SSHDisableAgentForwarding *bool `mapstructure:"ssh_disable_agent_forwarding" cty:"ssh_disable_agent_forwarding"` + SSHHandshakeAttempts *int `mapstructure:"ssh_handshake_attempts" cty:"ssh_handshake_attempts"` + SSHBastionHost *string `mapstructure:"ssh_bastion_host" cty:"ssh_bastion_host"` + SSHBastionPort *int `mapstructure:"ssh_bastion_port" cty:"ssh_bastion_port"` + SSHBastionAgentAuth *bool `mapstructure:"ssh_bastion_agent_auth" cty:"ssh_bastion_agent_auth"` + SSHBastionUsername *string `mapstructure:"ssh_bastion_username" cty:"ssh_bastion_username"` + SSHBastionPassword *string `mapstructure:"ssh_bastion_password" cty:"ssh_bastion_password"` + SSHBastionInteractive *bool `mapstructure:"ssh_bastion_interactive" cty:"ssh_bastion_interactive"` + SSHBastionPrivateKeyFile *string `mapstructure:"ssh_bastion_private_key_file" cty:"ssh_bastion_private_key_file"` + SSHFileTransferMethod *string `mapstructure:"ssh_file_transfer_method" cty:"ssh_file_transfer_method"` + SSHProxyHost *string `mapstructure:"ssh_proxy_host" cty:"ssh_proxy_host"` + SSHProxyPort *int `mapstructure:"ssh_proxy_port" cty:"ssh_proxy_port"` + SSHProxyUsername *string `mapstructure:"ssh_proxy_username" cty:"ssh_proxy_username"` + SSHProxyPassword *string `mapstructure:"ssh_proxy_password" cty:"ssh_proxy_password"` + SSHKeepAliveInterval *string `mapstructure:"ssh_keep_alive_interval" cty:"ssh_keep_alive_interval"` + SSHReadWriteTimeout *string `mapstructure:"ssh_read_write_timeout" cty:"ssh_read_write_timeout"` + SSHRemoteTunnels []string `mapstructure:"ssh_remote_tunnels" cty:"ssh_remote_tunnels"` + SSHLocalTunnels []string `mapstructure:"ssh_local_tunnels" cty:"ssh_local_tunnels"` + SSHPublicKey []byte `mapstructure:"ssh_public_key" cty:"ssh_public_key"` + SSHPrivateKey []byte `mapstructure:"ssh_private_key" cty:"ssh_private_key"` + WinRMUser *string `mapstructure:"winrm_username" cty:"winrm_username"` + WinRMPassword *string `mapstructure:"winrm_password" cty:"winrm_password"` + WinRMHost *string `mapstructure:"winrm_host" cty:"winrm_host"` + WinRMPort *int `mapstructure:"winrm_port" cty:"winrm_port"` + WinRMTimeout *string `mapstructure:"winrm_timeout" cty:"winrm_timeout"` + WinRMUseSSL *bool `mapstructure:"winrm_use_ssl" cty:"winrm_use_ssl"` + WinRMInsecure *bool `mapstructure:"winrm_insecure" cty:"winrm_insecure"` + WinRMUseNTLM *bool `mapstructure:"winrm_use_ntlm" cty:"winrm_use_ntlm"` +} + +// FlatMapstructure returns a new FlatConfig. +// FlatConfig is an auto-generated flat version of Config. +// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up. +func (*Config) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } { + return new(FlatConfig) +} + +// HCL2Spec returns the hcl spec of a Config. +// This spec is used by HCL to read the fields of Config. +// The decoded values from this spec will then be applied to a FlatConfig. +func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { + s := map[string]hcldec.Spec{ + "packer_build_name": &hcldec.AttrSpec{Name: "packer_build_name", Type: cty.String, Required: false}, + "packer_builder_type": &hcldec.AttrSpec{Name: "packer_builder_type", Type: cty.String, Required: false}, + "packer_debug": &hcldec.AttrSpec{Name: "packer_debug", Type: cty.Bool, Required: false}, + "packer_force": &hcldec.AttrSpec{Name: "packer_force", Type: cty.Bool, Required: false}, + "packer_on_error": &hcldec.AttrSpec{Name: "packer_on_error", Type: cty.String, Required: false}, + "packer_user_variables": &hcldec.BlockAttrsSpec{TypeName: "packer_user_variables", ElementType: cty.String, Required: false}, + "packer_sensitive_variables": &hcldec.AttrSpec{Name: "packer_sensitive_variables", Type: cty.List(cty.String), Required: false}, + "cloud_environment_name": &hcldec.AttrSpec{Name: "cloud_environment_name", Type: cty.String, Required: false}, + "client_id": &hcldec.AttrSpec{Name: "client_id", Type: cty.String, Required: false}, + "client_secret": &hcldec.AttrSpec{Name: "client_secret", Type: cty.String, Required: false}, + "client_cert_path": &hcldec.AttrSpec{Name: "client_cert_path", Type: cty.String, Required: false}, + "client_jwt": &hcldec.AttrSpec{Name: "client_jwt", Type: cty.String, Required: false}, + "object_id": &hcldec.AttrSpec{Name: "object_id", Type: cty.String, Required: false}, + "tenant_id": &hcldec.AttrSpec{Name: "tenant_id", Type: cty.String, Required: false}, + "subscription_id": &hcldec.AttrSpec{Name: "subscription_id", Type: cty.String, Required: false}, + "capture_name_prefix": &hcldec.AttrSpec{Name: "capture_name_prefix", Type: cty.String, Required: false}, + "capture_container_name": &hcldec.AttrSpec{Name: "capture_container_name", Type: cty.String, Required: false}, + "shared_image_gallery": &hcldec.BlockSpec{TypeName: "shared_image_gallery", Nested: hcldec.ObjectSpec((*FlatSharedImageGallery)(nil).HCL2Spec())}, + "shared_image_gallery_destination": &hcldec.BlockSpec{TypeName: "shared_image_gallery_destination", Nested: hcldec.ObjectSpec((*FlatSharedImageGalleryDestination)(nil).HCL2Spec())}, + "shared_image_gallery_timeout": &hcldec.AttrSpec{Name: "shared_image_gallery_timeout", Type: cty.String, Required: false}, + "image_publisher": &hcldec.AttrSpec{Name: "image_publisher", Type: cty.String, Required: false}, + "image_offer": &hcldec.AttrSpec{Name: "image_offer", Type: cty.String, Required: false}, + "image_sku": &hcldec.AttrSpec{Name: "image_sku", Type: cty.String, Required: false}, + "image_version": &hcldec.AttrSpec{Name: "image_version", Type: cty.String, Required: false}, + "image_url": &hcldec.AttrSpec{Name: "image_url", Type: cty.String, Required: false}, + "custom_managed_image_resource_group_name": &hcldec.AttrSpec{Name: "custom_managed_image_resource_group_name", Type: cty.String, Required: false}, + "custom_managed_image_name": &hcldec.AttrSpec{Name: "custom_managed_image_name", Type: cty.String, Required: false}, + "location": &hcldec.AttrSpec{Name: "location", Type: cty.String, Required: false}, + "vm_size": &hcldec.AttrSpec{Name: "vm_size", Type: cty.String, Required: false}, + "managed_image_resource_group_name": &hcldec.AttrSpec{Name: "managed_image_resource_group_name", Type: cty.String, Required: false}, + "managed_image_name": &hcldec.AttrSpec{Name: "managed_image_name", Type: cty.String, Required: false}, + "managed_image_storage_account_type": &hcldec.AttrSpec{Name: "managed_image_storage_account_type", Type: cty.String, Required: false}, + "azure_tags": &hcldec.BlockAttrsSpec{TypeName: "azure_tags", ElementType: cty.String, Required: false}, + "plan_id": &hcldec.AttrSpec{Name: "plan_id", Type: cty.String, Required: false}, + "polling_duration_timeout": &hcldec.AttrSpec{Name: "polling_duration_timeout", Type: cty.String, Required: false}, + "os_type": &hcldec.AttrSpec{Name: "os_type", Type: cty.String, Required: false}, + "os_disk_size_gb": &hcldec.AttrSpec{Name: "os_disk_size_gb", Type: cty.Number, Required: false}, + "disk_additional_size": &hcldec.AttrSpec{Name: "disk_additional_size", Type: cty.List(cty.Number), Required: false}, + "disk_caching_type": &hcldec.AttrSpec{Name: "disk_caching_type", Type: cty.String, Required: false}, + "storage_type": &hcldec.AttrSpec{Name: "storage_type", Type: cty.String, Required: false}, + "lab_virtual_network_name": &hcldec.AttrSpec{Name: "lab_virtual_network_name", Type: cty.String, Required: false}, + "lab_name": &hcldec.AttrSpec{Name: "lab_name", Type: cty.String, Required: false}, + "lab_subnet_name": &hcldec.AttrSpec{Name: "lab_subnet_name", Type: cty.String, Required: false}, + "lab_resource_group_name": &hcldec.AttrSpec{Name: "lab_resource_group_name", Type: cty.String, Required: false}, + "dtl_artifacts": &hcldec.BlockListSpec{TypeName: "dtl_artifacts", Nested: hcldec.ObjectSpec((*FlatDtlArtifact)(nil).HCL2Spec())}, + "vm_name": &hcldec.AttrSpec{Name: "vm_name", Type: cty.String, Required: false}, + "user_name": &hcldec.AttrSpec{Name: "user_name", Type: cty.String, Required: false}, + "password": &hcldec.AttrSpec{Name: "password", Type: cty.String, Required: false}, + "vm_creation_resource_group": &hcldec.AttrSpec{Name: "vm_creation_resource_group", Type: cty.String, Required: false}, + "communicator": &hcldec.AttrSpec{Name: "communicator", Type: cty.String, Required: false}, + "pause_before_connecting": &hcldec.AttrSpec{Name: "pause_before_connecting", Type: cty.String, Required: false}, + "ssh_host": &hcldec.AttrSpec{Name: "ssh_host", Type: cty.String, Required: false}, + "ssh_port": &hcldec.AttrSpec{Name: "ssh_port", Type: cty.Number, Required: false}, + "ssh_username": &hcldec.AttrSpec{Name: "ssh_username", Type: cty.String, Required: false}, + "ssh_password": &hcldec.AttrSpec{Name: "ssh_password", Type: cty.String, Required: false}, + "ssh_keypair_name": &hcldec.AttrSpec{Name: "ssh_keypair_name", Type: cty.String, Required: false}, + "temporary_key_pair_name": &hcldec.AttrSpec{Name: "temporary_key_pair_name", Type: cty.String, Required: false}, + "ssh_clear_authorized_keys": &hcldec.AttrSpec{Name: "ssh_clear_authorized_keys", Type: cty.Bool, Required: false}, + "ssh_private_key_file": &hcldec.AttrSpec{Name: "ssh_private_key_file", Type: cty.String, Required: false}, + "ssh_pty": &hcldec.AttrSpec{Name: "ssh_pty", Type: cty.Bool, Required: false}, + "ssh_timeout": &hcldec.AttrSpec{Name: "ssh_timeout", Type: cty.String, Required: false}, + "ssh_agent_auth": &hcldec.AttrSpec{Name: "ssh_agent_auth", Type: cty.Bool, Required: false}, + "ssh_disable_agent_forwarding": &hcldec.AttrSpec{Name: "ssh_disable_agent_forwarding", Type: cty.Bool, Required: false}, + "ssh_handshake_attempts": &hcldec.AttrSpec{Name: "ssh_handshake_attempts", Type: cty.Number, Required: false}, + "ssh_bastion_host": &hcldec.AttrSpec{Name: "ssh_bastion_host", Type: cty.String, Required: false}, + "ssh_bastion_port": &hcldec.AttrSpec{Name: "ssh_bastion_port", Type: cty.Number, Required: false}, + "ssh_bastion_agent_auth": &hcldec.AttrSpec{Name: "ssh_bastion_agent_auth", Type: cty.Bool, Required: false}, + "ssh_bastion_username": &hcldec.AttrSpec{Name: "ssh_bastion_username", Type: cty.String, Required: false}, + "ssh_bastion_password": &hcldec.AttrSpec{Name: "ssh_bastion_password", Type: cty.String, Required: false}, + "ssh_bastion_interactive": &hcldec.AttrSpec{Name: "ssh_bastion_interactive", Type: cty.Bool, Required: false}, + "ssh_bastion_private_key_file": &hcldec.AttrSpec{Name: "ssh_bastion_private_key_file", Type: cty.String, Required: false}, + "ssh_file_transfer_method": &hcldec.AttrSpec{Name: "ssh_file_transfer_method", Type: cty.String, Required: false}, + "ssh_proxy_host": &hcldec.AttrSpec{Name: "ssh_proxy_host", Type: cty.String, Required: false}, + "ssh_proxy_port": &hcldec.AttrSpec{Name: "ssh_proxy_port", Type: cty.Number, Required: false}, + "ssh_proxy_username": &hcldec.AttrSpec{Name: "ssh_proxy_username", Type: cty.String, Required: false}, + "ssh_proxy_password": &hcldec.AttrSpec{Name: "ssh_proxy_password", Type: cty.String, Required: false}, + "ssh_keep_alive_interval": &hcldec.AttrSpec{Name: "ssh_keep_alive_interval", Type: cty.String, Required: false}, + "ssh_read_write_timeout": &hcldec.AttrSpec{Name: "ssh_read_write_timeout", Type: cty.String, Required: false}, + "ssh_remote_tunnels": &hcldec.AttrSpec{Name: "ssh_remote_tunnels", Type: cty.List(cty.String), Required: false}, + "ssh_local_tunnels": &hcldec.AttrSpec{Name: "ssh_local_tunnels", Type: cty.List(cty.String), Required: false}, + "ssh_public_key": &hcldec.AttrSpec{Name: "ssh_public_key", Type: cty.List(cty.Number), Required: false}, + "ssh_private_key": &hcldec.AttrSpec{Name: "ssh_private_key", Type: cty.List(cty.Number), Required: false}, + "winrm_username": &hcldec.AttrSpec{Name: "winrm_username", Type: cty.String, Required: false}, + "winrm_password": &hcldec.AttrSpec{Name: "winrm_password", Type: cty.String, Required: false}, + "winrm_host": &hcldec.AttrSpec{Name: "winrm_host", Type: cty.String, Required: false}, + "winrm_port": &hcldec.AttrSpec{Name: "winrm_port", Type: cty.Number, Required: false}, + "winrm_timeout": &hcldec.AttrSpec{Name: "winrm_timeout", Type: cty.String, Required: false}, + "winrm_use_ssl": &hcldec.AttrSpec{Name: "winrm_use_ssl", Type: cty.Bool, Required: false}, + "winrm_insecure": &hcldec.AttrSpec{Name: "winrm_insecure", Type: cty.Bool, Required: false}, + "winrm_use_ntlm": &hcldec.AttrSpec{Name: "winrm_use_ntlm", Type: cty.Bool, Required: false}, + } + return s +} + +// FlatDtlArtifact is an auto-generated flat version of DtlArtifact. +// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. +type FlatDtlArtifact struct { + ArtifactName *string `mapstructure:"artifact_name" cty:"artifact_name"` + RepositoryName *string `mapstructure:"repository_name" cty:"repository_name"` + ArtifactId *string `mapstructure:"artifact_id" cty:"artifact_id"` + Parameters []FlatArtifactParameter `mapstructure:"parameters" cty:"parameters"` +} + +// FlatMapstructure returns a new FlatDtlArtifact. +// FlatDtlArtifact is an auto-generated flat version of DtlArtifact. +// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up. +func (*DtlArtifact) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } { + return new(FlatDtlArtifact) +} + +// HCL2Spec returns the hcl spec of a DtlArtifact. +// This spec is used by HCL to read the fields of DtlArtifact. +// The decoded values from this spec will then be applied to a FlatDtlArtifact. +func (*FlatDtlArtifact) HCL2Spec() map[string]hcldec.Spec { + s := map[string]hcldec.Spec{ + "artifact_name": &hcldec.AttrSpec{Name: "artifact_name", Type: cty.String, Required: false}, + "repository_name": &hcldec.AttrSpec{Name: "repository_name", Type: cty.String, Required: false}, + "artifact_id": &hcldec.AttrSpec{Name: "artifact_id", Type: cty.String, Required: false}, + "parameters": &hcldec.BlockListSpec{TypeName: "parameters", Nested: hcldec.ObjectSpec((*FlatArtifactParameter)(nil).HCL2Spec())}, + } + return s +} + +// FlatSharedImageGallery is an auto-generated flat version of SharedImageGallery. +// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. +type FlatSharedImageGallery struct { + Subscription *string `mapstructure:"subscription" cty:"subscription"` + ResourceGroup *string `mapstructure:"resource_group" cty:"resource_group"` + GalleryName *string `mapstructure:"gallery_name" cty:"gallery_name"` + ImageName *string `mapstructure:"image_name" cty:"image_name"` + ImageVersion *string `mapstructure:"image_version" cty:"image_version"` +} + +// FlatMapstructure returns a new FlatSharedImageGallery. +// FlatSharedImageGallery is an auto-generated flat version of SharedImageGallery. +// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up. +func (*SharedImageGallery) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } { + return new(FlatSharedImageGallery) +} + +// HCL2Spec returns the hcl spec of a SharedImageGallery. +// This spec is used by HCL to read the fields of SharedImageGallery. +// The decoded values from this spec will then be applied to a FlatSharedImageGallery. +func (*FlatSharedImageGallery) HCL2Spec() map[string]hcldec.Spec { + s := map[string]hcldec.Spec{ + "subscription": &hcldec.AttrSpec{Name: "subscription", Type: cty.String, Required: false}, + "resource_group": &hcldec.AttrSpec{Name: "resource_group", Type: cty.String, Required: false}, + "gallery_name": &hcldec.AttrSpec{Name: "gallery_name", Type: cty.String, Required: false}, + "image_name": &hcldec.AttrSpec{Name: "image_name", Type: cty.String, Required: false}, + "image_version": &hcldec.AttrSpec{Name: "image_version", Type: cty.String, Required: false}, + } + return s +} + +// FlatSharedImageGalleryDestination is an auto-generated flat version of SharedImageGalleryDestination. +// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. +type FlatSharedImageGalleryDestination struct { + SigDestinationResourceGroup *string `mapstructure:"resource_group" cty:"resource_group"` + SigDestinationGalleryName *string `mapstructure:"gallery_name" cty:"gallery_name"` + SigDestinationImageName *string `mapstructure:"image_name" cty:"image_name"` + SigDestinationImageVersion *string `mapstructure:"image_version" cty:"image_version"` + SigDestinationReplicationRegions []string `mapstructure:"replication_regions" cty:"replication_regions"` +} + +// FlatMapstructure returns a new FlatSharedImageGalleryDestination. +// FlatSharedImageGalleryDestination is an auto-generated flat version of SharedImageGalleryDestination. +// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up. +func (*SharedImageGalleryDestination) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } { + return new(FlatSharedImageGalleryDestination) +} + +// HCL2Spec returns the hcl spec of a SharedImageGalleryDestination. +// This spec is used by HCL to read the fields of SharedImageGalleryDestination. +// The decoded values from this spec will then be applied to a FlatSharedImageGalleryDestination. +func (*FlatSharedImageGalleryDestination) HCL2Spec() map[string]hcldec.Spec { + s := map[string]hcldec.Spec{ + "resource_group": &hcldec.AttrSpec{Name: "resource_group", Type: cty.String, Required: false}, + "gallery_name": &hcldec.AttrSpec{Name: "gallery_name", Type: cty.String, Required: false}, + "image_name": &hcldec.AttrSpec{Name: "image_name", Type: cty.String, Required: false}, + "image_version": &hcldec.AttrSpec{Name: "image_version", Type: cty.String, Required: false}, + "replication_regions": &hcldec.AttrSpec{Name: "replication_regions", Type: cty.List(cty.String), Required: false}, + } + return s +} diff --git a/builder/azure/dtl/config_test.go b/builder/azure/dtl/config_test.go new file mode 100644 index 000000000..5690ffe68 --- /dev/null +++ b/builder/azure/dtl/config_test.go @@ -0,0 +1,543 @@ +package dtl + +import ( + "fmt" + "testing" + "time" + + "github.com/hashicorp/packer/builder/azure/common/constants" +) + +// List of configuration parameters that are required by the DTL builder. +var requiredConfigValues = []string{ + "capture_name_prefix", + "capture_container_name", + "client_id", + "client_secret", + "image_offer", + "image_publisher", + "image_sku", + "location", + "os_type", + "subscription_id", + "lab_resource_group_name", + "lab_virtual_network_name", +} + +func TestConfigShouldProvideReasonableDefaultValues(t *testing.T) { + c, _, err := newConfig(getDtlBuilderConfiguration(), getPackerConfiguration()) + + if err != nil { + t.Error("Expected configuration creation to succeed, but it failed!\n") + t.Fatalf(" errors: %s\n", err) + } + + if c.UserName == "" { + t.Error("Expected 'UserName' to be populated, but it was empty!") + } + + if c.VMSize == "" { + t.Error("Expected 'VMSize' to be populated, but it was empty!") + } + + if c.ClientConfig.ObjectID != "" { + t.Errorf("Expected 'ObjectID' to be nil, but it was '%s'!", c.ClientConfig.ObjectID) + } + + if c.managedImageStorageAccountType == "" { + t.Errorf("Expected 'managedImageStorageAccountType' to be populated, but it was empty!") + } + + if c.diskCachingType == "" { + t.Errorf("Expected 'diskCachingType' to be populated, but it was empty!") + } +} + +func TestConfigShouldDefaultVMSizeToStandardA1(t *testing.T) { + c, _, _ := newConfig(getDtlBuilderConfiguration(), getPackerConfiguration()) + + if c.VMSize != "Standard_A1" { + t.Errorf("Expected 'VMSize' to default to 'Standard_A1', but got '%s'.", c.VMSize) + } +} + +func TestConfigShouldDefaultImageVersionToLatest(t *testing.T) { + c, _, _ := newConfig(getDtlBuilderConfiguration(), getPackerConfiguration()) + + if c.ImageVersion != "latest" { + t.Errorf("Expected 'ImageVersion' to default to 'latest', but got '%s'.", c.ImageVersion) + } +} + +// The user can pass the value virtual_network_resource_group_name to avoid the lookup of +// a virtual network's resource group, or to help with disambiguation. The value should +// only be set if virtual_network_name was set. +func TestConfigVirtualNetworkResourceGroupNameMustBeSetWithVirtualNetworkName(t *testing.T) { + config := map[string]string{ + "capture_name_prefix": "ignore", + "capture_container_name": "ignore", + "location": "ignore", + "image_url": "ignore", + "subscription_id": "ignore", + "os_type": constants.Target_Linux, + "communicator": "none", + "virtual_network_resource_group_name": "MyVirtualNetworkRG", + } + + _, _, err := newConfig(config, getPackerConfiguration()) + if err == nil { + t.Error("Expected Config to reject virtual_network_resource_group_name, if virtual_network_name is not set.") + } +} + +// The user can pass the value virtual_network_subnet_name to avoid the lookup of +// a virtual network subnet's name, or to help with disambiguation. The value should +// only be set if virtual_network_name was set. +func TestConfigVirtualNetworkSubnetNameMustBeSetWithVirtualNetworkName(t *testing.T) { + config := map[string]string{ + "capture_name_prefix": "ignore", + "capture_container_name": "ignore", + "location": "ignore", + "image_url": "ignore", + "subscription_id": "ignore", + "os_type": constants.Target_Linux, + "communicator": "none", + "virtual_network_subnet_name": "MyVirtualNetworkRG", + } + + _, _, err := newConfig(config, getPackerConfiguration()) + if err == nil { + t.Error("Expected Config to reject virtual_network_subnet_name, if virtual_network_name is not set.") + } +} + +func TestSystemShouldDefineRuntimeValues(t *testing.T) { + c, _, _ := newConfig(getDtlBuilderConfiguration(), getPackerConfiguration()) + + if c.Password == "" { + t.Errorf("Expected Password to not be empty, but it was '%s'!", c.Password) + } + + if c.tmpComputeName == "" { + t.Errorf("Expected tmpComputeName to not be empty, but it was '%s'!", c.tmpComputeName) + } + + if c.tmpDeploymentName == "" { + t.Errorf("Expected tmpDeploymentName to not be empty, but it was '%s'!", c.tmpDeploymentName) + } + + if c.tmpResourceGroupName == "" { + t.Errorf("Expected tmpResourceGroupName to not be empty, but it was '%s'!", c.tmpResourceGroupName) + } + + if c.tmpOSDiskName == "" { + t.Errorf("Expected tmpOSDiskName to not be empty, but it was '%s'!", c.tmpOSDiskName) + } +} + +func TestConfigShouldTransformToVirtualMachineCaptureParameters(t *testing.T) { + c, _, _ := newConfig(getDtlBuilderConfiguration(), getPackerConfiguration()) + parameters := c.toVirtualMachineCaptureParameters() + + if *parameters.DestinationContainerName != c.CaptureContainerName { + t.Errorf("Expected DestinationContainerName to be equal to config's CaptureContainerName, but they were '%s' and '%s' respectively.", *parameters.DestinationContainerName, c.CaptureContainerName) + } + + if *parameters.VhdPrefix != c.CaptureNamePrefix { + t.Errorf("Expected DestinationContainerName to be equal to config's CaptureContainerName, but they were '%s' and '%s' respectively.", *parameters.VhdPrefix, c.CaptureNamePrefix) + } + + if *parameters.OverwriteVhds != false { + t.Error("Expected OverwriteVhds to be false, but it was not.") + } +} + +func TestConfigShouldSupportPackersConfigElements(t *testing.T) { + c, _, err := newConfig( + getDtlBuilderConfiguration(), + getPackerConfiguration(), + getPackerCommunicatorConfiguration()) + + if err != nil { + t.Fatal(err) + } + + if c.Comm.SSHTimeout != 1*time.Hour { + t.Errorf("Expected Comm.SSHTimeout to be a duration of an hour, but got '%s' instead.", c.Comm.SSHTimeout) + } + + if c.Comm.WinRMTimeout != 2*time.Hour { + t.Errorf("Expected Comm.WinRMTimeout to be a durationof two hours, but got '%s' instead.", c.Comm.WinRMTimeout) + } +} + +func TestWinRMConfigShouldSetRoundTripDecorator(t *testing.T) { + config := getDtlBuilderConfiguration() + config["communicator"] = "winrm" + config["winrm_username"] = "username" + config["winrm_password"] = "password" + + c, _, err := newConfig(config, getPackerConfiguration()) + if err != nil { + t.Fatal(err) + } + + if c.Comm.WinRMTransportDecorator == nil { + t.Error("Expected WinRMTransportDecorator to be set, but it was nil") + } +} + +func TestUserDeviceLoginIsEnabledForLinux(t *testing.T) { + config := map[string]string{ + "capture_name_prefix": "ignore", + "capture_container_name": "ignore", + "image_offer": "ignore", + "image_publisher": "ignore", + "image_sku": "ignore", + "location": "ignore", + "subscription_id": "ignore", + "os_type": constants.Target_Linux, + "communicator": "none", + "lab_resource_group_name": "ignore", + "lab_virtual_network_name": "ignore", + } + + _, _, err := newConfig(config, getPackerConfiguration()) + if err != nil { + t.Fatalf("failed to use device login for Linux: %s", err) + } +} + +func TestConfigShouldAcceptTags(t *testing.T) { + config := map[string]interface{}{ + "capture_name_prefix": "ignore", + "capture_container_name": "ignore", + "image_offer": "ignore", + "image_publisher": "ignore", + "image_sku": "ignore", + "location": "ignore", + "subscription_id": "ignore", + "communicator": "none", + "lab_resource_group_name": "ignore", + "lab_virtual_network_name": "ignore", + // Does not matter for this test case, just pick one. + "os_type": constants.Target_Linux, + "azure_tags": map[string]string{ + "tag01": "value01", + "tag02": "value02", + }, + } + + c, _, err := newConfig(config, getPackerConfiguration()) + + if err != nil { + t.Fatal(err) + } + + if len(c.AzureTags) != 2 { + t.Fatalf("expected to find 2 tags, but got %d", len(c.AzureTags)) + } + + if _, ok := c.AzureTags["tag01"]; !ok { + t.Error("expected to find key=\"tag01\", but did not") + } + if _, ok := c.AzureTags["tag02"]; !ok { + t.Error("expected to find key=\"tag02\", but did not") + } + + value := c.AzureTags["tag01"] + if *value != "value01" { + t.Errorf("expected AzureTags[\"tag01\"] to have value \"value01\", but got %q", *value) + } + + value = c.AzureTags["tag02"] + if *value != "value02" { + t.Errorf("expected AzureTags[\"tag02\"] to have value \"value02\", but got %q", *value) + } +} + +func TestConfigShouldRejectTagsInExcessOf15AcceptTags(t *testing.T) { + tooManyTags := map[string]string{} + for i := 0; i < 16; i++ { + tooManyTags[fmt.Sprintf("tag%.2d", i)] = "ignored" + } + + config := map[string]interface{}{ + "capture_name_prefix": "ignore", + "capture_container_name": "ignore", + "image_offer": "ignore", + "image_publisher": "ignore", + "image_sku": "ignore", + "location": "ignore", + "subscription_id": "ignore", + "communicator": "none", + "lab_resource_group_name": "ignore", + "lab_virtual_network_name": "ignore", + // Does not matter for this test case, just pick one. + "os_type": constants.Target_Linux, + "azure_tags": tooManyTags, + } + + _, _, err := newConfig(config, getPackerConfiguration()) + + if err == nil { + t.Fatal("expected config to reject based on an excessive amount of tags (> 15)") + } +} + +func TestConfigShouldRejectExcessiveTagNameLength(t *testing.T) { + nameTooLong := make([]byte, 513) + for i := range nameTooLong { + nameTooLong[i] = 'a' + } + + tags := map[string]string{} + tags[string(nameTooLong)] = "ignored" + + config := map[string]interface{}{ + "capture_name_prefix": "ignore", + "capture_container_name": "ignore", + "image_offer": "ignore", + "image_publisher": "ignore", + "image_sku": "ignore", + "location": "ignore", + "subscription_id": "ignore", + "communicator": "none", + "lab_resource_group_name": "ignore", + "lab_virtual_network_name": "ignore", + // Does not matter for this test case, just pick one. + "os_type": constants.Target_Linux, + "azure_tags": tags, + } + + _, _, err := newConfig(config, getPackerConfiguration()) + if err == nil { + t.Fatal("expected config to reject tag name based on length (> 512)") + } +} + +func TestConfigShouldRejectExcessiveTagValueLength(t *testing.T) { + valueTooLong := make([]byte, 257) + for i := range valueTooLong { + valueTooLong[i] = 'a' + } + + tags := map[string]string{} + tags["tag01"] = string(valueTooLong) + + config := map[string]interface{}{ + "capture_name_prefix": "ignore", + "capture_container_name": "ignore", + "image_offer": "ignore", + "image_publisher": "ignore", + "image_sku": "ignore", + "location": "ignore", + "subscription_id": "ignore", + "communicator": "none", + "lab_resource_group_name": "ignore", + "lab_virtual_network_name": "ignore", + // Does not matter for this test case, just pick one. + "os_type": constants.Target_Linux, + "azure_tags": tags, + } + + _, _, err := newConfig(config, getPackerConfiguration()) + if err == nil { + t.Fatal("expected config to reject tag value based on length (> 256)") + } +} + +func TestConfigShouldAcceptPlatformManagedImageBuild(t *testing.T) { + config := map[string]interface{}{ + "image_offer": "ignore", + "image_publisher": "ignore", + "image_sku": "ignore", + "location": "ignore", + "subscription_id": "ignore", + "communicator": "none", + "managed_image_resource_group_name": "ignore", + "managed_image_name": "ignore", + "lab_resource_group_name": "ignore", + "lab_virtual_network_name": "ignore", + + // Does not matter for this test case, just pick one. + "os_type": constants.Target_Linux, + } + + _, _, err := newConfig(config, getPackerConfiguration()) + if err != nil { + t.Fatal("expected config to accept platform managed image build") + } +} + +func TestConfigShouldAcceptManagedImageStorageAccountTypes(t *testing.T) { + config := map[string]interface{}{ + "custom_managed_image_resource_group_name": "ignore", + "custom_managed_image_name": "ignore", + "location": "ignore", + "subscription_id": "ignore", + "communicator": "none", + "managed_image_resource_group_name": "ignore", + "managed_image_name": "ignore", + "lab_resource_group_name": "ignore", + "lab_virtual_network_name": "ignore", + + // Does not matter for this test case, just pick one. + "os_type": constants.Target_Linux, + } + + storage_account_types := []string{"Premium_LRS", "Standard_LRS"} + + for _, x := range storage_account_types { + config["managed_image_storage_account_type"] = x + _, _, err := newConfig(config, getPackerConfiguration()) + if err != nil { + t.Fatalf("expected config to accept a managed_image_storage_account_type of %q", x) + } + } +} + +func TestConfigShouldAcceptDiskCachingTypes(t *testing.T) { + config := map[string]interface{}{ + "custom_managed_image_resource_group_name": "ignore", + "custom_managed_image_name": "ignore", + "location": "ignore", + "subscription_id": "ignore", + "communicator": "none", + "managed_image_resource_group_name": "ignore", + "managed_image_name": "ignore", + "lab_resource_group_name": "ignore", + "lab_virtual_network_name": "ignore", + + // Does not matter for this test case, just pick one. + "os_type": constants.Target_Linux, + } + + storage_account_types := []string{"None", "ReadOnly", "ReadWrite"} + + for _, x := range storage_account_types { + config["disk_caching_type"] = x + _, _, err := newConfig(config, getPackerConfiguration()) + if err != nil { + t.Fatalf("expected config to accept a disk_caching_type of %q", x) + } + } +} + +func TestConfigAdditionalDiskDefaultIsNil(t *testing.T) { + c, _, _ := newConfig(getDtlBuilderConfiguration(), getPackerConfiguration()) + if c.AdditionalDiskSize != nil { + t.Errorf("Expected Config to not have a set of additional disks, but got a non nil value") + } +} + +func TestConfigAdditionalDiskOverrideDefault(t *testing.T) { + config := map[string]string{ + "capture_name_prefix": "ignore", + "capture_container_name": "ignore", + "location": "ignore", + "image_url": "ignore", + "subscription_id": "ignore", + "os_type": constants.Target_Linux, + "communicator": "none", + "lab_resource_group_name": "ignore", + "lab_virtual_network_name": "ignore", + } + + diskconfig := map[string][]int32{ + "disk_additional_size": {32, 64}, + } + + c, _, _ := newConfig(config, diskconfig, getPackerConfiguration()) + if c.AdditionalDiskSize == nil { + t.Errorf("Expected Config to have a set of additional disks, but got nil") + } + if len(c.AdditionalDiskSize) != 2 { + t.Errorf("Expected Config to have a 2 additional disks, but got %d additional disks", len(c.AdditionalDiskSize)) + } + if c.AdditionalDiskSize[0] != 32 { + t.Errorf("Expected Config to have the first additional disks of size 32Gb, but got %dGb", c.AdditionalDiskSize[0]) + } + if c.AdditionalDiskSize[1] != 64 { + t.Errorf("Expected Config to have the second additional disks of size 64Gb, but got %dGb", c.AdditionalDiskSize[1]) + } +} + +func TestConfigShouldAllowSharedImageGalleryOptions(t *testing.T) { + config := map[string]interface{}{ + "location": "ignore", + "subscription_id": "ignore", + "os_type": "linux", + "lab_resource_group_name": "ignore", + "lab_virtual_network_name": "ignore", + "shared_image_gallery": map[string]string{ + "subscription": "ignore", + "resource_group": "ignore", + "gallery_name": "ignore", + "image_name": "ignore", + "image_version": "ignore", + }, + } + + _, _, err := newConfig(config, getPackerConfiguration()) + if err == nil { + t.Log("expected config to accept Shared Image Gallery options", err) + } + +} + +func TestConfigShouldRejectSharedImageGalleryWithVhdTarget(t *testing.T) { + config := map[string]interface{}{ + "location": "ignore", + "subscription_id": "ignore", + "os_type": "linux", + "shared_image_gallery": map[string]string{ + "subscription": "ignore", + "resource_group": "ignore", + "gallery_name": "ignore", + "image_name": "ignore", + "image_version": "ignore", + }, + "capture_container_name": "ignore", + "capture_name_prefix": "ignore", + "lab_resource_group_name": "ignore", + "lab_virtual_network_name": "ignore", + } + + _, _, err := newConfig(config, getPackerConfiguration()) + if err != nil { + t.Log("expected an error if Shared Image Gallery source is used with VHD target", err) + } +} + +func getDtlBuilderConfiguration() map[string]string { + m := make(map[string]string) + for _, v := range requiredConfigValues { + m[v] = "ignored00" + } + + m["communicator"] = "none" + m["os_type"] = constants.Target_Linux + return m +} + +func getPackerConfiguration() interface{} { + config := map[string]interface{}{ + "packer_build_name": "azure-arm-vm", + "packer_builder_type": "azure-arm-vm", + "packer_debug": "false", + "packer_force": "false", + "packer_template_path": "/home/jenkins/azure-arm-vm/template.json", + } + + return config +} + +func getPackerCommunicatorConfiguration() map[string]string { + config := map[string]string{ + "ssh_timeout": "1h", + "winrm_timeout": "2h", + } + + return config +} diff --git a/builder/azure/dtl/inspector.go b/builder/azure/dtl/inspector.go new file mode 100644 index 000000000..824963f75 --- /dev/null +++ b/builder/azure/dtl/inspector.go @@ -0,0 +1,71 @@ +package dtl + +import ( + "bytes" + "io/ioutil" + "log" + "net/http" + + "io" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/hashicorp/packer/builder/azure/common/logutil" +) + +func chop(data []byte, maxlen int64) string { + s := string(data) + if int64(len(s)) > maxlen { + s = s[:maxlen] + "..." + } + return s +} + +func handleBody(body io.ReadCloser, maxlen int64) (io.ReadCloser, string) { + if body == nil { + return nil, "" + } + + defer body.Close() + + b, err := ioutil.ReadAll(body) + if err != nil { + return nil, "" + } + + return ioutil.NopCloser(bytes.NewReader(b)), chop(b, maxlen) +} + +func withInspection(maxlen int64) autorest.PrepareDecorator { + return func(p autorest.Preparer) autorest.Preparer { + return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { + body, bodyString := handleBody(r.Body, maxlen) + r.Body = body + + log.Print("Azure request", logutil.Fields{ + "method": r.Method, + "request": r.URL.String(), + "body": bodyString, + }) + return p.Prepare(r) + }) + } +} + +func byInspecting(maxlen int64) autorest.RespondDecorator { + return func(r autorest.Responder) autorest.Responder { + return autorest.ResponderFunc(func(resp *http.Response) error { + body, bodyString := handleBody(resp.Body, maxlen) + resp.Body = body + + log.Print("Azure response", logutil.Fields{ + "status": resp.Status, + "method": resp.Request.Method, + "request": resp.Request.URL.String(), + "x-ms-request-id": azure.ExtractRequestID(resp), + "body": bodyString, + }) + return r.Respond(resp) + }) + } +} diff --git a/builder/azure/dtl/openssh_key_pair.go b/builder/azure/dtl/openssh_key_pair.go new file mode 100644 index 000000000..3e2f5a371 --- /dev/null +++ b/builder/azure/dtl/openssh_key_pair.go @@ -0,0 +1,59 @@ +package dtl + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/pem" + "fmt" + "time" + + "golang.org/x/crypto/ssh" +) + +const ( + KeySize = 2048 +) + +type OpenSshKeyPair struct { + privateKey *rsa.PrivateKey + publicKey ssh.PublicKey +} + +func NewOpenSshKeyPair() (*OpenSshKeyPair, error) { + return NewOpenSshKeyPairWithSize(KeySize) +} + +func NewOpenSshKeyPairWithSize(keySize int) (*OpenSshKeyPair, error) { + privateKey, err := rsa.GenerateKey(rand.Reader, keySize) + if err != nil { + return nil, err + } + + publicKey, err := ssh.NewPublicKey(&privateKey.PublicKey) + if err != nil { + return nil, err + } + + return &OpenSshKeyPair{ + privateKey: privateKey, + publicKey: publicKey, + }, nil +} + +func (s *OpenSshKeyPair) AuthorizedKey() string { + return fmt.Sprintf("%s %s packer Azure Deployment%s", + s.publicKey.Type(), + base64.StdEncoding.EncodeToString(s.publicKey.Marshal()), + time.Now().Format(time.RFC3339)) +} + +func (s *OpenSshKeyPair) PrivateKey() []byte { + privateKey := pem.EncodeToMemory(&pem.Block{ + Type: "RSA PRIVATE KEY", + Bytes: x509.MarshalPKCS1PrivateKey(s.privateKey), + }) + + return privateKey +} diff --git a/builder/azure/dtl/openssh_key_pair_test.go b/builder/azure/dtl/openssh_key_pair_test.go new file mode 100644 index 000000000..d4aa6e94d --- /dev/null +++ b/builder/azure/dtl/openssh_key_pair_test.go @@ -0,0 +1,37 @@ +package dtl + +import ( + "testing" + + "golang.org/x/crypto/ssh" +) + +func TestFart(t *testing.T) { + +} + +func TestAuthorizedKeyShouldParse(t *testing.T) { + testSubject, err := NewOpenSshKeyPairWithSize(512) + if err != nil { + t.Fatalf("Failed to create a new OpenSSH key pair, err=%s.", err) + } + + authorizedKey := testSubject.AuthorizedKey() + + _, _, _, _, err = ssh.ParseAuthorizedKey([]byte(authorizedKey)) + if err != nil { + t.Fatalf("Failed to parse the authorized key, err=%s", err) + } +} + +func TestPrivateKeyShouldParse(t *testing.T) { + testSubject, err := NewOpenSshKeyPairWithSize(512) + if err != nil { + t.Fatalf("Failed to create a new OpenSSH key pair, err=%s.", err) + } + + _, err = ssh.ParsePrivateKey(testSubject.PrivateKey()) + if err != nil { + t.Fatalf("Failed to parse the private key, err=%s\n", err) + } +} diff --git a/builder/azure/dtl/resource_resolver.go b/builder/azure/dtl/resource_resolver.go new file mode 100644 index 000000000..d5c486fd8 --- /dev/null +++ b/builder/azure/dtl/resource_resolver.go @@ -0,0 +1,141 @@ +package dtl + +// Code to resolve resources that are required by the API. These resources +// can most likely be resolved without asking the user, thereby reducing the +// amount of configuration they need to provide. +// +// Resource resolver differs from config retriever because resource resolver +// requires a client to communicate with the Azure API. A config retriever is +// used to determine values without use of a client. + +import ( + "context" + "fmt" + "strings" + + "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute" +) + +type resourceResolver struct { + client *AzureClient + findVirtualNetworkResourceGroup func(*AzureClient, string) (string, error) + findVirtualNetworkSubnet func(*AzureClient, string, string) (string, error) +} + +func newResourceResolver(client *AzureClient) *resourceResolver { + return &resourceResolver{ + client: client, + findVirtualNetworkResourceGroup: findVirtualNetworkResourceGroup, + findVirtualNetworkSubnet: findVirtualNetworkSubnet, + } +} + +func (s *resourceResolver) Resolve(c *Config) error { + // if s.shouldResolveResourceGroup(c) { + // resourceGroupName, err := s.findVirtualNetworkResourceGroup(s.client, c.VirtualNetworkName) + // if err != nil { + // return err + // } + + // subnetName, err := s.findVirtualNetworkSubnet(s.client, resourceGroupName, c.VirtualNetworkName) + // if err != nil { + // return err + // } + + // c.VirtualNetworkResourceGroupName = resourceGroupName + // c.VirtualNetworkSubnetName = subnetName + // } + + if s.shouldResolveManagedImageName(c) { + image, err := findManagedImageByName(s.client, c.CustomManagedImageName, c.CustomManagedImageResourceGroupName) + if err != nil { + return err + } + + c.customManagedImageID = *image.ID + } + + return nil +} + +// func (s *resourceResolver) shouldResolveResourceGroup(c *Config) bool { +// return c.VirtualNetworkName != "" && c.VirtualNetworkResourceGroupName == "" +// } + +func (s *resourceResolver) shouldResolveManagedImageName(c *Config) bool { + return c.CustomManagedImageName != "" +} + +func getResourceGroupNameFromId(id string) string { + // "/subscriptions/3f499422-dd76-4114-8859-86d526c9deb6/resourceGroups/packer-Resource-Group-yylnwsl30j/providers/... + xs := strings.Split(id, "/") + return xs[4] +} + +func findManagedImageByName(client *AzureClient, name, resourceGroupName string) (*compute.Image, error) { + images, err := client.ImagesClient.ListByResourceGroupComplete(context.TODO(), resourceGroupName) + if err != nil { + return nil, err + } + + for images.NotDone() { + image := images.Value() + if strings.EqualFold(name, *image.Name) { + return &image, nil + } + if err = images.Next(); err != nil { + return nil, err + } + } + + return nil, fmt.Errorf("Cannot find an image named '%s' in the resource group '%s'", name, resourceGroupName) +} + +func findVirtualNetworkResourceGroup(client *AzureClient, name string) (string, error) { + virtualNetworks, err := client.VirtualNetworksClient.ListAllComplete(context.TODO()) + if err != nil { + return "", err + } + + resourceGroupNames := make([]string, 0) + for virtualNetworks.NotDone() { + virtualNetwork := virtualNetworks.Value() + if strings.EqualFold(name, *virtualNetwork.Name) { + rgn := getResourceGroupNameFromId(*virtualNetwork.ID) + resourceGroupNames = append(resourceGroupNames, rgn) + } + if err = virtualNetworks.Next(); err != nil { + return "", err + } + } + + if len(resourceGroupNames) == 0 { + return "", fmt.Errorf("Cannot find a resource group with a virtual network called %q", name) + } + + if len(resourceGroupNames) > 1 { + return "", fmt.Errorf("Found multiple resource groups with a virtual network called %q, please use virtual_network_subnet_name and virtual_network_resource_group_name to disambiguate", name) + } + + return resourceGroupNames[0], nil +} + +func findVirtualNetworkSubnet(client *AzureClient, resourceGroupName string, name string) (string, error) { + subnets, err := client.SubnetsClient.List(context.TODO(), resourceGroupName, name) + if err != nil { + return "", err + } + + subnetList := subnets.Values() // only first page of subnets, but only interested in ==0 or >1 + + if len(subnetList) == 0 { + return "", fmt.Errorf("Cannot find a subnet in the resource group %q associated with the virtual network called %q", resourceGroupName, name) + } + + if len(subnetList) > 1 { + return "", fmt.Errorf("Found multiple subnets in the resource group %q associated with the virtual network called %q, please use virtual_network_subnet_name and virtual_network_resource_group_name to disambiguate", resourceGroupName, name) + } + + subnet := subnetList[0] + return *subnet.Name, nil +} diff --git a/builder/azure/dtl/step.go b/builder/azure/dtl/step.go new file mode 100644 index 000000000..6418e5c15 --- /dev/null +++ b/builder/azure/dtl/step.go @@ -0,0 +1,20 @@ +package dtl + +import ( + "github.com/hashicorp/packer/builder/azure/common/constants" + "github.com/hashicorp/packer/helper/multistep" +) + +func processStepResult( + err error, sayError func(error), state multistep.StateBag) multistep.StepAction { + + if err != nil { + state.Put(constants.Error, err) + sayError(err) + + return multistep.ActionHalt + } + + return multistep.ActionContinue + +} diff --git a/builder/azure/dtl/step_capture_image.go b/builder/azure/dtl/step_capture_image.go new file mode 100644 index 000000000..30f726a7d --- /dev/null +++ b/builder/azure/dtl/step_capture_image.go @@ -0,0 +1,125 @@ +package dtl + +import ( + "context" + "fmt" + + "github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl" + + "github.com/hashicorp/packer/builder/azure/common/constants" + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" +) + +type StepCaptureImage struct { + client *AzureClient + captureManagedImage func(ctx context.Context) error + get func(client *AzureClient) *CaptureTemplate + config *Config + say func(message string) + error func(e error) +} + +func NewStepCaptureImage(client *AzureClient, ui packer.Ui, config *Config) *StepCaptureImage { + var step = &StepCaptureImage{ + client: client, + get: func(client *AzureClient) *CaptureTemplate { + return client.Template + }, + config: config, + say: func(message string) { + ui.Say(message) + }, + error: func(e error) { + ui.Error(e.Error()) + }, + } + + // step.captureVhd = step.captureImage + step.captureManagedImage = step.captureImageFromVM + + return step +} + +func (s *StepCaptureImage) captureImageFromVM(ctx context.Context) error { + imageID := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.DevTestLab/labs/%s/virtualMachines/%s", + s.config.ClientConfig.SubscriptionID, + s.config.tmpResourceGroupName, + s.config.LabName, + s.config.tmpComputeName) + + customImageProperties := dtl.CustomImageProperties{} + + if s.config.OSType == constants.Target_Linux { + customImageProperties = dtl.CustomImageProperties{ + VM: &dtl.CustomImagePropertiesFromVM{ + LinuxOsInfo: &dtl.LinuxOsInfo{ + LinuxOsState: dtl.DeprovisionRequested, + }, + SourceVMID: &imageID, + }, + } + } else if s.config.OSType == constants.Target_Windows { + customImageProperties = dtl.CustomImageProperties{ + VM: &dtl.CustomImagePropertiesFromVM{ + WindowsOsInfo: &dtl.WindowsOsInfo{ + WindowsOsState: dtl.SysprepRequested, + }, + SourceVMID: &imageID, + }, + } + } + + customImage := &dtl.CustomImage{ + Name: &s.config.ManagedImageName, + CustomImageProperties: &customImageProperties, + } + + f, err := s.client.DtlCustomImageClient.CreateOrUpdate(ctx, s.config.LabResourceGroupName, s.config.LabName, s.config.ManagedImageName, *customImage) + if err == nil { + err = f.WaitForCompletionRef(ctx, s.client.DtlCustomImageClient.Client) + } + if err != nil { + s.say("Error from Capture Image") + s.say(s.client.LastError.Error()) + } + + return err +} + +func (s *StepCaptureImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { + s.say("Capturing image ...") + + var computeName = state.Get(constants.ArmComputeName).(string) + var location = state.Get(constants.ArmLocation).(string) + var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string) + + s.say(fmt.Sprintf(" -> Compute ResourceGroupName : '%s'", resourceGroupName)) + s.say(fmt.Sprintf(" -> Compute Name : '%s'", computeName)) + s.say(fmt.Sprintf(" -> Compute Location : '%s'", location)) + + err := s.captureImageFromVM(ctx) + + if err != nil { + s.error(err) + state.Put(constants.Error, err) + + return multistep.ActionHalt + } + + // HACK(chrboum): I do not like this. The capture method should be returning this value + // instead having to pass in another lambda. + // + // Having to resort to capturing the template via an inspector is hack, and once I can + // resolve that I can cleanup this code too. See the comments in azure_client.go for more + // details. + // [paulmey]: autorest.Future now has access to the last http.Response, but I'm not sure if + // the body is still accessible. + template := s.get(s.client) + state.Put(constants.ArmCaptureTemplate, template) + + return multistep.ActionContinue +} + +func (*StepCaptureImage) Cleanup(multistep.StateBag) { +} diff --git a/builder/azure/dtl/step_delete_virtual_machine.go b/builder/azure/dtl/step_delete_virtual_machine.go new file mode 100644 index 000000000..a94f72d6a --- /dev/null +++ b/builder/azure/dtl/step_delete_virtual_machine.go @@ -0,0 +1,61 @@ +package dtl + +import ( + "context" + "fmt" + + "github.com/hashicorp/packer/builder/azure/common/constants" + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" +) + +type StepDeleteVirtualMachine struct { + client *AzureClient + config *Config + delete func(ctx context.Context, resourceGroupName string, computeName string, state multistep.StateBag) error + say func(message string) + error func(e error) +} + +func NewStepDeleteVirtualMachine(client *AzureClient, ui packer.Ui, config *Config) *StepDeleteVirtualMachine { + var step = &StepDeleteVirtualMachine{ + client: client, + config: config, + say: func(message string) { ui.Say(message) }, + error: func(e error) { ui.Error(e.Error()) }, + } + + step.delete = step.deleteVirtualMachine + return step +} + +func (s *StepDeleteVirtualMachine) deleteVirtualMachine(ctx context.Context, resourceGroupName string, vmName string, state multistep.StateBag) error { + f, err := s.client.DtlVirtualMachineClient.Delete(ctx, resourceGroupName, s.config.LabName, vmName) + if err == nil { + err = f.WaitForCompletionRef(ctx, s.client.DtlVirtualMachineClient.Client) + } + if err != nil { + s.say("Error from delete VM") + s.say(s.client.LastError.Error()) + } + + return err +} + +func (s *StepDeleteVirtualMachine) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { + s.say("Deleting the virtual machine ...") + + var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string) + var computeName = state.Get(constants.ArmComputeName).(string) + + s.say(fmt.Sprintf(" -> ResourceGroupName : '%s'", resourceGroupName)) + s.say(fmt.Sprintf(" -> ComputeName : '%s'", computeName)) + + err := s.deleteVirtualMachine(ctx, resourceGroupName, computeName, state) + + s.say("Deleting virtual machine ...Complete") + return processStepResult(err, s.error, state) +} + +func (*StepDeleteVirtualMachine) Cleanup(multistep.StateBag) { +} diff --git a/builder/azure/dtl/step_deploy_template.go b/builder/azure/dtl/step_deploy_template.go new file mode 100644 index 000000000..0cface5ff --- /dev/null +++ b/builder/azure/dtl/step_deploy_template.go @@ -0,0 +1,192 @@ +package dtl + +import ( + "context" + "errors" + "fmt" + "net/url" + "strings" + + "github.com/hashicorp/packer/builder/azure/common/constants" + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" +) + +type StepDeployTemplate struct { + client *AzureClient + deploy func(ctx context.Context, resourceGroupName string, deploymentName string, state multistep.StateBag) error + delete func(ctx context.Context, client *AzureClient, resourceType string, resourceName string, resourceGroupName string) error + disk func(ctx context.Context, resourceGroupName string, computeName string) (string, string, error) + deleteDisk func(ctx context.Context, imageType string, imageName string, resourceGroupName string) error + say func(message string) + error func(e error) + config *Config + factory templateFactoryFuncDtl + name string +} + +func NewStepDeployTemplate(client *AzureClient, ui packer.Ui, config *Config, deploymentName string, factory templateFactoryFuncDtl) *StepDeployTemplate { + var step = &StepDeployTemplate{ + client: client, + say: func(message string) { ui.Say(message) }, + error: func(e error) { ui.Error(e.Error()) }, + config: config, + factory: factory, + name: deploymentName, + } + + step.deploy = step.deployTemplate + step.delete = deleteResource + step.disk = step.getImageDetails + step.deleteDisk = step.deleteImage + return step +} + +func (s *StepDeployTemplate) deployTemplate(ctx context.Context, resourceGroupName string, deploymentName string, state multistep.StateBag) error { + + vmlistPage, err := s.client.DtlVirtualMachineClient.List(ctx, s.config.tmpResourceGroupName, s.config.LabName, "", "", nil, "") + + if err != nil { + s.say(s.client.LastError.Error()) + return err + } + + vmList := vmlistPage.Values() + for i := range vmList { + if *vmList[i].Name == s.config.tmpComputeName { + return fmt.Errorf("Error: Virtual Machine %s already exists. Please use another name", s.config.tmpComputeName) + } + } + + s.say(fmt.Sprintf("Creating Virtual Machine %s", s.config.tmpComputeName)) + labMachine, err := s.factory(s.config) + if err != nil { + return err + } + + f, err := s.client.DtlLabsClient.CreateEnvironment(ctx, s.config.tmpResourceGroupName, s.config.LabName, *labMachine) + + if err == nil { + err = f.WaitForCompletionRef(ctx, s.client.DtlLabsClient.Client) + } + if err != nil { + s.say(s.client.LastError.Error()) + return err + } + expand := "Properties($expand=ComputeVm,Artifacts,NetworkInterface)" + + vm, err := s.client.DtlVirtualMachineClient.Get(ctx, s.config.tmpResourceGroupName, s.config.LabName, s.config.tmpComputeName, expand) + if err != nil { + s.say(s.client.LastError.Error()) + } + xs := strings.Split(*vm.LabVirtualMachineProperties.ComputeID, "/") + s.config.VMCreationResourceGroup = xs[4] + + s.say(fmt.Sprintf(" -> VM FQDN : '%s'", *vm.Fqdn)) + + state.Put(constants.SSHHost, *vm.Fqdn) + s.config.tmpFQDN = *vm.Fqdn + + // Resuing the Resource group name from common constants as all steps depend on it. + state.Put(constants.ArmResourceGroupName, s.config.VMCreationResourceGroup) + + s.say(fmt.Sprintf(" -> VM ResourceGroupName : '%s'", s.config.VMCreationResourceGroup)) + + return err +} + +func (s *StepDeployTemplate) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { + s.say("Deploying deployment template ...") + + var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string) + + s.say(fmt.Sprintf(" -> Lab ResourceGroupName : '%s'", resourceGroupName)) + + return processStepResult( + s.deploy(ctx, resourceGroupName, s.name, state), + s.error, state) +} + +func (s *StepDeployTemplate) getImageDetails(ctx context.Context, resourceGroupName string, computeName string) (string, string, error) { + //We can't depend on constants.ArmOSDiskVhd being set + var imageName string + var imageType string + vm, err := s.client.VirtualMachinesClient.Get(ctx, resourceGroupName, computeName, "") + if err != nil { + return imageName, imageType, err + } else { + if vm.StorageProfile.OsDisk.Vhd != nil { + imageType = "image" + imageName = *vm.StorageProfile.OsDisk.Vhd.URI + } else { + imageType = "Microsoft.Compute/disks" + imageName = *vm.StorageProfile.OsDisk.ManagedDisk.ID + } + } + return imageType, imageName, nil +} + +//TODO(paulmey): move to helpers file +func deleteResource(ctx context.Context, client *AzureClient, resourceType string, resourceName string, resourceGroupName string) error { + switch resourceType { + case "Microsoft.Compute/virtualMachines": + f, err := client.VirtualMachinesClient.Delete(ctx, resourceGroupName, resourceName) + if err == nil { + err = f.WaitForCompletionRef(ctx, client.VirtualMachinesClient.Client) + } + return err + case "Microsoft.Network/networkInterfaces": + f, err := client.InterfacesClient.Delete(ctx, resourceGroupName, resourceName) + if err == nil { + err = f.WaitForCompletionRef(ctx, client.InterfacesClient.Client) + } + return err + case "Microsoft.Network/virtualNetworks": + f, err := client.VirtualNetworksClient.Delete(ctx, resourceGroupName, resourceName) + if err == nil { + err = f.WaitForCompletionRef(ctx, client.VirtualNetworksClient.Client) + } + return err + case "Microsoft.Network/publicIPAddresses": + f, err := client.PublicIPAddressesClient.Delete(ctx, resourceGroupName, resourceName) + if err == nil { + err = f.WaitForCompletionRef(ctx, client.PublicIPAddressesClient.Client) + } + return err + } + return nil +} + +func (s *StepDeployTemplate) deleteImage(ctx context.Context, imageType string, imageName string, resourceGroupName string) error { + // Managed disk + if imageType == "Microsoft.Compute/disks" { + xs := strings.Split(imageName, "/") + diskName := xs[len(xs)-1] + f, err := s.client.DisksClient.Delete(ctx, resourceGroupName, diskName) + if err == nil { + err = f.WaitForCompletionRef(ctx, s.client.DisksClient.Client) + } + return err + } + // VHD image + u, err := url.Parse(imageName) + if err != nil { + return err + } + xs := strings.Split(u.Path, "/") + if len(xs) < 3 { + return errors.New("Unable to parse path of image " + imageName) + } + var storageAccountName = xs[1] + var blobName = strings.Join(xs[2:], "/") + + blob := s.client.BlobStorageClient.GetContainerReference(storageAccountName).GetBlobReference(blobName) + err = blob.Delete(nil) + return err +} + +func (s *StepDeployTemplate) Cleanup(state multistep.StateBag) { + //Only clean up if this was an existing resource group and the resource group + //is marked as created + // Just return now +} diff --git a/builder/azure/dtl/step_power_off_compute.go b/builder/azure/dtl/step_power_off_compute.go new file mode 100644 index 000000000..794c3b751 --- /dev/null +++ b/builder/azure/dtl/step_power_off_compute.go @@ -0,0 +1,61 @@ +package dtl + +import ( + "context" + "fmt" + + "github.com/hashicorp/packer/builder/azure/common/constants" + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" +) + +type StepPowerOffCompute struct { + client *AzureClient + config *Config + powerOff func(ctx context.Context, resourceGroupName string, labName, computeName string) error + say func(message string) + error func(e error) +} + +func NewStepPowerOffCompute(client *AzureClient, ui packer.Ui, config *Config) *StepPowerOffCompute { + + var step = &StepPowerOffCompute{ + client: client, + config: config, + say: func(message string) { ui.Say(message) }, + error: func(e error) { ui.Error(e.Error()) }, + } + + step.powerOff = step.powerOffCompute + return step +} + +func (s *StepPowerOffCompute) powerOffCompute(ctx context.Context, resourceGroupName string, labName, computeName string) error { + //f, err := s.client.VirtualMachinesClient.Deallocate(ctx, resourceGroupName, computeName) + f, err := s.client.DtlVirtualMachineClient.Stop(ctx, resourceGroupName, labName, computeName) + if err == nil { + err = f.WaitForCompletionRef(ctx, s.client.DtlVirtualMachineClient.Client) + } + if err != nil { + s.say(s.client.LastError.Error()) + } + return err +} + +func (s *StepPowerOffCompute) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { + s.say("Powering off machine ...") + + var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string) + var computeName = state.Get(constants.ArmComputeName).(string) + + s.say(fmt.Sprintf(" -> ResourceGroupName : '%s'", resourceGroupName)) + s.say(fmt.Sprintf(" -> ComputeName : '%s'", computeName)) + + err := s.powerOff(ctx, s.config.LabResourceGroupName, s.config.LabName, computeName) + + s.say("Powering off machine ...Complete") + return processStepResult(err, s.error, state) +} + +func (*StepPowerOffCompute) Cleanup(multistep.StateBag) { +} diff --git a/builder/azure/dtl/step_publish_to_shared_image_gallery.go b/builder/azure/dtl/step_publish_to_shared_image_gallery.go new file mode 100644 index 000000000..3ed56794e --- /dev/null +++ b/builder/azure/dtl/step_publish_to_shared_image_gallery.go @@ -0,0 +1,126 @@ +package dtl + +import ( + "context" + "fmt" + + "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-03-01/compute" + "github.com/hashicorp/packer/builder/azure/common/constants" + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" +) + +type StepPublishToSharedImageGallery struct { + client *AzureClient + publish func(ctx context.Context, mdiID, miSigPubRg, miSIGalleryName, miSGImageName, miSGImageVersion string, miSigReplicationRegions []string, location string, tags map[string]*string) (string, error) + say func(message string) + error func(e error) + toSIG func() bool +} + +func NewStepPublishToSharedImageGallery(client *AzureClient, ui packer.Ui, config *Config) *StepPublishToSharedImageGallery { + var step = &StepPublishToSharedImageGallery{ + client: client, + say: func(message string) { + ui.Say(message) + }, + error: func(e error) { + ui.Error(e.Error()) + }, + toSIG: func() bool { + return config.isManagedImage() && config.SharedGalleryDestination.SigDestinationGalleryName != "" + }, + } + + step.publish = step.publishToSig + return step +} + +func (s *StepPublishToSharedImageGallery) publishToSig(ctx context.Context, mdiID string, miSigPubRg string, miSIGalleryName string, miSGImageName string, miSGImageVersion string, miSigReplicationRegions []string, location string, tags map[string]*string) (string, error) { + + replicationRegions := make([]compute.TargetRegion, len(miSigReplicationRegions)) + for i, v := range miSigReplicationRegions { + regionName := v + replicationRegions[i] = compute.TargetRegion{Name: ®ionName} + } + + galleryImageVersion := compute.GalleryImageVersion{ + Location: &location, + Tags: tags, + GalleryImageVersionProperties: &compute.GalleryImageVersionProperties{ + PublishingProfile: &compute.GalleryImageVersionPublishingProfile{ + Source: &compute.GalleryArtifactSource{ + ManagedImage: &compute.ManagedArtifact{ + ID: &mdiID, + }, + }, + TargetRegions: &replicationRegions, + }, + }, + } + + f, err := s.client.GalleryImageVersionsClient.CreateOrUpdate(ctx, miSigPubRg, miSIGalleryName, miSGImageName, miSGImageVersion, galleryImageVersion) + + if err != nil { + s.say(s.client.LastError.Error()) + return "", err + } + + err = f.WaitForCompletionRef(ctx, s.client.GalleryImageVersionsClient.Client) + + if err != nil { + s.say(s.client.LastError.Error()) + return "", err + } + + createdSGImageVersion, err := f.Result(s.client.GalleryImageVersionsClient) + + if err != nil { + s.say(s.client.LastError.Error()) + return "", err + } + + s.say(fmt.Sprintf(" -> Shared Gallery Image Version ID : '%s'", *(createdSGImageVersion.ID))) + return *(createdSGImageVersion.ID), nil +} + +func (s *StepPublishToSharedImageGallery) Run(ctx context.Context, stateBag multistep.StateBag) multistep.StepAction { + if !s.toSIG() { + return multistep.ActionContinue + } + + s.say("Publishing to Shared Image Gallery ...") + + var miSigPubRg = stateBag.Get(constants.ArmManagedImageSigPublishResourceGroup).(string) + var miSIGalleryName = stateBag.Get(constants.ArmManagedImageSharedGalleryName).(string) + var miSGImageName = stateBag.Get(constants.ArmManagedImageSharedGalleryImageName).(string) + var miSGImageVersion = stateBag.Get(constants.ArmManagedImageSharedGalleryImageVersion).(string) + var location = stateBag.Get(constants.ArmLocation).(string) + var tags = stateBag.Get(constants.ArmTags).(map[string]*string) + var miSigReplicationRegions = stateBag.Get(constants.ArmManagedImageSharedGalleryReplicationRegions).([]string) + var targetManagedImageResourceGroupName = stateBag.Get(constants.ArmManagedImageResourceGroupName).(string) + var targetManagedImageName = stateBag.Get(constants.ArmManagedImageName).(string) + var managedImageSubscription = stateBag.Get(constants.ArmManagedImageSubscription).(string) + var mdiID = fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/images/%s", managedImageSubscription, targetManagedImageResourceGroupName, targetManagedImageName) + + s.say(fmt.Sprintf(" -> MDI ID used for SIG publish : '%s'", mdiID)) + s.say(fmt.Sprintf(" -> SIG publish resource group : '%s'", miSigPubRg)) + s.say(fmt.Sprintf(" -> SIG gallery name : '%s'", miSIGalleryName)) + s.say(fmt.Sprintf(" -> SIG image name : '%s'", miSGImageName)) + s.say(fmt.Sprintf(" -> SIG image version : '%s'", miSGImageVersion)) + s.say(fmt.Sprintf(" -> SIG replication regions : '%v'", miSigReplicationRegions)) + createdGalleryImageVersionID, err := s.publish(ctx, mdiID, miSigPubRg, miSIGalleryName, miSGImageName, miSGImageVersion, miSigReplicationRegions, location, tags) + + if err != nil { + stateBag.Put(constants.Error, err) + s.error(err) + + return multistep.ActionHalt + } + + stateBag.Put(constants.ArmManagedImageSharedGalleryId, createdGalleryImageVersionID) + return multistep.ActionContinue +} + +func (*StepPublishToSharedImageGallery) Cleanup(multistep.StateBag) { +} diff --git a/builder/azure/dtl/step_save_winrm_password.go b/builder/azure/dtl/step_save_winrm_password.go new file mode 100644 index 000000000..006bd5c49 --- /dev/null +++ b/builder/azure/dtl/step_save_winrm_password.go @@ -0,0 +1,31 @@ +package dtl + +import ( + "context" + + "github.com/hashicorp/packer/builder/azure/common/constants" + commonhelper "github.com/hashicorp/packer/helper/common" + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" +) + +type StepSaveWinRMPassword struct { + Password string + BuildName string +} + +func (s *StepSaveWinRMPassword) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { + // store so that we can access this later during provisioning + err := commonhelper.SetSharedState("winrm_password", s.Password, s.BuildName) + if err != nil { + state.Put(constants.Error, err) + + return multistep.ActionHalt + } + packer.LogSecretFilter.Set(s.Password) + return multistep.ActionContinue +} + +func (s *StepSaveWinRMPassword) Cleanup(multistep.StateBag) { + commonhelper.RemoveSharedStateFile("winrm_password", s.BuildName) +} diff --git a/builder/azure/dtl/step_test.go b/builder/azure/dtl/step_test.go new file mode 100644 index 000000000..71ebb2b7a --- /dev/null +++ b/builder/azure/dtl/step_test.go @@ -0,0 +1,40 @@ +package dtl + +import ( + "fmt" + "testing" + + "github.com/hashicorp/packer/builder/azure/common/constants" + "github.com/hashicorp/packer/helper/multistep" +) + +func TestProcessStepResultShouldContinueForNonErrors(t *testing.T) { + stateBag := new(multistep.BasicStateBag) + + code := processStepResult(nil, func(error) { t.Fatal("Should not be called!") }, stateBag) + if _, ok := stateBag.GetOk(constants.Error); ok { + t.Errorf("Error was nil, but was still in the state bag.") + } + + if code != multistep.ActionContinue { + t.Errorf("Expected ActionContinue(%d), but got=%d", multistep.ActionContinue, code) + } +} + +func TestProcessStepResultShouldHaltOnError(t *testing.T) { + stateBag := new(multistep.BasicStateBag) + isSaidError := false + + code := processStepResult(fmt.Errorf("boom"), func(error) { isSaidError = true }, stateBag) + if _, ok := stateBag.GetOk(constants.Error); !ok { + t.Errorf("Error was non nil, but was not in the state bag.") + } + + if !isSaidError { + t.Errorf("Expected error to be said, but it was not.") + } + + if code != multistep.ActionHalt { + t.Errorf("Expected ActionHalt(%d), but got=%d", multistep.ActionHalt, code) + } +} diff --git a/builder/azure/dtl/template_factory.go b/builder/azure/dtl/template_factory.go new file mode 100644 index 000000000..821d43a03 --- /dev/null +++ b/builder/azure/dtl/template_factory.go @@ -0,0 +1,136 @@ +package dtl + +import ( + "fmt" + "strings" + + "github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl" +) + +type templateFactoryFuncDtl func(*Config) (*dtl.LabVirtualMachineCreationParameter, error) + +func newBool(val bool) *bool { + b := true + if val == b { + return &b + } else { + b = false + return &b + } +} + +func getCustomImageId(config *Config) *string { + if config.CustomManagedImageName != "" && config.CustomManagedImageResourceGroupName != "" { + customManagedImageID := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/images/%s", + config.ClientConfig.SubscriptionID, + config.CustomManagedImageResourceGroupName, + config.CustomManagedImageName) + return &customManagedImageID + } + return nil +} + +func GetVirtualMachineDeployment(config *Config) (*dtl.LabVirtualMachineCreationParameter, error) { + + galleryImageRef := dtl.GalleryImageReference{ + Offer: &config.ImageOffer, + Publisher: &config.ImagePublisher, + Sku: &config.ImageSku, + OsType: &config.OSType, + Version: &config.ImageVersion, + } + + labVirtualNetworkID := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.DevTestLab/labs/%s/virtualnetworks/%s", + config.ClientConfig.SubscriptionID, + config.tmpResourceGroupName, + config.LabName, + config.LabVirtualNetworkName) + + dtlArtifacts := []dtl.ArtifactInstallProperties{} + + if config.DtlArtifacts != nil { + for i := range config.DtlArtifacts { + if config.DtlArtifacts[i].RepositoryName == "" { + config.DtlArtifacts[i].RepositoryName = "public repo" + } + config.DtlArtifacts[i].ArtifactId = fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.DevTestLab/labs/%s/artifactSources/%s/artifacts/%s", + config.ClientConfig.SubscriptionID, + config.tmpResourceGroupName, + config.LabName, + config.DtlArtifacts[i].RepositoryName, + config.DtlArtifacts[i].ArtifactName) + + dparams := []dtl.ArtifactParameterProperties{} + for j := range config.DtlArtifacts[i].Parameters { + + dp := &dtl.ArtifactParameterProperties{} + dp.Name = &config.DtlArtifacts[i].Parameters[j].Name + dp.Value = &config.DtlArtifacts[i].Parameters[j].Value + + dparams = append(dparams, *dp) + } + dtlArtifact := &dtl.ArtifactInstallProperties{ + ArtifactTitle: &config.DtlArtifacts[i].ArtifactName, + ArtifactID: &config.DtlArtifacts[i].ArtifactId, + Parameters: &dparams, + } + dtlArtifacts = append(dtlArtifacts, *dtlArtifact) + } + } + + if strings.ToLower(config.OSType) == "windows" { + // Add mandatory Artifact + var winrma = "windows-winrm" + var artifactid = fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.DevTestLab/labs/%s/artifactSources/public repo/artifacts/%s", + config.ClientConfig.SubscriptionID, + config.tmpResourceGroupName, + config.LabName, + winrma) + + var hostname = "hostName" + //var hostNameValue = fmt.Sprintf("%s.%s.cloudapp.azure.com", config.VMName, config.Location) + dparams := []dtl.ArtifactParameterProperties{} + dp := &dtl.ArtifactParameterProperties{} + dp.Name = &hostname + dp.Value = &config.tmpFQDN + dparams = append(dparams, *dp) + + winrmArtifact := &dtl.ArtifactInstallProperties{ + ArtifactTitle: &winrma, + ArtifactID: &artifactid, + Parameters: &dparams, + } + dtlArtifacts = append(dtlArtifacts, *winrmArtifact) + } + + labMachineProps := &dtl.LabVirtualMachineCreationParameterProperties{ + CreatedByUserID: &config.ClientConfig.ClientID, + OwnerObjectID: &config.ClientConfig.ObjectID, + OsType: &config.OSType, + Size: &config.VMSize, + UserName: &config.UserName, + Password: &config.Password, + SSHKey: &config.sshAuthorizedKey, + IsAuthenticationWithSSHKey: newBool(true), + LabSubnetName: &config.LabSubnetName, + LabVirtualNetworkID: &labVirtualNetworkID, + DisallowPublicIPAddress: newBool(false), + GalleryImageReference: &galleryImageRef, + CustomImageID: getCustomImageId(config), + PlanID: &config.PlanID, + + AllowClaim: newBool(false), + StorageType: &config.StorageType, + VirtualMachineCreationSource: dtl.FromGalleryImage, + Artifacts: &dtlArtifacts, + } + + labMachine := &dtl.LabVirtualMachineCreationParameter{ + Name: &config.tmpComputeName, + Location: &config.Location, + Tags: config.AzureTags, + LabVirtualMachineCreationParameterProperties: labMachineProps, + } + + return labMachine, nil +} diff --git a/builder/azure/dtl/template_funcs.go b/builder/azure/dtl/template_funcs.go new file mode 100644 index 000000000..d76eda267 --- /dev/null +++ b/builder/azure/dtl/template_funcs.go @@ -0,0 +1,46 @@ +package dtl + +import ( + "bytes" + "text/template" + + packertpl "github.com/hashicorp/packer/common/template" +) + +func isValidByteValue(b byte) bool { + if '0' <= b && b <= '9' { + return true + } + if 'a' <= b && b <= 'z' { + return true + } + if 'A' <= b && b <= 'Z' { + return true + } + return b == '.' || b == '_' || b == '-' +} + +// Clean up image name by replacing invalid characters with "-" +// Names are not allowed to end in '.', '-', or '_' and are trimmed. +func templateCleanImageName(s string) string { + if ok, _ := assertManagedImageName(s, ""); ok { + return s + } + b := []byte(s) + newb := make([]byte, len(b)) + for i := range newb { + if isValidByteValue(b[i]) { + newb[i] = b[i] + } else { + newb[i] = '-' + } + } + + newb = bytes.TrimRight(newb, "-_.") + return string(newb) +} + +var TemplateFuncs = template.FuncMap{ + "clean_resource_name": templateCleanImageName, + "clean_image_name": packertpl.DeprecatedTemplateFunc("clean_image_name", "clean_resource_name", templateCleanImageName), +} diff --git a/builder/azure/dtl/template_funcs_test.go b/builder/azure/dtl/template_funcs_test.go new file mode 100644 index 000000000..13c8e25ce --- /dev/null +++ b/builder/azure/dtl/template_funcs_test.go @@ -0,0 +1,49 @@ +package dtl + +import "testing" + +func TestTemplateCleanImageName(t *testing.T) { + vals := []struct { + origName string + expected string + }{ + // test that valid name is unchanged + { + origName: "abcde-012345xyz", + expected: "abcde-012345xyz", + }, + // test that colons are converted to hyphens + { + origName: "abcde-012345v1.0:0", + expected: "abcde-012345v1.0-0", + }, + // Name starting with number is not valid, but not in scope of this + // function to correct + { + origName: "012345v1.0:0", + expected: "012345v1.0-0", + }, + // Name over 80 chars is not valid, but not corrected by this function. + { + origName: "l012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789", + expected: "l012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789", + }, + // Name cannot end in a -Name over 80 chars is not valid, but not corrected by this function. + { + origName: "abcde-:_", + expected: "abcde", + }, + // Lost of special characters + { + origName: "My()./-_:&^ $%[]#'@name", + expected: "My--.--_-----------name", + }, + } + + for _, v := range vals { + name := templateCleanImageName(v.origName) + if name != v.expected { + t.Fatalf("template names do not match: expected %s got %s\n", v.expected, name) + } + } +} diff --git a/builder/azure/dtl/tempname.go b/builder/azure/dtl/tempname.go new file mode 100644 index 000000000..b4c51d478 --- /dev/null +++ b/builder/azure/dtl/tempname.go @@ -0,0 +1,74 @@ +package dtl + +import ( + "fmt" + "strings" + + "github.com/hashicorp/packer/common/random" +) + +type TempName struct { + AdminPassword string + CertificatePassword string + ComputeName string + DeploymentName string + KeyVaultName string + ResourceGroupName string + OSDiskName string + NicName string + SubnetName string + PublicIPAddressName string + VirtualNetworkName string +} + +func NewTempName(c *Config) *TempName { + tempName := &TempName{} + suffix := random.AlphaNumLower(10) + + if c.VMName != "" { + suffix = c.VMName + } + + tempName.ComputeName = suffix + tempName.DeploymentName = fmt.Sprintf("pkrdp%s", suffix) + tempName.KeyVaultName = fmt.Sprintf("pkrkv%s", suffix) + tempName.OSDiskName = fmt.Sprintf("pkros%s", suffix) + tempName.NicName = tempName.ComputeName + tempName.PublicIPAddressName = tempName.ComputeName + tempName.SubnetName = fmt.Sprintf("pkrsn%s", suffix) + tempName.VirtualNetworkName = fmt.Sprintf("pkrvn%s", suffix) + tempName.ResourceGroupName = fmt.Sprintf("packer-Resource-Group-%s", suffix) + + tempName.AdminPassword = generatePassword() + tempName.CertificatePassword = random.AlphaNum(32) + return tempName +} + +// generate a password that is acceptable to Azure +// Three of the four items must be met. +// 1. Contains an uppercase character +// 2. Contains a lowercase character +// 3. Contains a numeric digit +// 4. Contains a special character +func generatePassword() string { + var s string + for i := 0; i < 100; i++ { + s := random.AlphaNum(32) + if !strings.ContainsAny(s, random.PossibleNumbers) { + continue + } + + if !strings.ContainsAny(s, random.PossibleLowerCase) { + continue + } + + if !strings.ContainsAny(s, random.PossibleUpperCase) { + continue + } + + return s + } + + // if an acceptable password cannot be generated in 100 tries, give up + return s +} diff --git a/command/plugin.go b/command/plugin.go index 9f6ee7b1b..fa57737a7 100644 --- a/command/plugin.go +++ b/command/plugin.go @@ -21,6 +21,7 @@ import ( amazoninstancebuilder "github.com/hashicorp/packer/builder/amazon/instance" azurearmbuilder "github.com/hashicorp/packer/builder/azure/arm" azurechrootbuilder "github.com/hashicorp/packer/builder/azure/chroot" + azuredtlbuilder "github.com/hashicorp/packer/builder/azure/dtl" cloudstackbuilder "github.com/hashicorp/packer/builder/cloudstack" digitaloceanbuilder "github.com/hashicorp/packer/builder/digitalocean" dockerbuilder "github.com/hashicorp/packer/builder/docker" @@ -84,6 +85,7 @@ import ( vspheretemplatepostprocessor "github.com/hashicorp/packer/post-processor/vsphere-template" ansibleprovisioner "github.com/hashicorp/packer/provisioner/ansible" ansiblelocalprovisioner "github.com/hashicorp/packer/provisioner/ansible-local" + azuredtlartifactprovisioner "github.com/hashicorp/packer/provisioner/azure-dtlartifact" breakpointprovisioner "github.com/hashicorp/packer/provisioner/breakpoint" chefclientprovisioner "github.com/hashicorp/packer/provisioner/chef-client" chefsoloprovisioner "github.com/hashicorp/packer/provisioner/chef-solo" @@ -114,6 +116,7 @@ var Builders = map[string]packer.Builder{ "amazon-instance": new(amazoninstancebuilder.Builder), "azure-arm": new(azurearmbuilder.Builder), "azure-chroot": new(azurechrootbuilder.Builder), + "azure-dtl": new(azuredtlbuilder.Builder), "cloudstack": new(cloudstackbuilder.Builder), "digitalocean": new(digitaloceanbuilder.Builder), "docker": new(dockerbuilder.Builder), @@ -160,6 +163,7 @@ var Builders = map[string]packer.Builder{ var Provisioners = map[string]packer.Provisioner{ "ansible": new(ansibleprovisioner.Provisioner), "ansible-local": new(ansiblelocalprovisioner.Provisioner), + "azure-dtlartifact": new(azuredtlartifactprovisioner.Provisioner), "breakpoint": new(breakpointprovisioner.Provisioner), "chef-client": new(chefclientprovisioner.Provisioner), "chef-solo": new(chefsoloprovisioner.Provisioner), diff --git a/go.sum b/go.sum index 477bbe43d..9167fd319 100644 --- a/go.sum +++ b/go.sum @@ -712,4 +712,4 @@ honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= \ No newline at end of file diff --git a/provisioner/azure-dtlartifact/provisioner.go b/provisioner/azure-dtlartifact/provisioner.go new file mode 100644 index 000000000..b38d1ab9f --- /dev/null +++ b/provisioner/azure-dtlartifact/provisioner.go @@ -0,0 +1,182 @@ +//go:generate mapstructure-to-hcl2 -type Config,DtlArtifact,ArtifactParameter + +package devtestlabsartifacts + +import ( + "context" + "fmt" + "time" + + "github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl" + "github.com/hashicorp/hcl/v2/hcldec" + "github.com/hashicorp/packer/builder/azure/common/client" + dtlBuilder "github.com/hashicorp/packer/builder/azure/dtl" + + "github.com/hashicorp/packer/packer" + + "github.com/hashicorp/packer/common" + "github.com/hashicorp/packer/helper/config" + "github.com/hashicorp/packer/template/interpolate" +) + +type DtlArtifact struct { + ArtifactName string `mapstructure:"artifact_name"` + ArtifactId string `mapstructure:"artifact_id"` + Parameters []ArtifactParameter `mapstructure:"parameters"` +} + +type ArtifactParameter struct { + Name string `mapstructure:"name"` + Value string `mapstructure:"value"` + Type string `mapstructure:"type"` +} + +type Config struct { + common.PackerConfig `mapstructure:",squash"` + + // Authentication via OAUTH + ClientConfig client.Config `mapstructure:",squash"` + + DtlArtifacts []DtlArtifact `mapstructure:"dtl_artifacts"` + LabName string `mapstructure:"lab_name"` + + ResourceGroupName string `mapstructure:"lab_resource_group_name"` + + VMName string `mapstructure:"vm_name"` + + // The default PollingDuration for azure is 15mins, this property will override + // that value. See [Azure DefaultPollingDuration](https://godoc.org/github.com/Azure/go-autorest/autorest#pkg-constants) + // If your Packer build is failing on the + // ARM deployment step with the error `Original Error: + // context deadline exceeded`, then you probably need to increase this timeout from + // its default of "15m" (valid time units include `s` for seconds, `m` for + // minutes, and `h` for hours.) + PollingDurationTimeout time.Duration `mapstructure:"polling_duration_timeout" required:"false"` + + AzureTags map[string]*string `mapstructure:"azure_tags"` + + Json map[string]interface{} + + ctx interpolate.Context +} + +type Provisioner struct { + config Config + communicator packer.Communicator +} + +func (p *Provisioner) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() } + +func (p *Provisioner) Prepare(raws ...interface{}) error { + // // Create passthrough for winrm password so we can fill it in once we know + // // it + // p.config.ctx.Data = &EnvVarsTemplate{ + // WinRMPassword: `{{.WinRMPassword}}`, + // } + err := config.Decode(&p.config, &config.DecodeOpts{ + Interpolate: true, + InterpolateContext: &p.config.ctx, + InterpolateFilter: &interpolate.RenderFilter{ + Exclude: []string{ + "execute_command", + }, + }, + }, raws...) + if err != nil { + return err + } + + p.config.ClientConfig.CloudEnvironmentName = "Public" + + return nil +} + +func (p *Provisioner) Communicator() packer.Communicator { + return p.communicator +} + +func (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, comm packer.Communicator, _ map[string]interface{}) error { + + p.communicator = comm + + err := p.config.ClientConfig.SetDefaultValues() + if err != nil { + ui.Say(fmt.Sprintf("Error saving debug key: %s", err)) + return nil + } + + ///////////////////////////////////////////// + // Polling Duration Timeout + if p.config.PollingDurationTimeout == 0 { + // In the sdk, the default is 15 m. + p.config.PollingDurationTimeout = 15 * time.Minute + } + // FillParameters function captures authType and sets defaults. + err = p.config.ClientConfig.FillParameters() + if err != nil { + return err + } + + spnCloud, err := p.config.ClientConfig.GetServicePrincipalToken(ui.Say, p.config.ClientConfig.CloudEnvironment().ResourceManagerEndpoint) + if err != nil { + return err + } + + ui.Message("Creating Azure Resource Manager (ARM) client ...") + azureClient, err := dtlBuilder.NewAzureClient( + p.config.ClientConfig.SubscriptionID, + "", + p.config.ClientConfig.CloudEnvironment(), + p.config.PollingDurationTimeout, + p.config.PollingDurationTimeout, + spnCloud) + + if err != nil { + ui.Say(fmt.Sprintf("Error saving debug key: %s", err)) + return err + } + + ui.Say("Installing Artifact DTL") + dtlArtifacts := []dtl.ArtifactInstallProperties{} + + if p.config.DtlArtifacts != nil { + for i := range p.config.DtlArtifacts { + p.config.DtlArtifacts[i].ArtifactId = fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.DevTestLab/labs/%s/artifactSources/public repo/artifacts/%s", + p.config.ClientConfig.SubscriptionID, + p.config.ResourceGroupName, + p.config.LabName, + p.config.DtlArtifacts[i].ArtifactName) + + dparams := []dtl.ArtifactParameterProperties{} + for j := range p.config.DtlArtifacts[i].Parameters { + dp := &dtl.ArtifactParameterProperties{} + dp.Name = &p.config.DtlArtifacts[i].Parameters[j].Name + dp.Value = &p.config.DtlArtifacts[i].Parameters[j].Value + + dparams = append(dparams, *dp) + } + Aip := dtl.ArtifactInstallProperties{ + ArtifactID: &p.config.DtlArtifacts[i].ArtifactId, + Parameters: &dparams, + ArtifactTitle: &p.config.DtlArtifacts[i].ArtifactName, + } + dtlArtifacts = append(dtlArtifacts, Aip) + } + } + + dtlApplyArifactRequest := dtl.ApplyArtifactsRequest{ + Artifacts: &dtlArtifacts, + } + + ui.Say("Applying artifact ") + f, err := azureClient.DtlVirtualMachineClient.ApplyArtifacts(ctx, p.config.ResourceGroupName, p.config.LabName, p.config.VMName, dtlApplyArifactRequest) + + if err == nil { + err = f.WaitForCompletionRef(ctx, azureClient.DtlVirtualMachineClient.Client) + } + if err != nil { + ui.Say(fmt.Sprintf("Error Applying artifact: %s", err)) + } + ui.Say("Aftifact installed") + return err +} diff --git a/provisioner/azure-dtlartifact/provisioner.hcl2spec.go b/provisioner/azure-dtlartifact/provisioner.hcl2spec.go new file mode 100644 index 000000000..d60a79dcf --- /dev/null +++ b/provisioner/azure-dtlartifact/provisioner.hcl2spec.go @@ -0,0 +1,126 @@ +// Code generated by "mapstructure-to-hcl2 -type Config,DtlArtifact,ArtifactParameter"; DO NOT EDIT. +package devtestlabsartifacts + +import ( + "github.com/hashicorp/hcl/v2/hcldec" + "github.com/zclconf/go-cty/cty" +) + +// FlatArtifactParameter is an auto-generated flat version of ArtifactParameter. +// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. +type FlatArtifactParameter struct { + Name *string `mapstructure:"name" cty:"name"` + Value *string `mapstructure:"value" cty:"value"` + Type *string `mapstructure:"type" cty:"type"` +} + +// FlatMapstructure returns a new FlatArtifactParameter. +// FlatArtifactParameter is an auto-generated flat version of ArtifactParameter. +// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up. +func (*ArtifactParameter) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } { + return new(FlatArtifactParameter) +} + +// HCL2Spec returns the hcl spec of a ArtifactParameter. +// This spec is used by HCL to read the fields of ArtifactParameter. +// The decoded values from this spec will then be applied to a FlatArtifactParameter. +func (*FlatArtifactParameter) HCL2Spec() map[string]hcldec.Spec { + s := map[string]hcldec.Spec{ + "name": &hcldec.AttrSpec{Name: "name", Type: cty.String, Required: false}, + "value": &hcldec.AttrSpec{Name: "value", Type: cty.String, Required: false}, + "type": &hcldec.AttrSpec{Name: "type", Type: cty.String, Required: false}, + } + return s +} + +// FlatConfig is an auto-generated flat version of Config. +// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. +type FlatConfig struct { + PackerBuildName *string `mapstructure:"packer_build_name" cty:"packer_build_name"` + PackerBuilderType *string `mapstructure:"packer_builder_type" cty:"packer_builder_type"` + PackerDebug *bool `mapstructure:"packer_debug" cty:"packer_debug"` + PackerForce *bool `mapstructure:"packer_force" cty:"packer_force"` + PackerOnError *string `mapstructure:"packer_on_error" cty:"packer_on_error"` + PackerUserVars map[string]string `mapstructure:"packer_user_variables" cty:"packer_user_variables"` + PackerSensitiveVars []string `mapstructure:"packer_sensitive_variables" cty:"packer_sensitive_variables"` + CloudEnvironmentName *string `mapstructure:"cloud_environment_name" required:"false" cty:"cloud_environment_name"` + ClientID *string `mapstructure:"client_id" cty:"client_id"` + ClientSecret *string `mapstructure:"client_secret" cty:"client_secret"` + ClientCertPath *string `mapstructure:"client_cert_path" cty:"client_cert_path"` + ClientJWT *string `mapstructure:"client_jwt" cty:"client_jwt"` + ObjectID *string `mapstructure:"object_id" cty:"object_id"` + TenantID *string `mapstructure:"tenant_id" required:"false" cty:"tenant_id"` + SubscriptionID *string `mapstructure:"subscription_id" cty:"subscription_id"` + DtlArtifacts []FlatDtlArtifact `mapstructure:"dtl_artifacts" cty:"dtl_artifacts"` + LabName *string `mapstructure:"lab_name" cty:"lab_name"` + ResourceGroupName *string `mapstructure:"lab_resource_group_name" cty:"lab_resource_group_name"` + VMName *string `mapstructure:"vm_name" cty:"vm_name"` + PollingDurationTimeout *string `mapstructure:"polling_duration_timeout" required:"false" cty:"polling_duration_timeout"` + AzureTags map[string]*string `mapstructure:"azure_tags" cty:"azure_tags"` + Json map[string]interface{} `cty:"json"` +} + +// FlatMapstructure returns a new FlatConfig. +// FlatConfig is an auto-generated flat version of Config. +// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up. +func (*Config) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } { + return new(FlatConfig) +} + +// HCL2Spec returns the hcl spec of a Config. +// This spec is used by HCL to read the fields of Config. +// The decoded values from this spec will then be applied to a FlatConfig. +func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { + s := map[string]hcldec.Spec{ + "packer_build_name": &hcldec.AttrSpec{Name: "packer_build_name", Type: cty.String, Required: false}, + "packer_builder_type": &hcldec.AttrSpec{Name: "packer_builder_type", Type: cty.String, Required: false}, + "packer_debug": &hcldec.AttrSpec{Name: "packer_debug", Type: cty.Bool, Required: false}, + "packer_force": &hcldec.AttrSpec{Name: "packer_force", Type: cty.Bool, Required: false}, + "packer_on_error": &hcldec.AttrSpec{Name: "packer_on_error", Type: cty.String, Required: false}, + "packer_user_variables": &hcldec.BlockAttrsSpec{TypeName: "packer_user_variables", ElementType: cty.String, Required: false}, + "packer_sensitive_variables": &hcldec.AttrSpec{Name: "packer_sensitive_variables", Type: cty.List(cty.String), Required: false}, + "cloud_environment_name": &hcldec.AttrSpec{Name: "cloud_environment_name", Type: cty.String, Required: false}, + "client_id": &hcldec.AttrSpec{Name: "client_id", Type: cty.String, Required: false}, + "client_secret": &hcldec.AttrSpec{Name: "client_secret", Type: cty.String, Required: false}, + "client_cert_path": &hcldec.AttrSpec{Name: "client_cert_path", Type: cty.String, Required: false}, + "client_jwt": &hcldec.AttrSpec{Name: "client_jwt", Type: cty.String, Required: false}, + "object_id": &hcldec.AttrSpec{Name: "object_id", Type: cty.String, Required: false}, + "tenant_id": &hcldec.AttrSpec{Name: "tenant_id", Type: cty.String, Required: false}, + "subscription_id": &hcldec.AttrSpec{Name: "subscription_id", Type: cty.String, Required: false}, + "dtl_artifacts": &hcldec.BlockListSpec{TypeName: "dtl_artifacts", Nested: hcldec.ObjectSpec((*FlatDtlArtifact)(nil).HCL2Spec())}, + "lab_name": &hcldec.AttrSpec{Name: "lab_name", Type: cty.String, Required: false}, + "lab_resource_group_name": &hcldec.AttrSpec{Name: "lab_resource_group_name", Type: cty.String, Required: false}, + "vm_name": &hcldec.AttrSpec{Name: "vm_name", Type: cty.String, Required: false}, + "polling_duration_timeout": &hcldec.AttrSpec{Name: "polling_duration_timeout", Type: cty.String, Required: false}, + "azure_tags": &hcldec.BlockAttrsSpec{TypeName: "azure_tags", ElementType: cty.String, Required: false}, + "json": &hcldec.BlockAttrsSpec{TypeName: "json", ElementType: cty.String, Required: false}, + } + return s +} + +// FlatDtlArtifact is an auto-generated flat version of DtlArtifact. +// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. +type FlatDtlArtifact struct { + ArtifactName *string `mapstructure:"artifact_name" cty:"artifact_name"` + ArtifactId *string `mapstructure:"artifact_id" cty:"artifact_id"` + Parameters []FlatArtifactParameter `mapstructure:"parameters" cty:"parameters"` +} + +// FlatMapstructure returns a new FlatDtlArtifact. +// FlatDtlArtifact is an auto-generated flat version of DtlArtifact. +// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up. +func (*DtlArtifact) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } { + return new(FlatDtlArtifact) +} + +// HCL2Spec returns the hcl spec of a DtlArtifact. +// This spec is used by HCL to read the fields of DtlArtifact. +// The decoded values from this spec will then be applied to a FlatDtlArtifact. +func (*FlatDtlArtifact) HCL2Spec() map[string]hcldec.Spec { + s := map[string]hcldec.Spec{ + "artifact_name": &hcldec.AttrSpec{Name: "artifact_name", Type: cty.String, Required: false}, + "artifact_id": &hcldec.AttrSpec{Name: "artifact_id", Type: cty.String, Required: false}, + "parameters": &hcldec.BlockListSpec{TypeName: "parameters", Nested: hcldec.ObjectSpec((*FlatArtifactParameter)(nil).HCL2Spec())}, + } + return s +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/armtemplates.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/armtemplates.go new file mode 100644 index 000000000..2a9b75a54 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/armtemplates.go @@ -0,0 +1,259 @@ +package dtl + +// 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" +) + +// ArmTemplatesClient is the the DevTest Labs Client. +type ArmTemplatesClient struct { + BaseClient +} + +// NewArmTemplatesClient creates an instance of the ArmTemplatesClient client. +func NewArmTemplatesClient(subscriptionID string) ArmTemplatesClient { + return NewArmTemplatesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewArmTemplatesClientWithBaseURI creates an instance of the ArmTemplatesClient client. +func NewArmTemplatesClientWithBaseURI(baseURI string, subscriptionID string) ArmTemplatesClient { + return ArmTemplatesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Get get azure resource manager template. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// artifactSourceName - the name of the artifact source. +// name - the name of the azure Resource Manager template. +// expand - specify the $expand query. Example: 'properties($select=displayName)' +func (client ArmTemplatesClient) Get(ctx context.Context, resourceGroupName string, labName string, artifactSourceName string, name string, expand string) (result ArmTemplate, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArmTemplatesClient.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, labName, artifactSourceName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArmTemplatesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ArmTemplatesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArmTemplatesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ArmTemplatesClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, artifactSourceName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "artifactSourceName": autorest.Encode("path", artifactSourceName), + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/artifactsources/{artifactSourceName}/armtemplates/{name}", 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 ArmTemplatesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ArmTemplatesClient) GetResponder(resp *http.Response) (result ArmTemplate, 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 list azure resource manager templates in a given artifact source. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// artifactSourceName - the name of the artifact source. +// expand - specify the $expand query. Example: 'properties($select=displayName)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client ArmTemplatesClient) List(ctx context.Context, resourceGroupName string, labName string, artifactSourceName string, expand string, filter string, top *int32, orderby string) (result ArmTemplateListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArmTemplatesClient.List") + defer func() { + sc := -1 + if result.atl.Response.Response != nil { + sc = result.atl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, artifactSourceName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArmTemplatesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.atl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ArmTemplatesClient", "List", resp, "Failure sending request") + return + } + + result.atl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArmTemplatesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ArmTemplatesClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, artifactSourceName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "artifactSourceName": autorest.Encode("path", artifactSourceName), + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources/{artifactSourceName}/armtemplates", 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 ArmTemplatesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ArmTemplatesClient) ListResponder(resp *http.Response) (result ArmTemplateList, 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 ArmTemplatesClient) listNextResults(ctx context.Context, lastResults ArmTemplateList) (result ArmTemplateList, err error) { + req, err := lastResults.armTemplateListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.ArmTemplatesClient", "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, "dtl.ArmTemplatesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArmTemplatesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ArmTemplatesClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, artifactSourceName string, expand string, filter string, top *int32, orderby string) (result ArmTemplateListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArmTemplatesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, artifactSourceName, expand, filter, top, orderby) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/artifacts.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/artifacts.go new file mode 100644 index 000000000..01998ee2b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/artifacts.go @@ -0,0 +1,344 @@ +package dtl + +// 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" +) + +// ArtifactsClient is the the DevTest Labs Client. +type ArtifactsClient struct { + BaseClient +} + +// NewArtifactsClient creates an instance of the ArtifactsClient client. +func NewArtifactsClient(subscriptionID string) ArtifactsClient { + return NewArtifactsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewArtifactsClientWithBaseURI creates an instance of the ArtifactsClient client. +func NewArtifactsClientWithBaseURI(baseURI string, subscriptionID string) ArtifactsClient { + return ArtifactsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// GenerateArmTemplate generates an ARM template for the given artifact, uploads the required files to a storage +// account, and validates the generated artifact. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// artifactSourceName - the name of the artifact source. +// name - the name of the artifact. +// generateArmTemplateRequest - parameters for generating an ARM template for deploying artifacts. +func (client ArtifactsClient) GenerateArmTemplate(ctx context.Context, resourceGroupName string, labName string, artifactSourceName string, name string, generateArmTemplateRequest GenerateArmTemplateRequest) (result ArmTemplateInfo, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactsClient.GenerateArmTemplate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GenerateArmTemplatePreparer(ctx, resourceGroupName, labName, artifactSourceName, name, generateArmTemplateRequest) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactsClient", "GenerateArmTemplate", nil, "Failure preparing request") + return + } + + resp, err := client.GenerateArmTemplateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ArtifactsClient", "GenerateArmTemplate", resp, "Failure sending request") + return + } + + result, err = client.GenerateArmTemplateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactsClient", "GenerateArmTemplate", resp, "Failure responding to request") + } + + return +} + +// GenerateArmTemplatePreparer prepares the GenerateArmTemplate request. +func (client ArtifactsClient) GenerateArmTemplatePreparer(ctx context.Context, resourceGroupName string, labName string, artifactSourceName string, name string, generateArmTemplateRequest GenerateArmTemplateRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "artifactSourceName": autorest.Encode("path", artifactSourceName), + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources/{artifactSourceName}/artifacts/{name}/generateArmTemplate", pathParameters), + autorest.WithJSON(generateArmTemplateRequest), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GenerateArmTemplateSender sends the GenerateArmTemplate request. The method will close the +// http.Response Body if it receives an error. +func (client ArtifactsClient) GenerateArmTemplateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GenerateArmTemplateResponder handles the response to the GenerateArmTemplate request. The method always +// closes the http.Response Body. +func (client ArtifactsClient) GenerateArmTemplateResponder(resp *http.Response) (result ArmTemplateInfo, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get get artifact. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// artifactSourceName - the name of the artifact source. +// name - the name of the artifact. +// expand - specify the $expand query. Example: 'properties($select=title)' +func (client ArtifactsClient) Get(ctx context.Context, resourceGroupName string, labName string, artifactSourceName string, name string, expand string) (result Artifact, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactsClient.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, labName, artifactSourceName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ArtifactsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ArtifactsClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, artifactSourceName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "artifactSourceName": autorest.Encode("path", artifactSourceName), + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/artifactsources/{artifactSourceName}/artifacts/{name}", 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 ArtifactsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ArtifactsClient) GetResponder(resp *http.Response) (result Artifact, 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 list artifacts in a given artifact source. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// artifactSourceName - the name of the artifact source. +// expand - specify the $expand query. Example: 'properties($select=title)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client ArtifactsClient) List(ctx context.Context, resourceGroupName string, labName string, artifactSourceName string, expand string, filter string, top *int32, orderby string) (result ArtifactListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactsClient.List") + defer func() { + sc := -1 + if result.al.Response.Response != nil { + sc = result.al.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, artifactSourceName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.al.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ArtifactsClient", "List", resp, "Failure sending request") + return + } + + result.al, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ArtifactsClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, artifactSourceName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "artifactSourceName": autorest.Encode("path", artifactSourceName), + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources/{artifactSourceName}/artifacts", 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 ArtifactsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ArtifactsClient) ListResponder(resp *http.Response) (result ArtifactList, 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 ArtifactsClient) listNextResults(ctx context.Context, lastResults ArtifactList) (result ArtifactList, err error) { + req, err := lastResults.artifactListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.ArtifactsClient", "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, "dtl.ArtifactsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ArtifactsClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, artifactSourceName string, expand string, filter string, top *int32, orderby string) (result ArtifactListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, artifactSourceName, expand, filter, top, orderby) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/artifactsources.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/artifactsources.go new file mode 100644 index 000000000..c647a1de6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/artifactsources.go @@ -0,0 +1,504 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ArtifactSourcesClient is the the DevTest Labs Client. +type ArtifactSourcesClient struct { + BaseClient +} + +// NewArtifactSourcesClient creates an instance of the ArtifactSourcesClient client. +func NewArtifactSourcesClient(subscriptionID string) ArtifactSourcesClient { + return NewArtifactSourcesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewArtifactSourcesClientWithBaseURI creates an instance of the ArtifactSourcesClient client. +func NewArtifactSourcesClientWithBaseURI(baseURI string, subscriptionID string) ArtifactSourcesClient { + return ArtifactSourcesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing artifact source. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the artifact source. +// artifactSource - properties of an artifact source. +func (client ArtifactSourcesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, name string, artifactSource ArtifactSource) (result ArtifactSource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactSourcesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: artifactSource, + Constraints: []validation.Constraint{{Target: "artifactSource.ArtifactSourceProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("dtl.ArtifactSourcesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, name, artifactSource) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ArtifactSourcesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, artifactSource ArtifactSource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/artifactsources/{name}", pathParameters), + autorest.WithJSON(artifactSource), + 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 ArtifactSourcesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ArtifactSourcesClient) CreateOrUpdateResponder(resp *http.Response) (result ArtifactSource, 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 delete artifact source. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the artifact source. +func (client ArtifactSourcesClient) Delete(ctx context.Context, resourceGroupName string, labName string, name string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactSourcesClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ArtifactSourcesClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources/{name}", 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 ArtifactSourcesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ArtifactSourcesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get artifact source. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the artifact source. +// expand - specify the $expand query. Example: 'properties($select=displayName)' +func (client ArtifactSourcesClient) Get(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (result ArtifactSource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactSourcesClient.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, labName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ArtifactSourcesClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/artifactsources/{name}", 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 ArtifactSourcesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ArtifactSourcesClient) GetResponder(resp *http.Response) (result ArtifactSource, 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 list artifact sources in a given lab. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// expand - specify the $expand query. Example: 'properties($select=displayName)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client ArtifactSourcesClient) List(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result ArtifactSourceListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactSourcesClient.List") + defer func() { + sc := -1 + if result.asl.Response.Response != nil { + sc = result.asl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.asl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "List", resp, "Failure sending request") + return + } + + result.asl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ArtifactSourcesClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources", 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 ArtifactSourcesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ArtifactSourcesClient) ListResponder(resp *http.Response) (result ArtifactSourceList, 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 ArtifactSourcesClient) listNextResults(ctx context.Context, lastResults ArtifactSourceList) (result ArtifactSourceList, err error) { + req, err := lastResults.artifactSourceListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "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, "dtl.ArtifactSourcesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ArtifactSourcesClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result ArtifactSourceListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactSourcesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, expand, filter, top, orderby) + return +} + +// Update modify properties of artifact sources. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the artifact source. +// artifactSource - properties of an artifact source. +func (client ArtifactSourcesClient) Update(ctx context.Context, resourceGroupName string, labName string, name string, artifactSource ArtifactSourceFragment) (result ArtifactSource, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactSourcesClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, name, artifactSource) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ArtifactSourcesClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client ArtifactSourcesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, artifactSource ArtifactSourceFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/artifactsources/{name}", pathParameters), + autorest.WithJSON(artifactSource), + 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 ArtifactSourcesClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client ArtifactSourcesClient) UpdateResponder(resp *http.Response) (result ArtifactSource, 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/devtestlabs/mgmt/2018-09-15/dtl/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/client.go new file mode 100644 index 000000000..f9c187ce9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/client.go @@ -0,0 +1,51 @@ +// Package dtl implements the Azure ARM Dtl service API version 2018-09-15. +// +// The DevTest Labs Client. +package dtl + +// 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 Dtl + DefaultBaseURI = "https://management.azure.com" +) + +// BaseClient is the base client for Dtl. +type BaseClient struct { + autorest.Client + BaseURI string + SubscriptionID string +} + +// New creates an instance of the BaseClient client. +func New(subscriptionID string) BaseClient { + return NewWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWithBaseURI creates an instance of the BaseClient client. +func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { + return BaseClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + SubscriptionID: subscriptionID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/costs.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/costs.go new file mode 100644 index 000000000..748c9b20c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/costs.go @@ -0,0 +1,213 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// CostsClient is the the DevTest Labs Client. +type CostsClient struct { + BaseClient +} + +// NewCostsClient creates an instance of the CostsClient client. +func NewCostsClient(subscriptionID string) CostsClient { + return NewCostsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewCostsClientWithBaseURI creates an instance of the CostsClient client. +func NewCostsClientWithBaseURI(baseURI string, subscriptionID string) CostsClient { + return CostsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing cost. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the cost. +// labCost - a cost item. +func (client CostsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, name string, labCost LabCost) (result LabCost, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CostsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: labCost, + Constraints: []validation.Constraint{{Target: "labCost.LabCostProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("dtl.CostsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, name, labCost) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CostsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.CostsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CostsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client CostsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, labCost LabCost) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/costs/{name}", pathParameters), + autorest.WithJSON(labCost), + 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 CostsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client CostsClient) CreateOrUpdateResponder(resp *http.Response) (result LabCost, 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 +} + +// Get get cost. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the cost. +// expand - specify the $expand query. Example: 'properties($expand=labCostDetails)' +func (client CostsClient) Get(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (result LabCost, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CostsClient.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, labName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CostsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.CostsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CostsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client CostsClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/costs/{name}", 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 CostsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client CostsClient) GetResponder(resp *http.Response) (result LabCost, 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/devtestlabs/mgmt/2018-09-15/dtl/customimages.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/customimages.go new file mode 100644 index 000000000..87d8d5c64 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/customimages.go @@ -0,0 +1,504 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// CustomImagesClient is the the DevTest Labs Client. +type CustomImagesClient struct { + BaseClient +} + +// NewCustomImagesClient creates an instance of the CustomImagesClient client. +func NewCustomImagesClient(subscriptionID string) CustomImagesClient { + return NewCustomImagesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewCustomImagesClientWithBaseURI creates an instance of the CustomImagesClient client. +func NewCustomImagesClientWithBaseURI(baseURI string, subscriptionID string) CustomImagesClient { + return CustomImagesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing custom image. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the custom image. +// customImage - a custom image. +func (client CustomImagesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, name string, customImage CustomImage) (result CustomImagesCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomImagesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: customImage, + Constraints: []validation.Constraint{{Target: "customImage.CustomImageProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("dtl.CustomImagesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, name, customImage) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client CustomImagesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, customImage CustomImage) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/customimages/{name}", pathParameters), + autorest.WithJSON(customImage), + 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 CustomImagesClient) CreateOrUpdateSender(req *http.Request) (future CustomImagesCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 CustomImagesClient) CreateOrUpdateResponder(resp *http.Response) (result CustomImage, 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 delete custom image. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the custom image. +func (client CustomImagesClient) Delete(ctx context.Context, resourceGroupName string, labName string, name string) (result CustomImagesDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomImagesClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client CustomImagesClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}", 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 CustomImagesClient) DeleteSender(req *http.Request) (future CustomImagesDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 CustomImagesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get custom image. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the custom image. +// expand - specify the $expand query. Example: 'properties($select=vm)' +func (client CustomImagesClient) Get(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (result CustomImage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomImagesClient.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, labName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client CustomImagesClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/customimages/{name}", 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 CustomImagesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client CustomImagesClient) GetResponder(resp *http.Response) (result CustomImage, 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 list custom images in a given lab. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// expand - specify the $expand query. Example: 'properties($select=vm)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client CustomImagesClient) List(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result CustomImageListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomImagesClient.List") + defer func() { + sc := -1 + if result.cil.Response.Response != nil { + sc = result.cil.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.cil.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "List", resp, "Failure sending request") + return + } + + result.cil, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client CustomImagesClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages", 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 CustomImagesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client CustomImagesClient) ListResponder(resp *http.Response) (result CustomImageList, 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 CustomImagesClient) listNextResults(ctx context.Context, lastResults CustomImageList) (result CustomImageList, err error) { + req, err := lastResults.customImageListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "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, "dtl.CustomImagesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client CustomImagesClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result CustomImageListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomImagesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, expand, filter, top, orderby) + return +} + +// Update modify properties of custom images. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the custom image. +// customImage - a custom image. +func (client CustomImagesClient) Update(ctx context.Context, resourceGroupName string, labName string, name string, customImage CustomImageFragment) (result CustomImage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomImagesClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, name, customImage) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client CustomImagesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, customImage CustomImageFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/customimages/{name}", pathParameters), + autorest.WithJSON(customImage), + 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 CustomImagesClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client CustomImagesClient) UpdateResponder(resp *http.Response) (result CustomImage, 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/devtestlabs/mgmt/2018-09-15/dtl/disks.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/disks.go new file mode 100644 index 000000000..43f15f478 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/disks.go @@ -0,0 +1,681 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// DisksClient is the the DevTest Labs Client. +type DisksClient struct { + BaseClient +} + +// NewDisksClient creates an instance of the DisksClient client. +func NewDisksClient(subscriptionID string) DisksClient { + return NewDisksClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewDisksClientWithBaseURI creates an instance of the DisksClient client. +func NewDisksClientWithBaseURI(baseURI string, subscriptionID string) DisksClient { + return DisksClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Attach attach and create the lease of the disk to the virtual machine. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the disk. +// attachDiskProperties - properties of the disk to attach. +func (client DisksClient) Attach(ctx context.Context, resourceGroupName string, labName string, userName string, name string, attachDiskProperties AttachDiskProperties) (result DisksAttachFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.Attach") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.AttachPreparer(ctx, resourceGroupName, labName, userName, name, attachDiskProperties) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "Attach", nil, "Failure preparing request") + return + } + + result, err = client.AttachSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "Attach", result.Response(), "Failure sending request") + return + } + + return +} + +// AttachPreparer prepares the Attach request. +func (client DisksClient) AttachPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, attachDiskProperties AttachDiskProperties) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/disks/{name}/attach", pathParameters), + autorest.WithJSON(attachDiskProperties), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// AttachSender sends the Attach request. The method will close the +// http.Response Body if it receives an error. +func (client DisksClient) AttachSender(req *http.Request) (future DisksAttachFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// AttachResponder handles the response to the Attach request. The method always +// closes the http.Response Body. +func (client DisksClient) AttachResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// CreateOrUpdate create or replace an existing disk. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the disk. +// disk - a Disk. +func (client DisksClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, userName string, name string, disk Disk) (result DisksCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: disk, + Constraints: []validation.Constraint{{Target: "disk.DiskProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("dtl.DisksClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, userName, name, disk) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client DisksClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, disk Disk) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/disks/{name}", pathParameters), + autorest.WithJSON(disk), + 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 DisksClient) CreateOrUpdateSender(req *http.Request) (future DisksCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 DisksClient) CreateOrUpdateResponder(resp *http.Response) (result Disk, 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 delete disk. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the disk. +func (client DisksClient) Delete(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (result DisksDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, userName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client DisksClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/disks/{name}", 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 DisksClient) DeleteSender(req *http.Request) (future DisksDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 DisksClient) 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 +} + +// Detach detach and break the lease of the disk attached to the virtual machine. This operation can take a while to +// complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the disk. +// detachDiskProperties - properties of the disk to detach. +func (client DisksClient) Detach(ctx context.Context, resourceGroupName string, labName string, userName string, name string, detachDiskProperties DetachDiskProperties) (result DisksDetachFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.Detach") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DetachPreparer(ctx, resourceGroupName, labName, userName, name, detachDiskProperties) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "Detach", nil, "Failure preparing request") + return + } + + result, err = client.DetachSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "Detach", result.Response(), "Failure sending request") + return + } + + return +} + +// DetachPreparer prepares the Detach request. +func (client DisksClient) DetachPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, detachDiskProperties DetachDiskProperties) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/disks/{name}/detach", pathParameters), + autorest.WithJSON(detachDiskProperties), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DetachSender sends the Detach request. The method will close the +// http.Response Body if it receives an error. +func (client DisksClient) DetachSender(req *http.Request) (future DisksDetachFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DetachResponder handles the response to the Detach request. The method always +// closes the http.Response Body. +func (client DisksClient) DetachResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get disk. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the disk. +// expand - specify the $expand query. Example: 'properties($select=diskType)' +func (client DisksClient) Get(ctx context.Context, resourceGroupName string, labName string, userName string, name string, expand string) (result Disk, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.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, labName, userName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client DisksClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/disks/{name}", 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 DisksClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client DisksClient) GetResponder(resp *http.Response) (result Disk, 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 list disks in a given user profile. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// expand - specify the $expand query. Example: 'properties($select=diskType)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client DisksClient) List(ctx context.Context, resourceGroupName string, labName string, userName string, expand string, filter string, top *int32, orderby string) (result DiskListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.List") + defer func() { + sc := -1 + if result.dl.Response.Response != nil { + sc = result.dl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, userName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.dl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "List", resp, "Failure sending request") + return + } + + result.dl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client DisksClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/disks", 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 DisksClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client DisksClient) ListResponder(resp *http.Response) (result DiskList, 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 DisksClient) listNextResults(ctx context.Context, lastResults DiskList) (result DiskList, err error) { + req, err := lastResults.diskListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.DisksClient", "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, "dtl.DisksClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client DisksClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, userName string, expand string, filter string, top *int32, orderby string) (result DiskListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, userName, expand, filter, top, orderby) + return +} + +// Update modify properties of disks. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the disk. +// disk - a Disk. +func (client DisksClient) Update(ctx context.Context, resourceGroupName string, labName string, userName string, name string, disk DiskFragment) (result Disk, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DisksClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, userName, name, disk) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client DisksClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, disk DiskFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/disks/{name}", pathParameters), + autorest.WithJSON(disk), + 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 DisksClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client DisksClient) UpdateResponder(resp *http.Response) (result Disk, 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/devtestlabs/mgmt/2018-09-15/dtl/environments.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/environments.go new file mode 100644 index 000000000..1d7ec6836 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/environments.go @@ -0,0 +1,514 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// EnvironmentsClient is the the DevTest Labs Client. +type EnvironmentsClient struct { + BaseClient +} + +// NewEnvironmentsClient creates an instance of the EnvironmentsClient client. +func NewEnvironmentsClient(subscriptionID string) EnvironmentsClient { + return NewEnvironmentsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewEnvironmentsClientWithBaseURI creates an instance of the EnvironmentsClient client. +func NewEnvironmentsClientWithBaseURI(baseURI string, subscriptionID string) EnvironmentsClient { + return EnvironmentsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing environment. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the environment. +// dtlEnvironment - an environment, which is essentially an ARM template deployment. +func (client EnvironmentsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, userName string, name string, dtlEnvironment Environment) (result EnvironmentsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EnvironmentsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: dtlEnvironment, + Constraints: []validation.Constraint{{Target: "dtlEnvironment.EnvironmentProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("dtl.EnvironmentsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, userName, name, dtlEnvironment) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client EnvironmentsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, dtlEnvironment Environment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/environments/{name}", pathParameters), + autorest.WithJSON(dtlEnvironment), + 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 EnvironmentsClient) CreateOrUpdateSender(req *http.Request) (future EnvironmentsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 EnvironmentsClient) CreateOrUpdateResponder(resp *http.Response) (result Environment, 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 delete environment. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the environment. +func (client EnvironmentsClient) Delete(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (result EnvironmentsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EnvironmentsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, userName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client EnvironmentsClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/environments/{name}", 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 EnvironmentsClient) DeleteSender(req *http.Request) (future EnvironmentsDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 EnvironmentsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get environment. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the environment. +// expand - specify the $expand query. Example: 'properties($select=deploymentProperties)' +func (client EnvironmentsClient) Get(ctx context.Context, resourceGroupName string, labName string, userName string, name string, expand string) (result Environment, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EnvironmentsClient.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, labName, userName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client EnvironmentsClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/environments/{name}", 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 EnvironmentsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client EnvironmentsClient) GetResponder(resp *http.Response) (result Environment, 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 list environments in a given user profile. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// expand - specify the $expand query. Example: 'properties($select=deploymentProperties)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client EnvironmentsClient) List(ctx context.Context, resourceGroupName string, labName string, userName string, expand string, filter string, top *int32, orderby string) (result EnvironmentListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EnvironmentsClient.List") + defer func() { + sc := -1 + if result.el.Response.Response != nil { + sc = result.el.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, userName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.el.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "List", resp, "Failure sending request") + return + } + + result.el, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client EnvironmentsClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/environments", 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 EnvironmentsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client EnvironmentsClient) ListResponder(resp *http.Response) (result EnvironmentList, 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 EnvironmentsClient) listNextResults(ctx context.Context, lastResults EnvironmentList) (result EnvironmentList, err error) { + req, err := lastResults.environmentListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "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, "dtl.EnvironmentsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client EnvironmentsClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, userName string, expand string, filter string, top *int32, orderby string) (result EnvironmentListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EnvironmentsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, userName, expand, filter, top, orderby) + return +} + +// Update modify properties of environments. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the environment. +// dtlEnvironment - an environment, which is essentially an ARM template deployment. +func (client EnvironmentsClient) Update(ctx context.Context, resourceGroupName string, labName string, userName string, name string, dtlEnvironment EnvironmentFragment) (result Environment, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EnvironmentsClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, userName, name, dtlEnvironment) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client EnvironmentsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, dtlEnvironment EnvironmentFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/environments/{name}", pathParameters), + autorest.WithJSON(dtlEnvironment), + 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 EnvironmentsClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client EnvironmentsClient) UpdateResponder(resp *http.Response) (result Environment, 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/devtestlabs/mgmt/2018-09-15/dtl/formulas.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/formulas.go new file mode 100644 index 000000000..c244f2888 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/formulas.go @@ -0,0 +1,504 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// FormulasClient is the the DevTest Labs Client. +type FormulasClient struct { + BaseClient +} + +// NewFormulasClient creates an instance of the FormulasClient client. +func NewFormulasClient(subscriptionID string) FormulasClient { + return NewFormulasClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewFormulasClientWithBaseURI creates an instance of the FormulasClient client. +func NewFormulasClientWithBaseURI(baseURI string, subscriptionID string) FormulasClient { + return FormulasClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing Formula. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the formula. +// formula - a formula for creating a VM, specifying an image base and other parameters +func (client FormulasClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, name string, formula Formula) (result FormulasCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FormulasClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: formula, + Constraints: []validation.Constraint{{Target: "formula.FormulaProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("dtl.FormulasClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, name, formula) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client FormulasClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, formula Formula) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/formulas/{name}", pathParameters), + autorest.WithJSON(formula), + 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 FormulasClient) CreateOrUpdateSender(req *http.Request) (future FormulasCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 FormulasClient) CreateOrUpdateResponder(resp *http.Response) (result Formula, 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 delete formula. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the formula. +func (client FormulasClient) Delete(ctx context.Context, resourceGroupName string, labName string, name string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FormulasClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client FormulasClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/formulas/{name}", 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 FormulasClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client FormulasClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get formula. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the formula. +// expand - specify the $expand query. Example: 'properties($select=description)' +func (client FormulasClient) Get(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (result Formula, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FormulasClient.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, labName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client FormulasClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/formulas/{name}", 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 FormulasClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client FormulasClient) GetResponder(resp *http.Response) (result Formula, 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 list formulas in a given lab. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// expand - specify the $expand query. Example: 'properties($select=description)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client FormulasClient) List(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result FormulaListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FormulasClient.List") + defer func() { + sc := -1 + if result.fl.Response.Response != nil { + sc = result.fl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.fl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "List", resp, "Failure sending request") + return + } + + result.fl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client FormulasClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/formulas", 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 FormulasClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client FormulasClient) ListResponder(resp *http.Response) (result FormulaList, 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 FormulasClient) listNextResults(ctx context.Context, lastResults FormulaList) (result FormulaList, err error) { + req, err := lastResults.formulaListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.FormulasClient", "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, "dtl.FormulasClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client FormulasClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result FormulaListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FormulasClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, expand, filter, top, orderby) + return +} + +// Update modify properties of formulas. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the formula. +// formula - a formula for creating a VM, specifying an image base and other parameters +func (client FormulasClient) Update(ctx context.Context, resourceGroupName string, labName string, name string, formula FormulaFragment) (result Formula, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FormulasClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, name, formula) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.FormulasClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client FormulasClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, formula FormulaFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/formulas/{name}", pathParameters), + autorest.WithJSON(formula), + 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 FormulasClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client FormulasClient) UpdateResponder(resp *http.Response) (result Formula, 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/devtestlabs/mgmt/2018-09-15/dtl/galleryimages.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/galleryimages.go new file mode 100644 index 000000000..647672944 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/galleryimages.go @@ -0,0 +1,172 @@ +package dtl + +// 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" +) + +// GalleryImagesClient is the the DevTest Labs Client. +type GalleryImagesClient struct { + BaseClient +} + +// NewGalleryImagesClient creates an instance of the GalleryImagesClient client. +func NewGalleryImagesClient(subscriptionID string) GalleryImagesClient { + return NewGalleryImagesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewGalleryImagesClientWithBaseURI creates an instance of the GalleryImagesClient client. +func NewGalleryImagesClientWithBaseURI(baseURI string, subscriptionID string) GalleryImagesClient { + return GalleryImagesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List list gallery images in a given lab. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// expand - specify the $expand query. Example: 'properties($select=author)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client GalleryImagesClient) List(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result GalleryImageListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImagesClient.List") + defer func() { + sc := -1 + if result.gil.Response.Response != nil { + sc = result.gil.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GalleryImagesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.gil.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.GalleryImagesClient", "List", resp, "Failure sending request") + return + } + + result.gil, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GalleryImagesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client GalleryImagesClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/galleryimages", 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 GalleryImagesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client GalleryImagesClient) ListResponder(resp *http.Response) (result GalleryImageList, 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 GalleryImagesClient) listNextResults(ctx context.Context, lastResults GalleryImageList) (result GalleryImageList, err error) { + req, err := lastResults.galleryImageListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.GalleryImagesClient", "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, "dtl.GalleryImagesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GalleryImagesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client GalleryImagesClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result GalleryImageListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImagesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, expand, filter, top, orderby) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/globalschedules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/globalschedules.go new file mode 100644 index 000000000..586415082 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/globalschedules.go @@ -0,0 +1,776 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// GlobalSchedulesClient is the the DevTest Labs Client. +type GlobalSchedulesClient struct { + BaseClient +} + +// NewGlobalSchedulesClient creates an instance of the GlobalSchedulesClient client. +func NewGlobalSchedulesClient(subscriptionID string) GlobalSchedulesClient { + return NewGlobalSchedulesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewGlobalSchedulesClientWithBaseURI creates an instance of the GlobalSchedulesClient client. +func NewGlobalSchedulesClientWithBaseURI(baseURI string, subscriptionID string) GlobalSchedulesClient { + return GlobalSchedulesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing schedule. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the schedule. +// schedule - a schedule. +func (client GlobalSchedulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, name string, schedule Schedule) (result Schedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GlobalSchedulesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: schedule, + Constraints: []validation.Constraint{{Target: "schedule.ScheduleProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("dtl.GlobalSchedulesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, name, schedule) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client GlobalSchedulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, name string, schedule Schedule) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/schedules/{name}", pathParameters), + autorest.WithJSON(schedule), + 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 GlobalSchedulesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client GlobalSchedulesClient) CreateOrUpdateResponder(resp *http.Response) (result Schedule, 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 delete schedule. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the schedule. +func (client GlobalSchedulesClient) Delete(ctx context.Context, resourceGroupName string, name string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GlobalSchedulesClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client GlobalSchedulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/schedules/{name}", 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 GlobalSchedulesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client GlobalSchedulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Execute execute a schedule. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the schedule. +func (client GlobalSchedulesClient) Execute(ctx context.Context, resourceGroupName string, name string) (result GlobalSchedulesExecuteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GlobalSchedulesClient.Execute") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ExecutePreparer(ctx, resourceGroupName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "Execute", nil, "Failure preparing request") + return + } + + result, err = client.ExecuteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "Execute", result.Response(), "Failure sending request") + return + } + + return +} + +// ExecutePreparer prepares the Execute request. +func (client GlobalSchedulesClient) ExecutePreparer(ctx context.Context, resourceGroupName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/schedules/{name}/execute", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ExecuteSender sends the Execute request. The method will close the +// http.Response Body if it receives an error. +func (client GlobalSchedulesClient) ExecuteSender(req *http.Request) (future GlobalSchedulesExecuteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// ExecuteResponder handles the response to the Execute request. The method always +// closes the http.Response Body. +func (client GlobalSchedulesClient) ExecuteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get schedule. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the schedule. +// expand - specify the $expand query. Example: 'properties($select=status)' +func (client GlobalSchedulesClient) Get(ctx context.Context, resourceGroupName string, name string, expand string) (result Schedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GlobalSchedulesClient.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, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client GlobalSchedulesClient) GetPreparer(ctx context.Context, resourceGroupName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/schedules/{name}", 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 GlobalSchedulesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client GlobalSchedulesClient) GetResponder(resp *http.Response) (result Schedule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroup list schedules in a resource group. +// Parameters: +// resourceGroupName - the name of the resource group. +// expand - specify the $expand query. Example: 'properties($select=status)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client GlobalSchedulesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, expand string, filter string, top *int32, orderby string) (result ScheduleListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GlobalSchedulesClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.sl.Response.Response != nil { + sc = result.sl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.sl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result.sl, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client GlobalSchedulesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/schedules", 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 GlobalSchedulesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client GlobalSchedulesClient) ListByResourceGroupResponder(resp *http.Response) (result ScheduleList, 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 GlobalSchedulesClient) listByResourceGroupNextResults(ctx context.Context, lastResults ScheduleList) (result ScheduleList, err error) { + req, err := lastResults.scheduleListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "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, "dtl.GlobalSchedulesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client GlobalSchedulesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, expand string, filter string, top *int32, orderby string) (result ScheduleListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GlobalSchedulesClient.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, expand, filter, top, orderby) + return +} + +// ListBySubscription list schedules in a subscription. +// Parameters: +// expand - specify the $expand query. Example: 'properties($select=status)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client GlobalSchedulesClient) ListBySubscription(ctx context.Context, expand string, filter string, top *int32, orderby string) (result ScheduleListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GlobalSchedulesClient.ListBySubscription") + defer func() { + sc := -1 + if result.sl.Response.Response != nil { + sc = result.sl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listBySubscriptionNextResults + req, err := client.ListBySubscriptionPreparer(ctx, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.sl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "ListBySubscription", resp, "Failure sending request") + return + } + + result.sl, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "ListBySubscription", resp, "Failure responding to request") + } + + return +} + +// ListBySubscriptionPreparer prepares the ListBySubscription request. +func (client GlobalSchedulesClient) ListBySubscriptionPreparer(ctx context.Context, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.DevTestLab/schedules", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBySubscriptionSender sends the ListBySubscription request. The method will close the +// http.Response Body if it receives an error. +func (client GlobalSchedulesClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (client GlobalSchedulesClient) ListBySubscriptionResponder(resp *http.Response) (result ScheduleList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBySubscriptionNextResults retrieves the next set of results, if any. +func (client GlobalSchedulesClient) listBySubscriptionNextResults(ctx context.Context, lastResults ScheduleList) (result ScheduleList, err error) { + req, err := lastResults.scheduleListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. +func (client GlobalSchedulesClient) ListBySubscriptionComplete(ctx context.Context, expand string, filter string, top *int32, orderby string) (result ScheduleListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GlobalSchedulesClient.ListBySubscription") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListBySubscription(ctx, expand, filter, top, orderby) + return +} + +// Retarget updates a schedule's target resource Id. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the schedule. +// retargetScheduleProperties - properties for retargeting a virtual machine schedule. +func (client GlobalSchedulesClient) Retarget(ctx context.Context, resourceGroupName string, name string, retargetScheduleProperties RetargetScheduleProperties) (result GlobalSchedulesRetargetFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GlobalSchedulesClient.Retarget") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.RetargetPreparer(ctx, resourceGroupName, name, retargetScheduleProperties) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "Retarget", nil, "Failure preparing request") + return + } + + result, err = client.RetargetSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "Retarget", result.Response(), "Failure sending request") + return + } + + return +} + +// RetargetPreparer prepares the Retarget request. +func (client GlobalSchedulesClient) RetargetPreparer(ctx context.Context, resourceGroupName string, name string, retargetScheduleProperties RetargetScheduleProperties) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/schedules/{name}/retarget", pathParameters), + autorest.WithJSON(retargetScheduleProperties), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RetargetSender sends the Retarget request. The method will close the +// http.Response Body if it receives an error. +func (client GlobalSchedulesClient) RetargetSender(req *http.Request) (future GlobalSchedulesRetargetFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// RetargetResponder handles the response to the Retarget request. The method always +// closes the http.Response Body. +func (client GlobalSchedulesClient) RetargetResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Update modify properties of schedules. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the schedule. +// schedule - a schedule. +func (client GlobalSchedulesClient) Update(ctx context.Context, resourceGroupName string, name string, schedule ScheduleFragment) (result Schedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GlobalSchedulesClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, name, schedule) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client GlobalSchedulesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, name string, schedule ScheduleFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/schedules/{name}", pathParameters), + autorest.WithJSON(schedule), + 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 GlobalSchedulesClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client GlobalSchedulesClient) UpdateResponder(resp *http.Response) (result Schedule, 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/devtestlabs/mgmt/2018-09-15/dtl/labs.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/labs.go new file mode 100644 index 000000000..16a2ecee4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/labs.go @@ -0,0 +1,1124 @@ +package dtl + +// 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" +) + +// LabsClient is the the DevTest Labs Client. +type LabsClient struct { + BaseClient +} + +// NewLabsClient creates an instance of the LabsClient client. +func NewLabsClient(subscriptionID string) LabsClient { + return NewLabsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewLabsClientWithBaseURI creates an instance of the LabsClient client. +func NewLabsClientWithBaseURI(baseURI string, subscriptionID string) LabsClient { + return LabsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// ClaimAnyVM claim a random claimable virtual machine in the lab. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the lab. +func (client LabsClient) ClaimAnyVM(ctx context.Context, resourceGroupName string, name string) (result LabsClaimAnyVMFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.ClaimAnyVM") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ClaimAnyVMPreparer(ctx, resourceGroupName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ClaimAnyVM", nil, "Failure preparing request") + return + } + + result, err = client.ClaimAnyVMSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ClaimAnyVM", result.Response(), "Failure sending request") + return + } + + return +} + +// ClaimAnyVMPreparer prepares the ClaimAnyVM request. +func (client LabsClient) ClaimAnyVMPreparer(ctx context.Context, resourceGroupName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{name}/claimAnyVm", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ClaimAnyVMSender sends the ClaimAnyVM request. The method will close the +// http.Response Body if it receives an error. +func (client LabsClient) ClaimAnyVMSender(req *http.Request) (future LabsClaimAnyVMFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// ClaimAnyVMResponder handles the response to the ClaimAnyVM request. The method always +// closes the http.Response Body. +func (client LabsClient) ClaimAnyVMResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// CreateEnvironment create virtual machines in a lab. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the lab. +// labVirtualMachineCreationParameter - properties for creating a virtual machine. +func (client LabsClient) CreateEnvironment(ctx context.Context, resourceGroupName string, name string, labVirtualMachineCreationParameter LabVirtualMachineCreationParameter) (result LabsCreateEnvironmentFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.CreateEnvironment") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateEnvironmentPreparer(ctx, resourceGroupName, name, labVirtualMachineCreationParameter) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "CreateEnvironment", nil, "Failure preparing request") + return + } + + result, err = client.CreateEnvironmentSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "CreateEnvironment", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateEnvironmentPreparer prepares the CreateEnvironment request. +func (client LabsClient) CreateEnvironmentPreparer(ctx context.Context, resourceGroupName string, name string, labVirtualMachineCreationParameter LabVirtualMachineCreationParameter) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{name}/createEnvironment", pathParameters), + autorest.WithJSON(labVirtualMachineCreationParameter), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateEnvironmentSender sends the CreateEnvironment request. The method will close the +// http.Response Body if it receives an error. +func (client LabsClient) CreateEnvironmentSender(req *http.Request) (future LabsCreateEnvironmentFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateEnvironmentResponder handles the response to the CreateEnvironment request. The method always +// closes the http.Response Body. +func (client LabsClient) CreateEnvironmentResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// CreateOrUpdate create or replace an existing lab. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the lab. +// lab - a lab. +func (client LabsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, name string, lab Lab) (result LabsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, name, lab) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client LabsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, name string, lab Lab) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{name}", pathParameters), + autorest.WithJSON(lab), + 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 LabsClient) CreateOrUpdateSender(req *http.Request) (future LabsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 LabsClient) CreateOrUpdateResponder(resp *http.Response) (result Lab, 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 delete lab. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the lab. +func (client LabsClient) Delete(ctx context.Context, resourceGroupName string, name string) (result LabsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client LabsClient) DeletePreparer(ctx context.Context, resourceGroupName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{name}", 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 LabsClient) DeleteSender(req *http.Request) (future LabsDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 LabsClient) 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 +} + +// ExportResourceUsage exports the lab resource usage into a storage account This operation can take a while to +// complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the lab. +// exportResourceUsageParameters - the parameters of the export operation. +func (client LabsClient) ExportResourceUsage(ctx context.Context, resourceGroupName string, name string, exportResourceUsageParameters ExportResourceUsageParameters) (result LabsExportResourceUsageFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.ExportResourceUsage") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ExportResourceUsagePreparer(ctx, resourceGroupName, name, exportResourceUsageParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ExportResourceUsage", nil, "Failure preparing request") + return + } + + result, err = client.ExportResourceUsageSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ExportResourceUsage", result.Response(), "Failure sending request") + return + } + + return +} + +// ExportResourceUsagePreparer prepares the ExportResourceUsage request. +func (client LabsClient) ExportResourceUsagePreparer(ctx context.Context, resourceGroupName string, name string, exportResourceUsageParameters ExportResourceUsageParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{name}/exportResourceUsage", pathParameters), + autorest.WithJSON(exportResourceUsageParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ExportResourceUsageSender sends the ExportResourceUsage request. The method will close the +// http.Response Body if it receives an error. +func (client LabsClient) ExportResourceUsageSender(req *http.Request) (future LabsExportResourceUsageFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// ExportResourceUsageResponder handles the response to the ExportResourceUsage request. The method always +// closes the http.Response Body. +func (client LabsClient) ExportResourceUsageResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// GenerateUploadURI generate a URI for uploading custom disk images to a Lab. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the lab. +// generateUploadURIParameter - properties for generating an upload URI. +func (client LabsClient) GenerateUploadURI(ctx context.Context, resourceGroupName string, name string, generateUploadURIParameter GenerateUploadURIParameter) (result GenerateUploadURIResponse, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.GenerateUploadURI") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GenerateUploadURIPreparer(ctx, resourceGroupName, name, generateUploadURIParameter) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "GenerateUploadURI", nil, "Failure preparing request") + return + } + + resp, err := client.GenerateUploadURISender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "GenerateUploadURI", resp, "Failure sending request") + return + } + + result, err = client.GenerateUploadURIResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "GenerateUploadURI", resp, "Failure responding to request") + } + + return +} + +// GenerateUploadURIPreparer prepares the GenerateUploadURI request. +func (client LabsClient) GenerateUploadURIPreparer(ctx context.Context, resourceGroupName string, name string, generateUploadURIParameter GenerateUploadURIParameter) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{name}/generateUploadUri", pathParameters), + autorest.WithJSON(generateUploadURIParameter), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GenerateUploadURISender sends the GenerateUploadURI request. The method will close the +// http.Response Body if it receives an error. +func (client LabsClient) GenerateUploadURISender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GenerateUploadURIResponder handles the response to the GenerateUploadURI request. The method always +// closes the http.Response Body. +func (client LabsClient) GenerateUploadURIResponder(resp *http.Response) (result GenerateUploadURIResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get get lab. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the lab. +// expand - specify the $expand query. Example: 'properties($select=defaultStorageAccount)' +func (client LabsClient) Get(ctx context.Context, resourceGroupName string, name string, expand string) (result Lab, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.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, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client LabsClient) GetPreparer(ctx context.Context, resourceGroupName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{name}", 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 LabsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client LabsClient) GetResponder(resp *http.Response) (result Lab, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ImportVirtualMachine import a virtual machine into a different lab. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the lab. +// importLabVirtualMachineRequest - this represents the payload required to import a virtual machine from a +// different lab into the current one +func (client LabsClient) ImportVirtualMachine(ctx context.Context, resourceGroupName string, name string, importLabVirtualMachineRequest ImportLabVirtualMachineRequest) (result LabsImportVirtualMachineFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.ImportVirtualMachine") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ImportVirtualMachinePreparer(ctx, resourceGroupName, name, importLabVirtualMachineRequest) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ImportVirtualMachine", nil, "Failure preparing request") + return + } + + result, err = client.ImportVirtualMachineSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ImportVirtualMachine", result.Response(), "Failure sending request") + return + } + + return +} + +// ImportVirtualMachinePreparer prepares the ImportVirtualMachine request. +func (client LabsClient) ImportVirtualMachinePreparer(ctx context.Context, resourceGroupName string, name string, importLabVirtualMachineRequest ImportLabVirtualMachineRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{name}/importVirtualMachine", pathParameters), + autorest.WithJSON(importLabVirtualMachineRequest), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ImportVirtualMachineSender sends the ImportVirtualMachine request. The method will close the +// http.Response Body if it receives an error. +func (client LabsClient) ImportVirtualMachineSender(req *http.Request) (future LabsImportVirtualMachineFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// ImportVirtualMachineResponder handles the response to the ImportVirtualMachine request. The method always +// closes the http.Response Body. +func (client LabsClient) ImportVirtualMachineResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// ListByResourceGroup list labs in a resource group. +// Parameters: +// resourceGroupName - the name of the resource group. +// expand - specify the $expand query. Example: 'properties($select=defaultStorageAccount)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client LabsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, expand string, filter string, top *int32, orderby string) (result LabListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.ListByResourceGroup") + defer func() { + sc := -1 + if result.ll.Response.Response != nil { + sc = result.ll.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.ll.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result.ll, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client LabsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs", 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 LabsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client LabsClient) ListByResourceGroupResponder(resp *http.Response) (result LabList, 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 LabsClient) listByResourceGroupNextResults(ctx context.Context, lastResults LabList) (result LabList, err error) { + req, err := lastResults.labListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.LabsClient", "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, "dtl.LabsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client LabsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, expand string, filter string, top *int32, orderby string) (result LabListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.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, expand, filter, top, orderby) + return +} + +// ListBySubscription list labs in a subscription. +// Parameters: +// expand - specify the $expand query. Example: 'properties($select=defaultStorageAccount)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client LabsClient) ListBySubscription(ctx context.Context, expand string, filter string, top *int32, orderby string) (result LabListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.ListBySubscription") + defer func() { + sc := -1 + if result.ll.Response.Response != nil { + sc = result.ll.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listBySubscriptionNextResults + req, err := client.ListBySubscriptionPreparer(ctx, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.ll.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ListBySubscription", resp, "Failure sending request") + return + } + + result.ll, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ListBySubscription", resp, "Failure responding to request") + } + + return +} + +// ListBySubscriptionPreparer prepares the ListBySubscription request. +func (client LabsClient) ListBySubscriptionPreparer(ctx context.Context, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.DevTestLab/labs", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBySubscriptionSender sends the ListBySubscription request. The method will close the +// http.Response Body if it receives an error. +func (client LabsClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (client LabsClient) ListBySubscriptionResponder(resp *http.Response) (result LabList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBySubscriptionNextResults retrieves the next set of results, if any. +func (client LabsClient) listBySubscriptionNextResults(ctx context.Context, lastResults LabList) (result LabList, err error) { + req, err := lastResults.labListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.LabsClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "dtl.LabsClient", "listBySubscriptionNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required. +func (client LabsClient) ListBySubscriptionComplete(ctx context.Context, expand string, filter string, top *int32, orderby string) (result LabListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.ListBySubscription") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.ListBySubscription(ctx, expand, filter, top, orderby) + return +} + +// ListVhds list disk images available for custom image creation. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the lab. +func (client LabsClient) ListVhds(ctx context.Context, resourceGroupName string, name string) (result LabVhdListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.ListVhds") + defer func() { + sc := -1 + if result.lvl.Response.Response != nil { + sc = result.lvl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listVhdsNextResults + req, err := client.ListVhdsPreparer(ctx, resourceGroupName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ListVhds", nil, "Failure preparing request") + return + } + + resp, err := client.ListVhdsSender(req) + if err != nil { + result.lvl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ListVhds", resp, "Failure sending request") + return + } + + result.lvl, err = client.ListVhdsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "ListVhds", resp, "Failure responding to request") + } + + return +} + +// ListVhdsPreparer prepares the ListVhds request. +func (client LabsClient) ListVhdsPreparer(ctx context.Context, resourceGroupName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{name}/listVhds", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListVhdsSender sends the ListVhds request. The method will close the +// http.Response Body if it receives an error. +func (client LabsClient) ListVhdsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListVhdsResponder handles the response to the ListVhds request. The method always +// closes the http.Response Body. +func (client LabsClient) ListVhdsResponder(resp *http.Response) (result LabVhdList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listVhdsNextResults retrieves the next set of results, if any. +func (client LabsClient) listVhdsNextResults(ctx context.Context, lastResults LabVhdList) (result LabVhdList, err error) { + req, err := lastResults.labVhdListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.LabsClient", "listVhdsNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListVhdsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "dtl.LabsClient", "listVhdsNextResults", resp, "Failure sending next results request") + } + result, err = client.ListVhdsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "listVhdsNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListVhdsComplete enumerates all values, automatically crossing page boundaries as required. +func (client LabsClient) ListVhdsComplete(ctx context.Context, resourceGroupName string, name string) (result LabVhdListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.ListVhds") + 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.ListVhds(ctx, resourceGroupName, name) + return +} + +// Update modify properties of labs. +// Parameters: +// resourceGroupName - the name of the resource group. +// name - the name of the lab. +// lab - a lab. +func (client LabsClient) Update(ctx context.Context, resourceGroupName string, name string, lab LabFragment) (result Lab, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabsClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, name, lab) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client LabsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, name string, lab LabFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{name}", pathParameters), + autorest.WithJSON(lab), + 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 LabsClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client LabsClient) UpdateResponder(resp *http.Response) (result Lab, 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/devtestlabs/mgmt/2018-09-15/dtl/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/models.go new file mode 100644 index 000000000..98acd9422 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/models.go @@ -0,0 +1,9538 @@ +package dtl + +// 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/date" + "github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// The package's fully qualified name. +const fqdn = "github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl" + +// CostThresholdStatus enumerates the values for cost threshold status. +type CostThresholdStatus string + +const ( + // Disabled ... + Disabled CostThresholdStatus = "Disabled" + // Enabled ... + Enabled CostThresholdStatus = "Enabled" +) + +// PossibleCostThresholdStatusValues returns an array of possible values for the CostThresholdStatus const type. +func PossibleCostThresholdStatusValues() []CostThresholdStatus { + return []CostThresholdStatus{Disabled, Enabled} +} + +// CostType enumerates the values for cost type. +type CostType string + +const ( + // Projected ... + Projected CostType = "Projected" + // Reported ... + Reported CostType = "Reported" + // Unavailable ... + Unavailable CostType = "Unavailable" +) + +// PossibleCostTypeValues returns an array of possible values for the CostType const type. +func PossibleCostTypeValues() []CostType { + return []CostType{Projected, Reported, Unavailable} +} + +// CustomImageOsType enumerates the values for custom image os type. +type CustomImageOsType string + +const ( + // Linux ... + Linux CustomImageOsType = "Linux" + // None ... + None CustomImageOsType = "None" + // Windows ... + Windows CustomImageOsType = "Windows" +) + +// PossibleCustomImageOsTypeValues returns an array of possible values for the CustomImageOsType const type. +func PossibleCustomImageOsTypeValues() []CustomImageOsType { + return []CustomImageOsType{Linux, None, Windows} +} + +// EnableStatus enumerates the values for enable status. +type EnableStatus string + +const ( + // EnableStatusDisabled ... + EnableStatusDisabled EnableStatus = "Disabled" + // EnableStatusEnabled ... + EnableStatusEnabled EnableStatus = "Enabled" +) + +// PossibleEnableStatusValues returns an array of possible values for the EnableStatus const type. +func PossibleEnableStatusValues() []EnableStatus { + return []EnableStatus{EnableStatusDisabled, EnableStatusEnabled} +} + +// EnvironmentPermission enumerates the values for environment permission. +type EnvironmentPermission string + +const ( + // Contributor ... + Contributor EnvironmentPermission = "Contributor" + // Reader ... + Reader EnvironmentPermission = "Reader" +) + +// PossibleEnvironmentPermissionValues returns an array of possible values for the EnvironmentPermission const type. +func PossibleEnvironmentPermissionValues() []EnvironmentPermission { + return []EnvironmentPermission{Contributor, Reader} +} + +// FileUploadOptions enumerates the values for file upload options. +type FileUploadOptions string + +const ( + // FileUploadOptionsNone ... + FileUploadOptionsNone FileUploadOptions = "None" + // FileUploadOptionsUploadFilesAndGenerateSasTokens ... + FileUploadOptionsUploadFilesAndGenerateSasTokens FileUploadOptions = "UploadFilesAndGenerateSasTokens" +) + +// PossibleFileUploadOptionsValues returns an array of possible values for the FileUploadOptions const type. +func PossibleFileUploadOptionsValues() []FileUploadOptions { + return []FileUploadOptions{FileUploadOptionsNone, FileUploadOptionsUploadFilesAndGenerateSasTokens} +} + +// HostCachingOptions enumerates the values for host caching options. +type HostCachingOptions string + +const ( + // HostCachingOptionsNone ... + HostCachingOptionsNone HostCachingOptions = "None" + // HostCachingOptionsReadOnly ... + HostCachingOptionsReadOnly HostCachingOptions = "ReadOnly" + // HostCachingOptionsReadWrite ... + HostCachingOptionsReadWrite HostCachingOptions = "ReadWrite" +) + +// PossibleHostCachingOptionsValues returns an array of possible values for the HostCachingOptions const type. +func PossibleHostCachingOptionsValues() []HostCachingOptions { + return []HostCachingOptions{HostCachingOptionsNone, HostCachingOptionsReadOnly, HostCachingOptionsReadWrite} +} + +// HTTPStatusCode enumerates the values for http status code. +type HTTPStatusCode string + +const ( + // Accepted ... + Accepted HTTPStatusCode = "Accepted" + // BadGateway ... + BadGateway HTTPStatusCode = "BadGateway" + // BadRequest ... + BadRequest HTTPStatusCode = "BadRequest" + // Conflict ... + Conflict HTTPStatusCode = "Conflict" + // Continue ... + Continue HTTPStatusCode = "Continue" + // Created ... + Created HTTPStatusCode = "Created" + // ExpectationFailed ... + ExpectationFailed HTTPStatusCode = "ExpectationFailed" + // Forbidden ... + Forbidden HTTPStatusCode = "Forbidden" + // GatewayTimeout ... + GatewayTimeout HTTPStatusCode = "GatewayTimeout" + // Gone ... + Gone HTTPStatusCode = "Gone" + // HTTPVersionNotSupported ... + HTTPVersionNotSupported HTTPStatusCode = "HttpVersionNotSupported" + // InternalServerError ... + InternalServerError HTTPStatusCode = "InternalServerError" + // LengthRequired ... + LengthRequired HTTPStatusCode = "LengthRequired" + // MethodNotAllowed ... + MethodNotAllowed HTTPStatusCode = "MethodNotAllowed" + // MovedPermanently ... + MovedPermanently HTTPStatusCode = "MovedPermanently" + // MultipleChoices ... + MultipleChoices HTTPStatusCode = "MultipleChoices" + // NoContent ... + NoContent HTTPStatusCode = "NoContent" + // NonAuthoritativeInformation ... + NonAuthoritativeInformation HTTPStatusCode = "NonAuthoritativeInformation" + // NotAcceptable ... + NotAcceptable HTTPStatusCode = "NotAcceptable" + // NotFound ... + NotFound HTTPStatusCode = "NotFound" + // NotImplemented ... + NotImplemented HTTPStatusCode = "NotImplemented" + // NotModified ... + NotModified HTTPStatusCode = "NotModified" + // OK ... + OK HTTPStatusCode = "OK" + // PartialContent ... + PartialContent HTTPStatusCode = "PartialContent" + // PaymentRequired ... + PaymentRequired HTTPStatusCode = "PaymentRequired" + // PreconditionFailed ... + PreconditionFailed HTTPStatusCode = "PreconditionFailed" + // ProxyAuthenticationRequired ... + ProxyAuthenticationRequired HTTPStatusCode = "ProxyAuthenticationRequired" + // Redirect ... + Redirect HTTPStatusCode = "Redirect" + // RequestedRangeNotSatisfiable ... + RequestedRangeNotSatisfiable HTTPStatusCode = "RequestedRangeNotSatisfiable" + // RequestEntityTooLarge ... + RequestEntityTooLarge HTTPStatusCode = "RequestEntityTooLarge" + // RequestTimeout ... + RequestTimeout HTTPStatusCode = "RequestTimeout" + // RequestURITooLong ... + RequestURITooLong HTTPStatusCode = "RequestUriTooLong" + // ResetContent ... + ResetContent HTTPStatusCode = "ResetContent" + // SeeOther ... + SeeOther HTTPStatusCode = "SeeOther" + // ServiceUnavailable ... + ServiceUnavailable HTTPStatusCode = "ServiceUnavailable" + // SwitchingProtocols ... + SwitchingProtocols HTTPStatusCode = "SwitchingProtocols" + // TemporaryRedirect ... + TemporaryRedirect HTTPStatusCode = "TemporaryRedirect" + // Unauthorized ... + Unauthorized HTTPStatusCode = "Unauthorized" + // UnsupportedMediaType ... + UnsupportedMediaType HTTPStatusCode = "UnsupportedMediaType" + // Unused ... + Unused HTTPStatusCode = "Unused" + // UpgradeRequired ... + UpgradeRequired HTTPStatusCode = "UpgradeRequired" + // UseProxy ... + UseProxy HTTPStatusCode = "UseProxy" +) + +// PossibleHTTPStatusCodeValues returns an array of possible values for the HTTPStatusCode const type. +func PossibleHTTPStatusCodeValues() []HTTPStatusCode { + return []HTTPStatusCode{Accepted, BadGateway, BadRequest, Conflict, Continue, Created, ExpectationFailed, Forbidden, GatewayTimeout, Gone, HTTPVersionNotSupported, InternalServerError, LengthRequired, MethodNotAllowed, MovedPermanently, MultipleChoices, NoContent, NonAuthoritativeInformation, NotAcceptable, NotFound, NotImplemented, NotModified, OK, PartialContent, PaymentRequired, PreconditionFailed, ProxyAuthenticationRequired, Redirect, RequestedRangeNotSatisfiable, RequestEntityTooLarge, RequestTimeout, RequestURITooLong, ResetContent, SeeOther, ServiceUnavailable, SwitchingProtocols, TemporaryRedirect, Unauthorized, UnsupportedMediaType, Unused, UpgradeRequired, UseProxy} +} + +// LinuxOsState enumerates the values for linux os state. +type LinuxOsState string + +const ( + // DeprovisionApplied ... + DeprovisionApplied LinuxOsState = "DeprovisionApplied" + // DeprovisionRequested ... + DeprovisionRequested LinuxOsState = "DeprovisionRequested" + // NonDeprovisioned ... + NonDeprovisioned LinuxOsState = "NonDeprovisioned" +) + +// PossibleLinuxOsStateValues returns an array of possible values for the LinuxOsState const type. +func PossibleLinuxOsStateValues() []LinuxOsState { + return []LinuxOsState{DeprovisionApplied, DeprovisionRequested, NonDeprovisioned} +} + +// NotificationChannelEventType enumerates the values for notification channel event type. +type NotificationChannelEventType string + +const ( + // AutoShutdown ... + AutoShutdown NotificationChannelEventType = "AutoShutdown" + // Cost ... + Cost NotificationChannelEventType = "Cost" +) + +// PossibleNotificationChannelEventTypeValues returns an array of possible values for the NotificationChannelEventType const type. +func PossibleNotificationChannelEventTypeValues() []NotificationChannelEventType { + return []NotificationChannelEventType{AutoShutdown, Cost} +} + +// PolicyEvaluatorType enumerates the values for policy evaluator type. +type PolicyEvaluatorType string + +const ( + // AllowedValuesPolicy ... + AllowedValuesPolicy PolicyEvaluatorType = "AllowedValuesPolicy" + // MaxValuePolicy ... + MaxValuePolicy PolicyEvaluatorType = "MaxValuePolicy" +) + +// PossiblePolicyEvaluatorTypeValues returns an array of possible values for the PolicyEvaluatorType const type. +func PossiblePolicyEvaluatorTypeValues() []PolicyEvaluatorType { + return []PolicyEvaluatorType{AllowedValuesPolicy, MaxValuePolicy} +} + +// PolicyFactName enumerates the values for policy fact name. +type PolicyFactName string + +const ( + // PolicyFactNameEnvironmentTemplate ... + PolicyFactNameEnvironmentTemplate PolicyFactName = "EnvironmentTemplate" + // PolicyFactNameGalleryImage ... + PolicyFactNameGalleryImage PolicyFactName = "GalleryImage" + // PolicyFactNameLabPremiumVMCount ... + PolicyFactNameLabPremiumVMCount PolicyFactName = "LabPremiumVmCount" + // PolicyFactNameLabTargetCost ... + PolicyFactNameLabTargetCost PolicyFactName = "LabTargetCost" + // PolicyFactNameLabVMCount ... + PolicyFactNameLabVMCount PolicyFactName = "LabVmCount" + // PolicyFactNameLabVMSize ... + PolicyFactNameLabVMSize PolicyFactName = "LabVmSize" + // PolicyFactNameScheduleEditPermission ... + PolicyFactNameScheduleEditPermission PolicyFactName = "ScheduleEditPermission" + // PolicyFactNameUserOwnedLabPremiumVMCount ... + PolicyFactNameUserOwnedLabPremiumVMCount PolicyFactName = "UserOwnedLabPremiumVmCount" + // PolicyFactNameUserOwnedLabVMCount ... + PolicyFactNameUserOwnedLabVMCount PolicyFactName = "UserOwnedLabVmCount" + // PolicyFactNameUserOwnedLabVMCountInSubnet ... + PolicyFactNameUserOwnedLabVMCountInSubnet PolicyFactName = "UserOwnedLabVmCountInSubnet" +) + +// PossiblePolicyFactNameValues returns an array of possible values for the PolicyFactName const type. +func PossiblePolicyFactNameValues() []PolicyFactName { + return []PolicyFactName{PolicyFactNameEnvironmentTemplate, PolicyFactNameGalleryImage, PolicyFactNameLabPremiumVMCount, PolicyFactNameLabTargetCost, PolicyFactNameLabVMCount, PolicyFactNameLabVMSize, PolicyFactNameScheduleEditPermission, PolicyFactNameUserOwnedLabPremiumVMCount, PolicyFactNameUserOwnedLabVMCount, PolicyFactNameUserOwnedLabVMCountInSubnet} +} + +// PolicyStatus enumerates the values for policy status. +type PolicyStatus string + +const ( + // PolicyStatusDisabled ... + PolicyStatusDisabled PolicyStatus = "Disabled" + // PolicyStatusEnabled ... + PolicyStatusEnabled PolicyStatus = "Enabled" +) + +// PossiblePolicyStatusValues returns an array of possible values for the PolicyStatus const type. +func PossiblePolicyStatusValues() []PolicyStatus { + return []PolicyStatus{PolicyStatusDisabled, PolicyStatusEnabled} +} + +// PremiumDataDisk enumerates the values for premium data disk. +type PremiumDataDisk string + +const ( + // PremiumDataDiskDisabled ... + PremiumDataDiskDisabled PremiumDataDisk = "Disabled" + // PremiumDataDiskEnabled ... + PremiumDataDiskEnabled PremiumDataDisk = "Enabled" +) + +// PossiblePremiumDataDiskValues returns an array of possible values for the PremiumDataDisk const type. +func PossiblePremiumDataDiskValues() []PremiumDataDisk { + return []PremiumDataDisk{PremiumDataDiskDisabled, PremiumDataDiskEnabled} +} + +// ReportingCycleType enumerates the values for reporting cycle type. +type ReportingCycleType string + +const ( + // CalendarMonth ... + CalendarMonth ReportingCycleType = "CalendarMonth" + // Custom ... + Custom ReportingCycleType = "Custom" +) + +// PossibleReportingCycleTypeValues returns an array of possible values for the ReportingCycleType const type. +func PossibleReportingCycleTypeValues() []ReportingCycleType { + return []ReportingCycleType{CalendarMonth, Custom} +} + +// SourceControlType enumerates the values for source control type. +type SourceControlType string + +const ( + // GitHub ... + GitHub SourceControlType = "GitHub" + // VsoGit ... + VsoGit SourceControlType = "VsoGit" +) + +// PossibleSourceControlTypeValues returns an array of possible values for the SourceControlType const type. +func PossibleSourceControlTypeValues() []SourceControlType { + return []SourceControlType{GitHub, VsoGit} +} + +// StorageType enumerates the values for storage type. +type StorageType string + +const ( + // Premium ... + Premium StorageType = "Premium" + // Standard ... + Standard StorageType = "Standard" +) + +// PossibleStorageTypeValues returns an array of possible values for the StorageType const type. +func PossibleStorageTypeValues() []StorageType { + return []StorageType{Premium, Standard} +} + +// TargetCostStatus enumerates the values for target cost status. +type TargetCostStatus string + +const ( + // TargetCostStatusDisabled ... + TargetCostStatusDisabled TargetCostStatus = "Disabled" + // TargetCostStatusEnabled ... + TargetCostStatusEnabled TargetCostStatus = "Enabled" +) + +// PossibleTargetCostStatusValues returns an array of possible values for the TargetCostStatus const type. +func PossibleTargetCostStatusValues() []TargetCostStatus { + return []TargetCostStatus{TargetCostStatusDisabled, TargetCostStatusEnabled} +} + +// TransportProtocol enumerates the values for transport protocol. +type TransportProtocol string + +const ( + // TCP ... + TCP TransportProtocol = "Tcp" + // UDP ... + UDP TransportProtocol = "Udp" +) + +// PossibleTransportProtocolValues returns an array of possible values for the TransportProtocol const type. +func PossibleTransportProtocolValues() []TransportProtocol { + return []TransportProtocol{TCP, UDP} +} + +// UsagePermissionType enumerates the values for usage permission type. +type UsagePermissionType string + +const ( + // Allow ... + Allow UsagePermissionType = "Allow" + // Default ... + Default UsagePermissionType = "Default" + // Deny ... + Deny UsagePermissionType = "Deny" +) + +// PossibleUsagePermissionTypeValues returns an array of possible values for the UsagePermissionType const type. +func PossibleUsagePermissionTypeValues() []UsagePermissionType { + return []UsagePermissionType{Allow, Default, Deny} +} + +// VirtualMachineCreationSource enumerates the values for virtual machine creation source. +type VirtualMachineCreationSource string + +const ( + // FromCustomImage ... + FromCustomImage VirtualMachineCreationSource = "FromCustomImage" + // FromGalleryImage ... + FromGalleryImage VirtualMachineCreationSource = "FromGalleryImage" +) + +// PossibleVirtualMachineCreationSourceValues returns an array of possible values for the VirtualMachineCreationSource const type. +func PossibleVirtualMachineCreationSourceValues() []VirtualMachineCreationSource { + return []VirtualMachineCreationSource{FromCustomImage, FromGalleryImage} +} + +// WindowsOsState enumerates the values for windows os state. +type WindowsOsState string + +const ( + // NonSysprepped ... + NonSysprepped WindowsOsState = "NonSysprepped" + // SysprepApplied ... + SysprepApplied WindowsOsState = "SysprepApplied" + // SysprepRequested ... + SysprepRequested WindowsOsState = "SysprepRequested" +) + +// PossibleWindowsOsStateValues returns an array of possible values for the WindowsOsState const type. +func PossibleWindowsOsStateValues() []WindowsOsState { + return []WindowsOsState{NonSysprepped, SysprepApplied, SysprepRequested} +} + +// ApplicableSchedule schedules applicable to a virtual machine. The schedules may have been defined on a +// VM or on lab level. +type ApplicableSchedule struct { + autorest.Response `json:"-"` + // ApplicableScheduleProperties - The properties of the resource. + *ApplicableScheduleProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ApplicableSchedule. +func (as ApplicableSchedule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if as.ApplicableScheduleProperties != nil { + objectMap["properties"] = as.ApplicableScheduleProperties + } + if as.Location != nil { + objectMap["location"] = as.Location + } + if as.Tags != nil { + objectMap["tags"] = as.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ApplicableSchedule struct. +func (as *ApplicableSchedule) 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 applicableScheduleProperties ApplicableScheduleProperties + err = json.Unmarshal(*v, &applicableScheduleProperties) + if err != nil { + return err + } + as.ApplicableScheduleProperties = &applicableScheduleProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + as.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + as.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + as.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + as.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + as.Tags = tags + } + } + } + + return nil +} + +// ApplicableScheduleFragment schedules applicable to a virtual machine. The schedules may have been +// defined on a VM or on lab level. +type ApplicableScheduleFragment struct { + // ApplicableSchedulePropertiesFragment - The properties of the resource. + *ApplicableSchedulePropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ApplicableScheduleFragment. +func (asf ApplicableScheduleFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if asf.ApplicableSchedulePropertiesFragment != nil { + objectMap["properties"] = asf.ApplicableSchedulePropertiesFragment + } + if asf.Tags != nil { + objectMap["tags"] = asf.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ApplicableScheduleFragment struct. +func (asf *ApplicableScheduleFragment) 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 applicableSchedulePropertiesFragment ApplicableSchedulePropertiesFragment + err = json.Unmarshal(*v, &applicableSchedulePropertiesFragment) + if err != nil { + return err + } + asf.ApplicableSchedulePropertiesFragment = &applicableSchedulePropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + asf.Tags = tags + } + } + } + + return nil +} + +// ApplicableScheduleProperties properties of a schedules applicable to a virtual machine. +type ApplicableScheduleProperties struct { + // LabVmsShutdown - The auto-shutdown schedule, if one has been set at the lab or lab resource level. + LabVmsShutdown *Schedule `json:"labVmsShutdown,omitempty"` + // LabVmsStartup - The auto-startup schedule, if one has been set at the lab or lab resource level. + LabVmsStartup *Schedule `json:"labVmsStartup,omitempty"` +} + +// ApplicableSchedulePropertiesFragment properties of a schedules applicable to a virtual machine. +type ApplicableSchedulePropertiesFragment struct { + // LabVmsShutdown - The auto-shutdown schedule, if one has been set at the lab or lab resource level. + LabVmsShutdown *ScheduleFragment `json:"labVmsShutdown,omitempty"` + // LabVmsStartup - The auto-startup schedule, if one has been set at the lab or lab resource level. + LabVmsStartup *ScheduleFragment `json:"labVmsStartup,omitempty"` +} + +// ApplyArtifactsRequest request body for applying artifacts to a virtual machine. +type ApplyArtifactsRequest struct { + // Artifacts - The list of artifacts to apply. + Artifacts *[]ArtifactInstallProperties `json:"artifacts,omitempty"` +} + +// ArmTemplate an Azure Resource Manager template. +type ArmTemplate struct { + autorest.Response `json:"-"` + // ArmTemplateProperties - The properties of the resource. + *ArmTemplateProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ArmTemplate. +func (at ArmTemplate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if at.ArmTemplateProperties != nil { + objectMap["properties"] = at.ArmTemplateProperties + } + if at.Location != nil { + objectMap["location"] = at.Location + } + if at.Tags != nil { + objectMap["tags"] = at.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ArmTemplate struct. +func (at *ArmTemplate) 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 armTemplateProperties ArmTemplateProperties + err = json.Unmarshal(*v, &armTemplateProperties) + if err != nil { + return err + } + at.ArmTemplateProperties = &armTemplateProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + at.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + at.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + at.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + at.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + at.Tags = tags + } + } + } + + return nil +} + +// ArmTemplateInfo information about a generated ARM template. +type ArmTemplateInfo struct { + autorest.Response `json:"-"` + // Template - The template's contents. + Template interface{} `json:"template,omitempty"` + // Parameters - The parameters of the ARM template. + Parameters interface{} `json:"parameters,omitempty"` +} + +// ArmTemplateList the response of a list operation. +type ArmTemplateList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]ArmTemplate `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ArmTemplateListIterator provides access to a complete listing of ArmTemplate values. +type ArmTemplateListIterator struct { + i int + page ArmTemplateListPage +} + +// 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 *ArmTemplateListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArmTemplateListIterator.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 *ArmTemplateListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ArmTemplateListIterator) 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 ArmTemplateListIterator) Response() ArmTemplateList { + 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 ArmTemplateListIterator) Value() ArmTemplate { + if !iter.page.NotDone() { + return ArmTemplate{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ArmTemplateListIterator type. +func NewArmTemplateListIterator(page ArmTemplateListPage) ArmTemplateListIterator { + return ArmTemplateListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (atl ArmTemplateList) IsEmpty() bool { + return atl.Value == nil || len(*atl.Value) == 0 +} + +// armTemplateListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (atl ArmTemplateList) armTemplateListPreparer(ctx context.Context) (*http.Request, error) { + if atl.NextLink == nil || len(to.String(atl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(atl.NextLink))) +} + +// ArmTemplateListPage contains a page of ArmTemplate values. +type ArmTemplateListPage struct { + fn func(context.Context, ArmTemplateList) (ArmTemplateList, error) + atl ArmTemplateList +} + +// 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 *ArmTemplateListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArmTemplateListPage.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.atl) + if err != nil { + return err + } + page.atl = 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 *ArmTemplateListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ArmTemplateListPage) NotDone() bool { + return !page.atl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ArmTemplateListPage) Response() ArmTemplateList { + return page.atl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ArmTemplateListPage) Values() []ArmTemplate { + if page.atl.IsEmpty() { + return nil + } + return *page.atl.Value +} + +// Creates a new instance of the ArmTemplateListPage type. +func NewArmTemplateListPage(getNextPage func(context.Context, ArmTemplateList) (ArmTemplateList, error)) ArmTemplateListPage { + return ArmTemplateListPage{fn: getNextPage} +} + +// ArmTemplateParameterProperties properties of an Azure Resource Manager template parameter. +type ArmTemplateParameterProperties struct { + // Name - The name of the template parameter. + Name *string `json:"name,omitempty"` + // Value - The value of the template parameter. + Value *string `json:"value,omitempty"` +} + +// ArmTemplateParameterPropertiesFragment properties of an Azure Resource Manager template parameter. +type ArmTemplateParameterPropertiesFragment struct { + // Name - The name of the template parameter. + Name *string `json:"name,omitempty"` + // Value - The value of the template parameter. + Value *string `json:"value,omitempty"` +} + +// ArmTemplateProperties properties of an Azure Resource Manager template. +type ArmTemplateProperties struct { + // DisplayName - READ-ONLY; The display name of the ARM template. + DisplayName *string `json:"displayName,omitempty"` + // Description - READ-ONLY; The description of the ARM template. + Description *string `json:"description,omitempty"` + // Publisher - READ-ONLY; The publisher of the ARM template. + Publisher *string `json:"publisher,omitempty"` + // Icon - READ-ONLY; The URI to the icon of the ARM template. + Icon *string `json:"icon,omitempty"` + // Contents - READ-ONLY; The contents of the ARM template. + Contents interface{} `json:"contents,omitempty"` + // CreatedDate - READ-ONLY; The creation date of the armTemplate. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // ParametersValueFilesInfo - READ-ONLY; File name and parameter values information from all azuredeploy.*.parameters.json for the ARM template. + ParametersValueFilesInfo *[]ParametersValueFileInfo `json:"parametersValueFilesInfo,omitempty"` + // Enabled - READ-ONLY; Whether or not ARM template is enabled for use by lab user. + Enabled *bool `json:"enabled,omitempty"` +} + +// Artifact an artifact. +type Artifact struct { + autorest.Response `json:"-"` + // ArtifactProperties - The properties of the resource. + *ArtifactProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Artifact. +func (a Artifact) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if a.ArtifactProperties != nil { + objectMap["properties"] = a.ArtifactProperties + } + if a.Location != nil { + objectMap["location"] = a.Location + } + if a.Tags != nil { + objectMap["tags"] = a.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Artifact struct. +func (a *Artifact) 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 artifactProperties ArtifactProperties + err = json.Unmarshal(*v, &artifactProperties) + if err != nil { + return err + } + a.ArtifactProperties = &artifactProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + a.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + a.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + a.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + a.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + a.Tags = tags + } + } + } + + return nil +} + +// ArtifactDeploymentStatusProperties properties of an artifact deployment. +type ArtifactDeploymentStatusProperties struct { + // DeploymentStatus - The deployment status of the artifact. + DeploymentStatus *string `json:"deploymentStatus,omitempty"` + // ArtifactsApplied - The total count of the artifacts that were successfully applied. + ArtifactsApplied *int32 `json:"artifactsApplied,omitempty"` + // TotalArtifacts - The total count of the artifacts that were tentatively applied. + TotalArtifacts *int32 `json:"totalArtifacts,omitempty"` +} + +// ArtifactDeploymentStatusPropertiesFragment properties of an artifact deployment. +type ArtifactDeploymentStatusPropertiesFragment struct { + // DeploymentStatus - The deployment status of the artifact. + DeploymentStatus *string `json:"deploymentStatus,omitempty"` + // ArtifactsApplied - The total count of the artifacts that were successfully applied. + ArtifactsApplied *int32 `json:"artifactsApplied,omitempty"` + // TotalArtifacts - The total count of the artifacts that were tentatively applied. + TotalArtifacts *int32 `json:"totalArtifacts,omitempty"` +} + +// ArtifactInstallProperties properties of an artifact. +type ArtifactInstallProperties struct { + // ArtifactID - The artifact's identifier. + ArtifactID *string `json:"artifactId,omitempty"` + // ArtifactTitle - The artifact's title. + ArtifactTitle *string `json:"artifactTitle,omitempty"` + // Parameters - The parameters of the artifact. + Parameters *[]ArtifactParameterProperties `json:"parameters,omitempty"` + // Status - The status of the artifact. + Status *string `json:"status,omitempty"` + // DeploymentStatusMessage - The status message from the deployment. + DeploymentStatusMessage *string `json:"deploymentStatusMessage,omitempty"` + // VMExtensionStatusMessage - The status message from the virtual machine extension. + VMExtensionStatusMessage *string `json:"vmExtensionStatusMessage,omitempty"` + // InstallTime - The time that the artifact starts to install on the virtual machine. + InstallTime *date.Time `json:"installTime,omitempty"` +} + +// ArtifactInstallPropertiesFragment properties of an artifact. +type ArtifactInstallPropertiesFragment struct { + // ArtifactID - The artifact's identifier. + ArtifactID *string `json:"artifactId,omitempty"` + // ArtifactTitle - The artifact's title. + ArtifactTitle *string `json:"artifactTitle,omitempty"` + // Parameters - The parameters of the artifact. + Parameters *[]ArtifactParameterPropertiesFragment `json:"parameters,omitempty"` + // Status - The status of the artifact. + Status *string `json:"status,omitempty"` + // DeploymentStatusMessage - The status message from the deployment. + DeploymentStatusMessage *string `json:"deploymentStatusMessage,omitempty"` + // VMExtensionStatusMessage - The status message from the virtual machine extension. + VMExtensionStatusMessage *string `json:"vmExtensionStatusMessage,omitempty"` + // InstallTime - The time that the artifact starts to install on the virtual machine. + InstallTime *date.Time `json:"installTime,omitempty"` +} + +// ArtifactList the response of a list operation. +type ArtifactList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]Artifact `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ArtifactListIterator provides access to a complete listing of Artifact values. +type ArtifactListIterator struct { + i int + page ArtifactListPage +} + +// 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 *ArtifactListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactListIterator.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 *ArtifactListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ArtifactListIterator) 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 ArtifactListIterator) Response() ArtifactList { + 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 ArtifactListIterator) Value() Artifact { + if !iter.page.NotDone() { + return Artifact{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ArtifactListIterator type. +func NewArtifactListIterator(page ArtifactListPage) ArtifactListIterator { + return ArtifactListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (al ArtifactList) IsEmpty() bool { + return al.Value == nil || len(*al.Value) == 0 +} + +// artifactListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (al ArtifactList) artifactListPreparer(ctx context.Context) (*http.Request, error) { + if al.NextLink == nil || len(to.String(al.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(al.NextLink))) +} + +// ArtifactListPage contains a page of Artifact values. +type ArtifactListPage struct { + fn func(context.Context, ArtifactList) (ArtifactList, error) + al ArtifactList +} + +// 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 *ArtifactListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactListPage.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.al) + if err != nil { + return err + } + page.al = 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 *ArtifactListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ArtifactListPage) NotDone() bool { + return !page.al.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ArtifactListPage) Response() ArtifactList { + return page.al +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ArtifactListPage) Values() []Artifact { + if page.al.IsEmpty() { + return nil + } + return *page.al.Value +} + +// Creates a new instance of the ArtifactListPage type. +func NewArtifactListPage(getNextPage func(context.Context, ArtifactList) (ArtifactList, error)) ArtifactListPage { + return ArtifactListPage{fn: getNextPage} +} + +// ArtifactParameterProperties properties of an artifact parameter. +type ArtifactParameterProperties struct { + // Name - The name of the artifact parameter. + Name *string `json:"name,omitempty"` + // Value - The value of the artifact parameter. + Value *string `json:"value,omitempty"` +} + +// ArtifactParameterPropertiesFragment properties of an artifact parameter. +type ArtifactParameterPropertiesFragment struct { + // Name - The name of the artifact parameter. + Name *string `json:"name,omitempty"` + // Value - The value of the artifact parameter. + Value *string `json:"value,omitempty"` +} + +// ArtifactProperties properties of an artifact. +type ArtifactProperties struct { + // Title - READ-ONLY; The artifact's title. + Title *string `json:"title,omitempty"` + // Description - READ-ONLY; The artifact's description. + Description *string `json:"description,omitempty"` + // Publisher - READ-ONLY; The artifact's publisher. + Publisher *string `json:"publisher,omitempty"` + // FilePath - READ-ONLY; The file path to the artifact. + FilePath *string `json:"filePath,omitempty"` + // Icon - READ-ONLY; The URI to the artifact icon. + Icon *string `json:"icon,omitempty"` + // TargetOsType - READ-ONLY; The artifact's target OS. + TargetOsType *string `json:"targetOsType,omitempty"` + // Parameters - READ-ONLY; The artifact's parameters. + Parameters interface{} `json:"parameters,omitempty"` + // CreatedDate - READ-ONLY; The artifact's creation date. + CreatedDate *date.Time `json:"createdDate,omitempty"` +} + +// ArtifactSource properties of an artifact source. +type ArtifactSource struct { + autorest.Response `json:"-"` + // ArtifactSourceProperties - The properties of the resource. + *ArtifactSourceProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ArtifactSource. +func (as ArtifactSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if as.ArtifactSourceProperties != nil { + objectMap["properties"] = as.ArtifactSourceProperties + } + if as.Location != nil { + objectMap["location"] = as.Location + } + if as.Tags != nil { + objectMap["tags"] = as.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ArtifactSource struct. +func (as *ArtifactSource) 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 artifactSourceProperties ArtifactSourceProperties + err = json.Unmarshal(*v, &artifactSourceProperties) + if err != nil { + return err + } + as.ArtifactSourceProperties = &artifactSourceProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + as.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + as.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + as.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + as.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + as.Tags = tags + } + } + } + + return nil +} + +// ArtifactSourceFragment properties of an artifact source. +type ArtifactSourceFragment struct { + // ArtifactSourcePropertiesFragment - The properties of the resource. + *ArtifactSourcePropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ArtifactSourceFragment. +func (asf ArtifactSourceFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if asf.ArtifactSourcePropertiesFragment != nil { + objectMap["properties"] = asf.ArtifactSourcePropertiesFragment + } + if asf.Tags != nil { + objectMap["tags"] = asf.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ArtifactSourceFragment struct. +func (asf *ArtifactSourceFragment) 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 artifactSourcePropertiesFragment ArtifactSourcePropertiesFragment + err = json.Unmarshal(*v, &artifactSourcePropertiesFragment) + if err != nil { + return err + } + asf.ArtifactSourcePropertiesFragment = &artifactSourcePropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + asf.Tags = tags + } + } + } + + return nil +} + +// ArtifactSourceList the response of a list operation. +type ArtifactSourceList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]ArtifactSource `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ArtifactSourceListIterator provides access to a complete listing of ArtifactSource values. +type ArtifactSourceListIterator struct { + i int + page ArtifactSourceListPage +} + +// 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 *ArtifactSourceListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactSourceListIterator.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 *ArtifactSourceListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ArtifactSourceListIterator) 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 ArtifactSourceListIterator) Response() ArtifactSourceList { + 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 ArtifactSourceListIterator) Value() ArtifactSource { + if !iter.page.NotDone() { + return ArtifactSource{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ArtifactSourceListIterator type. +func NewArtifactSourceListIterator(page ArtifactSourceListPage) ArtifactSourceListIterator { + return ArtifactSourceListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (asl ArtifactSourceList) IsEmpty() bool { + return asl.Value == nil || len(*asl.Value) == 0 +} + +// artifactSourceListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (asl ArtifactSourceList) artifactSourceListPreparer(ctx context.Context) (*http.Request, error) { + if asl.NextLink == nil || len(to.String(asl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(asl.NextLink))) +} + +// ArtifactSourceListPage contains a page of ArtifactSource values. +type ArtifactSourceListPage struct { + fn func(context.Context, ArtifactSourceList) (ArtifactSourceList, error) + asl ArtifactSourceList +} + +// 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 *ArtifactSourceListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ArtifactSourceListPage.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.asl) + if err != nil { + return err + } + page.asl = 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 *ArtifactSourceListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ArtifactSourceListPage) NotDone() bool { + return !page.asl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ArtifactSourceListPage) Response() ArtifactSourceList { + return page.asl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ArtifactSourceListPage) Values() []ArtifactSource { + if page.asl.IsEmpty() { + return nil + } + return *page.asl.Value +} + +// Creates a new instance of the ArtifactSourceListPage type. +func NewArtifactSourceListPage(getNextPage func(context.Context, ArtifactSourceList) (ArtifactSourceList, error)) ArtifactSourceListPage { + return ArtifactSourceListPage{fn: getNextPage} +} + +// ArtifactSourceProperties properties of an artifact source. +type ArtifactSourceProperties struct { + // DisplayName - The artifact source's display name. + DisplayName *string `json:"displayName,omitempty"` + // URI - The artifact source's URI. + URI *string `json:"uri,omitempty"` + // SourceType - The artifact source's type. Possible values include: 'VsoGit', 'GitHub' + SourceType SourceControlType `json:"sourceType,omitempty"` + // FolderPath - The folder containing artifacts. + FolderPath *string `json:"folderPath,omitempty"` + // ArmTemplateFolderPath - The folder containing Azure Resource Manager templates. + ArmTemplateFolderPath *string `json:"armTemplateFolderPath,omitempty"` + // BranchRef - The artifact source's branch reference. + BranchRef *string `json:"branchRef,omitempty"` + // SecurityToken - The security token to authenticate to the artifact source. + SecurityToken *string `json:"securityToken,omitempty"` + // Status - Indicates if the artifact source is enabled (values: Enabled, Disabled). Possible values include: 'EnableStatusEnabled', 'EnableStatusDisabled' + Status EnableStatus `json:"status,omitempty"` + // CreatedDate - READ-ONLY; The artifact source's creation date. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// ArtifactSourcePropertiesFragment properties of an artifact source. +type ArtifactSourcePropertiesFragment struct { + // DisplayName - The artifact source's display name. + DisplayName *string `json:"displayName,omitempty"` + // URI - The artifact source's URI. + URI *string `json:"uri,omitempty"` + // SourceType - The artifact source's type. Possible values include: 'VsoGit', 'GitHub' + SourceType SourceControlType `json:"sourceType,omitempty"` + // FolderPath - The folder containing artifacts. + FolderPath *string `json:"folderPath,omitempty"` + // ArmTemplateFolderPath - The folder containing Azure Resource Manager templates. + ArmTemplateFolderPath *string `json:"armTemplateFolderPath,omitempty"` + // BranchRef - The artifact source's branch reference. + BranchRef *string `json:"branchRef,omitempty"` + // SecurityToken - The security token to authenticate to the artifact source. + SecurityToken *string `json:"securityToken,omitempty"` + // Status - Indicates if the artifact source is enabled (values: Enabled, Disabled). Possible values include: 'EnableStatusEnabled', 'EnableStatusDisabled' + Status EnableStatus `json:"status,omitempty"` +} + +// AttachDiskProperties properties of the disk to attach. +type AttachDiskProperties struct { + // LeasedByLabVMID - The resource ID of the Lab virtual machine to which the disk is attached. + LeasedByLabVMID *string `json:"leasedByLabVmId,omitempty"` +} + +// AttachNewDataDiskOptions properties to attach new disk to the Virtual Machine. +type AttachNewDataDiskOptions struct { + // DiskSizeGiB - Size of the disk to be attached in Gibibytes. + DiskSizeGiB *int32 `json:"diskSizeGiB,omitempty"` + // DiskName - The name of the disk to be attached. + DiskName *string `json:"diskName,omitempty"` + // DiskType - The storage type for the disk (i.e. Standard, Premium). Possible values include: 'Standard', 'Premium' + DiskType StorageType `json:"diskType,omitempty"` +} + +// AttachNewDataDiskOptionsFragment properties to attach new disk to the Virtual Machine. +type AttachNewDataDiskOptionsFragment struct { + // DiskSizeGiB - Size of the disk to be attached in Gibibytes. + DiskSizeGiB *int32 `json:"diskSizeGiB,omitempty"` + // DiskName - The name of the disk to be attached. + DiskName *string `json:"diskName,omitempty"` + // DiskType - The storage type for the disk (i.e. Standard, Premium). Possible values include: 'Standard', 'Premium' + DiskType StorageType `json:"diskType,omitempty"` +} + +// BulkCreationParameters parameters for creating multiple virtual machines as a single action. +type BulkCreationParameters struct { + // InstanceCount - The number of virtual machine instances to create. + InstanceCount *int32 `json:"instanceCount,omitempty"` +} + +// BulkCreationParametersFragment parameters for creating multiple virtual machines as a single action. +type BulkCreationParametersFragment struct { + // InstanceCount - The number of virtual machine instances to create. + InstanceCount *int32 `json:"instanceCount,omitempty"` +} + +// CloudError error from a REST request. +type CloudError struct { + // Error - The cloud error that occurred + Error *CloudErrorBody `json:"error,omitempty"` +} + +// CloudErrorBody body of an error from a REST request. +type CloudErrorBody struct { + // Code - The error code. + Code *string `json:"code,omitempty"` + // Message - The error message. + Message *string `json:"message,omitempty"` + // Target - The error target. + Target *string `json:"target,omitempty"` + // Details - Inner errors. + Details *[]CloudErrorBody `json:"details,omitempty"` +} + +// ComputeDataDisk a data disks attached to a virtual machine. +type ComputeDataDisk struct { + // Name - Gets data disk name. + Name *string `json:"name,omitempty"` + // DiskURI - When backed by a blob, the URI of underlying blob. + DiskURI *string `json:"diskUri,omitempty"` + // ManagedDiskID - When backed by managed disk, this is the ID of the compute disk resource. + ManagedDiskID *string `json:"managedDiskId,omitempty"` + // DiskSizeGiB - Gets data disk size in GiB. + DiskSizeGiB *int32 `json:"diskSizeGiB,omitempty"` +} + +// ComputeDataDiskFragment a data disks attached to a virtual machine. +type ComputeDataDiskFragment struct { + // Name - Gets data disk name. + Name *string `json:"name,omitempty"` + // DiskURI - When backed by a blob, the URI of underlying blob. + DiskURI *string `json:"diskUri,omitempty"` + // ManagedDiskID - When backed by managed disk, this is the ID of the compute disk resource. + ManagedDiskID *string `json:"managedDiskId,omitempty"` + // DiskSizeGiB - Gets data disk size in GiB. + DiskSizeGiB *int32 `json:"diskSizeGiB,omitempty"` +} + +// ComputeVMInstanceViewStatus status information about a virtual machine. +type ComputeVMInstanceViewStatus struct { + // Code - Gets the status Code. + Code *string `json:"code,omitempty"` + // DisplayStatus - Gets the short localizable label for the status. + DisplayStatus *string `json:"displayStatus,omitempty"` + // Message - Gets the message associated with the status. + Message *string `json:"message,omitempty"` +} + +// ComputeVMInstanceViewStatusFragment status information about a virtual machine. +type ComputeVMInstanceViewStatusFragment struct { + // Code - Gets the status Code. + Code *string `json:"code,omitempty"` + // DisplayStatus - Gets the short localizable label for the status. + DisplayStatus *string `json:"displayStatus,omitempty"` + // Message - Gets the message associated with the status. + Message *string `json:"message,omitempty"` +} + +// ComputeVMProperties properties of a virtual machine returned by the Microsoft.Compute API. +type ComputeVMProperties struct { + // Statuses - Gets the statuses of the virtual machine. + Statuses *[]ComputeVMInstanceViewStatus `json:"statuses,omitempty"` + // OsType - Gets the OS type of the virtual machine. + OsType *string `json:"osType,omitempty"` + // VMSize - Gets the size of the virtual machine. + VMSize *string `json:"vmSize,omitempty"` + // NetworkInterfaceID - Gets the network interface ID of the virtual machine. + NetworkInterfaceID *string `json:"networkInterfaceId,omitempty"` + // OsDiskID - Gets OS disk blob uri for the virtual machine. + OsDiskID *string `json:"osDiskId,omitempty"` + // DataDiskIds - Gets data disks blob uri for the virtual machine. + DataDiskIds *[]string `json:"dataDiskIds,omitempty"` + // DataDisks - Gets all data disks attached to the virtual machine. + DataDisks *[]ComputeDataDisk `json:"dataDisks,omitempty"` +} + +// ComputeVMPropertiesFragment properties of a virtual machine returned by the Microsoft.Compute API. +type ComputeVMPropertiesFragment struct { + // Statuses - Gets the statuses of the virtual machine. + Statuses *[]ComputeVMInstanceViewStatusFragment `json:"statuses,omitempty"` + // OsType - Gets the OS type of the virtual machine. + OsType *string `json:"osType,omitempty"` + // VMSize - Gets the size of the virtual machine. + VMSize *string `json:"vmSize,omitempty"` + // NetworkInterfaceID - Gets the network interface ID of the virtual machine. + NetworkInterfaceID *string `json:"networkInterfaceId,omitempty"` + // OsDiskID - Gets OS disk blob uri for the virtual machine. + OsDiskID *string `json:"osDiskId,omitempty"` + // DataDiskIds - Gets data disks blob uri for the virtual machine. + DataDiskIds *[]string `json:"dataDiskIds,omitempty"` + // DataDisks - Gets all data disks attached to the virtual machine. + DataDisks *[]ComputeDataDiskFragment `json:"dataDisks,omitempty"` +} + +// CostThresholdProperties properties of a cost threshold item. +type CostThresholdProperties struct { + // ThresholdID - The ID of the cost threshold item. + ThresholdID *string `json:"thresholdId,omitempty"` + // PercentageThreshold - The value of the percentage cost threshold. + PercentageThreshold *PercentageCostThresholdProperties `json:"percentageThreshold,omitempty"` + // DisplayOnChart - Indicates whether this threshold will be displayed on cost charts. Possible values include: 'Enabled', 'Disabled' + DisplayOnChart CostThresholdStatus `json:"displayOnChart,omitempty"` + // SendNotificationWhenExceeded - Indicates whether notifications will be sent when this threshold is exceeded. Possible values include: 'Enabled', 'Disabled' + SendNotificationWhenExceeded CostThresholdStatus `json:"sendNotificationWhenExceeded,omitempty"` + // NotificationSent - Indicates the datetime when notifications were last sent for this threshold. + NotificationSent *string `json:"notificationSent,omitempty"` +} + +// CustomImage a custom image. +type CustomImage struct { + autorest.Response `json:"-"` + // CustomImageProperties - The properties of the resource. + *CustomImageProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for CustomImage. +func (ci CustomImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ci.CustomImageProperties != nil { + objectMap["properties"] = ci.CustomImageProperties + } + if ci.Location != nil { + objectMap["location"] = ci.Location + } + if ci.Tags != nil { + objectMap["tags"] = ci.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for CustomImage struct. +func (ci *CustomImage) 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 customImageProperties CustomImageProperties + err = json.Unmarshal(*v, &customImageProperties) + if err != nil { + return err + } + ci.CustomImageProperties = &customImageProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + ci.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + ci.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + ci.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + ci.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + ci.Tags = tags + } + } + } + + return nil +} + +// CustomImageFragment a custom image. +type CustomImageFragment struct { + // CustomImagePropertiesFragment - The properties of the resource. + *CustomImagePropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for CustomImageFragment. +func (cif CustomImageFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if cif.CustomImagePropertiesFragment != nil { + objectMap["properties"] = cif.CustomImagePropertiesFragment + } + if cif.Tags != nil { + objectMap["tags"] = cif.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for CustomImageFragment struct. +func (cif *CustomImageFragment) 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 customImagePropertiesFragment CustomImagePropertiesFragment + err = json.Unmarshal(*v, &customImagePropertiesFragment) + if err != nil { + return err + } + cif.CustomImagePropertiesFragment = &customImagePropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + cif.Tags = tags + } + } + } + + return nil +} + +// CustomImageList the response of a list operation. +type CustomImageList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]CustomImage `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// CustomImageListIterator provides access to a complete listing of CustomImage values. +type CustomImageListIterator struct { + i int + page CustomImageListPage +} + +// 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 *CustomImageListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomImageListIterator.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 *CustomImageListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter CustomImageListIterator) 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 CustomImageListIterator) Response() CustomImageList { + 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 CustomImageListIterator) Value() CustomImage { + if !iter.page.NotDone() { + return CustomImage{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the CustomImageListIterator type. +func NewCustomImageListIterator(page CustomImageListPage) CustomImageListIterator { + return CustomImageListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (cil CustomImageList) IsEmpty() bool { + return cil.Value == nil || len(*cil.Value) == 0 +} + +// customImageListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (cil CustomImageList) customImageListPreparer(ctx context.Context) (*http.Request, error) { + if cil.NextLink == nil || len(to.String(cil.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(cil.NextLink))) +} + +// CustomImageListPage contains a page of CustomImage values. +type CustomImageListPage struct { + fn func(context.Context, CustomImageList) (CustomImageList, error) + cil CustomImageList +} + +// 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 *CustomImageListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/CustomImageListPage.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.cil) + if err != nil { + return err + } + page.cil = 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 *CustomImageListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page CustomImageListPage) NotDone() bool { + return !page.cil.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page CustomImageListPage) Response() CustomImageList { + return page.cil +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page CustomImageListPage) Values() []CustomImage { + if page.cil.IsEmpty() { + return nil + } + return *page.cil.Value +} + +// Creates a new instance of the CustomImageListPage type. +func NewCustomImageListPage(getNextPage func(context.Context, CustomImageList) (CustomImageList, error)) CustomImageListPage { + return CustomImageListPage{fn: getNextPage} +} + +// CustomImageProperties properties of a custom image. +type CustomImageProperties struct { + // VM - The virtual machine from which the image is to be created. + VM *CustomImagePropertiesFromVM `json:"vm,omitempty"` + // Vhd - The VHD from which the image is to be created. + Vhd *CustomImagePropertiesCustom `json:"vhd,omitempty"` + // Description - The description of the custom image. + Description *string `json:"description,omitempty"` + // Author - The author of the custom image. + Author *string `json:"author,omitempty"` + // CreationDate - READ-ONLY; The creation date of the custom image. + CreationDate *date.Time `json:"creationDate,omitempty"` + // ManagedImageID - The Managed Image Id backing the custom image. + ManagedImageID *string `json:"managedImageId,omitempty"` + // ManagedSnapshotID - The Managed Snapshot Id backing the custom image. + ManagedSnapshotID *string `json:"managedSnapshotId,omitempty"` + // DataDiskStorageInfo - Storage information about the data disks present in the custom image + DataDiskStorageInfo *[]DataDiskStorageTypeInfo `json:"dataDiskStorageInfo,omitempty"` + // CustomImagePlan - Storage information about the plan related to this custom image + CustomImagePlan *CustomImagePropertiesFromPlan `json:"customImagePlan,omitempty"` + // IsPlanAuthorized - Whether or not the custom images underlying offer/plan has been enabled for programmatic deployment + IsPlanAuthorized *bool `json:"isPlanAuthorized,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// CustomImagePropertiesCustom properties for creating a custom image from a VHD. +type CustomImagePropertiesCustom struct { + // ImageName - The image name. + ImageName *string `json:"imageName,omitempty"` + // SysPrep - Indicates whether sysprep has been run on the VHD. + SysPrep *bool `json:"sysPrep,omitempty"` + // OsType - The OS type of the custom image (i.e. Windows, Linux). Possible values include: 'Windows', 'Linux', 'None' + OsType CustomImageOsType `json:"osType,omitempty"` +} + +// CustomImagePropertiesCustomFragment properties for creating a custom image from a VHD. +type CustomImagePropertiesCustomFragment struct { + // ImageName - The image name. + ImageName *string `json:"imageName,omitempty"` + // SysPrep - Indicates whether sysprep has been run on the VHD. + SysPrep *bool `json:"sysPrep,omitempty"` + // OsType - The OS type of the custom image (i.e. Windows, Linux). Possible values include: 'Windows', 'Linux', 'None' + OsType CustomImageOsType `json:"osType,omitempty"` +} + +// CustomImagePropertiesFragment properties of a custom image. +type CustomImagePropertiesFragment struct { + // VM - The virtual machine from which the image is to be created. + VM *CustomImagePropertiesFromVMFragment `json:"vm,omitempty"` + // Vhd - The VHD from which the image is to be created. + Vhd *CustomImagePropertiesCustomFragment `json:"vhd,omitempty"` + // Description - The description of the custom image. + Description *string `json:"description,omitempty"` + // Author - The author of the custom image. + Author *string `json:"author,omitempty"` + // ManagedImageID - The Managed Image Id backing the custom image. + ManagedImageID *string `json:"managedImageId,omitempty"` + // ManagedSnapshotID - The Managed Snapshot Id backing the custom image. + ManagedSnapshotID *string `json:"managedSnapshotId,omitempty"` + // DataDiskStorageInfo - Storage information about the data disks present in the custom image + DataDiskStorageInfo *[]DataDiskStorageTypeInfoFragment `json:"dataDiskStorageInfo,omitempty"` + // CustomImagePlan - Storage information about the plan related to this custom image + CustomImagePlan *CustomImagePropertiesFromPlanFragment `json:"customImagePlan,omitempty"` + // IsPlanAuthorized - Whether or not the custom images underlying offer/plan has been enabled for programmatic deployment + IsPlanAuthorized *bool `json:"isPlanAuthorized,omitempty"` +} + +// CustomImagePropertiesFromPlan properties for plan on a custom image. +type CustomImagePropertiesFromPlan struct { + // ID - The id of the plan, equivalent to name of the plan + ID *string `json:"id,omitempty"` + // Publisher - The publisher for the plan from the marketplace image the custom image is derived from + Publisher *string `json:"publisher,omitempty"` + // Offer - The offer for the plan from the marketplace image the custom image is derived from + Offer *string `json:"offer,omitempty"` +} + +// CustomImagePropertiesFromPlanFragment properties for plan on a custom image. +type CustomImagePropertiesFromPlanFragment struct { + // ID - The id of the plan, equivalent to name of the plan + ID *string `json:"id,omitempty"` + // Publisher - The publisher for the plan from the marketplace image the custom image is derived from + Publisher *string `json:"publisher,omitempty"` + // Offer - The offer for the plan from the marketplace image the custom image is derived from + Offer *string `json:"offer,omitempty"` +} + +// CustomImagePropertiesFromVM properties for creating a custom image from a virtual machine. +type CustomImagePropertiesFromVM struct { + // SourceVMID - The source vm identifier. + SourceVMID *string `json:"sourceVmId,omitempty"` + // WindowsOsInfo - The Windows OS information of the VM. + WindowsOsInfo *WindowsOsInfo `json:"windowsOsInfo,omitempty"` + // LinuxOsInfo - The Linux OS information of the VM. + LinuxOsInfo *LinuxOsInfo `json:"linuxOsInfo,omitempty"` +} + +// CustomImagePropertiesFromVMFragment properties for creating a custom image from a virtual machine. +type CustomImagePropertiesFromVMFragment struct { + // SourceVMID - The source vm identifier. + SourceVMID *string `json:"sourceVmId,omitempty"` + // WindowsOsInfo - The Windows OS information of the VM. + WindowsOsInfo *WindowsOsInfoFragment `json:"windowsOsInfo,omitempty"` + // LinuxOsInfo - The Linux OS information of the VM. + LinuxOsInfo *LinuxOsInfoFragment `json:"linuxOsInfo,omitempty"` +} + +// CustomImagesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type CustomImagesCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *CustomImagesCreateOrUpdateFuture) Result(client CustomImagesClient) (ci CustomImage, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.CustomImagesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if ci.Response.Response, err = future.GetResult(sender); err == nil && ci.Response.Response.StatusCode != http.StatusNoContent { + ci, err = client.CreateOrUpdateResponder(ci.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesCreateOrUpdateFuture", "Result", ci.Response.Response, "Failure responding to request") + } + } + return +} + +// CustomImagesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type CustomImagesDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *CustomImagesDeleteFuture) Result(client CustomImagesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.CustomImagesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.CustomImagesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// DataDiskProperties request body for adding a new or existing data disk to a virtual machine. +type DataDiskProperties struct { + // AttachNewDataDiskOptions - Specifies options to attach a new disk to the virtual machine. + AttachNewDataDiskOptions *AttachNewDataDiskOptions `json:"attachNewDataDiskOptions,omitempty"` + // ExistingLabDiskID - Specifies the existing lab disk id to attach to virtual machine. + ExistingLabDiskID *string `json:"existingLabDiskId,omitempty"` + // HostCaching - Caching option for a data disk (i.e. None, ReadOnly, ReadWrite). Possible values include: 'HostCachingOptionsNone', 'HostCachingOptionsReadOnly', 'HostCachingOptionsReadWrite' + HostCaching HostCachingOptions `json:"hostCaching,omitempty"` +} + +// DataDiskPropertiesFragment request body for adding a new or existing data disk to a virtual machine. +type DataDiskPropertiesFragment struct { + // AttachNewDataDiskOptions - Specifies options to attach a new disk to the virtual machine. + AttachNewDataDiskOptions *AttachNewDataDiskOptionsFragment `json:"attachNewDataDiskOptions,omitempty"` + // ExistingLabDiskID - Specifies the existing lab disk id to attach to virtual machine. + ExistingLabDiskID *string `json:"existingLabDiskId,omitempty"` + // HostCaching - Caching option for a data disk (i.e. None, ReadOnly, ReadWrite). Possible values include: 'HostCachingOptionsNone', 'HostCachingOptionsReadOnly', 'HostCachingOptionsReadWrite' + HostCaching HostCachingOptions `json:"hostCaching,omitempty"` +} + +// DataDiskStorageTypeInfo storage information about the data disks present in the custom image +type DataDiskStorageTypeInfo struct { + // Lun - Disk Lun + Lun *string `json:"lun,omitempty"` + // StorageType - Disk Storage Type. Possible values include: 'Standard', 'Premium' + StorageType StorageType `json:"storageType,omitempty"` +} + +// DataDiskStorageTypeInfoFragment storage information about the data disks present in the custom image +type DataDiskStorageTypeInfoFragment struct { + // Lun - Disk Lun + Lun *string `json:"lun,omitempty"` + // StorageType - Disk Storage Type. Possible values include: 'Standard', 'Premium' + StorageType StorageType `json:"storageType,omitempty"` +} + +// DayDetails properties of a daily schedule. +type DayDetails struct { + // Time - The time of day the schedule will occur. + Time *string `json:"time,omitempty"` +} + +// DayDetailsFragment properties of a daily schedule. +type DayDetailsFragment struct { + // Time - The time of day the schedule will occur. + Time *string `json:"time,omitempty"` +} + +// DetachDataDiskProperties request body for detaching data disk from a virtual machine. +type DetachDataDiskProperties struct { + // ExistingLabDiskID - Specifies the disk resource ID to detach from virtual machine. + ExistingLabDiskID *string `json:"existingLabDiskId,omitempty"` +} + +// DetachDiskProperties properties of the disk to detach. +type DetachDiskProperties struct { + // LeasedByLabVMID - The resource ID of the Lab VM to which the disk is attached. + LeasedByLabVMID *string `json:"leasedByLabVmId,omitempty"` +} + +// Disk a Disk. +type Disk struct { + autorest.Response `json:"-"` + // DiskProperties - The properties of the resource. + *DiskProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Disk. +func (d Disk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if d.DiskProperties != nil { + objectMap["properties"] = d.DiskProperties + } + if d.Location != nil { + objectMap["location"] = d.Location + } + if d.Tags != nil { + objectMap["tags"] = d.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Disk struct. +func (d *Disk) 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 diskProperties DiskProperties + err = json.Unmarshal(*v, &diskProperties) + if err != nil { + return err + } + d.DiskProperties = &diskProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + d.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + d.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + d.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + d.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + d.Tags = tags + } + } + } + + return nil +} + +// DiskFragment a Disk. +type DiskFragment struct { + // DiskPropertiesFragment - The properties of the resource. + *DiskPropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for DiskFragment. +func (df DiskFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if df.DiskPropertiesFragment != nil { + objectMap["properties"] = df.DiskPropertiesFragment + } + if df.Tags != nil { + objectMap["tags"] = df.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for DiskFragment struct. +func (df *DiskFragment) 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 diskPropertiesFragment DiskPropertiesFragment + err = json.Unmarshal(*v, &diskPropertiesFragment) + if err != nil { + return err + } + df.DiskPropertiesFragment = &diskPropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + df.Tags = tags + } + } + } + + return nil +} + +// DiskList the response of a list operation. +type DiskList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]Disk `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// DiskListIterator provides access to a complete listing of Disk values. +type DiskListIterator struct { + i int + page DiskListPage +} + +// 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 *DiskListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DiskListIterator.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 *DiskListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter DiskListIterator) 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 DiskListIterator) Response() DiskList { + 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 DiskListIterator) Value() Disk { + if !iter.page.NotDone() { + return Disk{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the DiskListIterator type. +func NewDiskListIterator(page DiskListPage) DiskListIterator { + return DiskListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (dl DiskList) IsEmpty() bool { + return dl.Value == nil || len(*dl.Value) == 0 +} + +// diskListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (dl DiskList) diskListPreparer(ctx context.Context) (*http.Request, error) { + if dl.NextLink == nil || len(to.String(dl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(dl.NextLink))) +} + +// DiskListPage contains a page of Disk values. +type DiskListPage struct { + fn func(context.Context, DiskList) (DiskList, error) + dl DiskList +} + +// 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 *DiskListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/DiskListPage.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.dl) + if err != nil { + return err + } + page.dl = 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 *DiskListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page DiskListPage) NotDone() bool { + return !page.dl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page DiskListPage) Response() DiskList { + return page.dl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page DiskListPage) Values() []Disk { + if page.dl.IsEmpty() { + return nil + } + return *page.dl.Value +} + +// Creates a new instance of the DiskListPage type. +func NewDiskListPage(getNextPage func(context.Context, DiskList) (DiskList, error)) DiskListPage { + return DiskListPage{fn: getNextPage} +} + +// DiskProperties properties of a disk. +type DiskProperties struct { + // DiskType - The storage type for the disk (i.e. Standard, Premium). Possible values include: 'Standard', 'Premium' + DiskType StorageType `json:"diskType,omitempty"` + // DiskSizeGiB - The size of the disk in Gibibytes. + DiskSizeGiB *int32 `json:"diskSizeGiB,omitempty"` + // LeasedByLabVMID - The resource ID of the VM to which this disk is leased. + LeasedByLabVMID *string `json:"leasedByLabVmId,omitempty"` + // DiskBlobName - When backed by a blob, the name of the VHD blob without extension. + DiskBlobName *string `json:"diskBlobName,omitempty"` + // DiskURI - When backed by a blob, the URI of underlying blob. + DiskURI *string `json:"diskUri,omitempty"` + // CreatedDate - READ-ONLY; The creation date of the disk. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // HostCaching - The host caching policy of the disk (i.e. None, ReadOnly, ReadWrite). + HostCaching *string `json:"hostCaching,omitempty"` + // ManagedDiskID - When backed by managed disk, this is the ID of the compute disk resource. + ManagedDiskID *string `json:"managedDiskId,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// DiskPropertiesFragment properties of a disk. +type DiskPropertiesFragment struct { + // DiskType - The storage type for the disk (i.e. Standard, Premium). Possible values include: 'Standard', 'Premium' + DiskType StorageType `json:"diskType,omitempty"` + // DiskSizeGiB - The size of the disk in Gibibytes. + DiskSizeGiB *int32 `json:"diskSizeGiB,omitempty"` + // LeasedByLabVMID - The resource ID of the VM to which this disk is leased. + LeasedByLabVMID *string `json:"leasedByLabVmId,omitempty"` + // DiskBlobName - When backed by a blob, the name of the VHD blob without extension. + DiskBlobName *string `json:"diskBlobName,omitempty"` + // DiskURI - When backed by a blob, the URI of underlying blob. + DiskURI *string `json:"diskUri,omitempty"` + // HostCaching - The host caching policy of the disk (i.e. None, ReadOnly, ReadWrite). + HostCaching *string `json:"hostCaching,omitempty"` + // ManagedDiskID - When backed by managed disk, this is the ID of the compute disk resource. + ManagedDiskID *string `json:"managedDiskId,omitempty"` +} + +// DisksAttachFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type DisksAttachFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DisksAttachFuture) Result(client DisksClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksAttachFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.DisksAttachFuture") + return + } + ar.Response = future.Response() + return +} + +// DisksCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type DisksCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DisksCreateOrUpdateFuture) Result(client DisksClient) (d Disk, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.DisksCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { + d, err = client.CreateOrUpdateResponder(d.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksCreateOrUpdateFuture", "Result", d.Response.Response, "Failure responding to request") + } + } + return +} + +// DisksDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type DisksDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DisksDeleteFuture) Result(client DisksClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.DisksDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// DisksDetachFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type DisksDetachFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *DisksDetachFuture) Result(client DisksClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.DisksDetachFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.DisksDetachFuture") + return + } + ar.Response = future.Response() + return +} + +// Environment an environment, which is essentially an ARM template deployment. +type Environment struct { + autorest.Response `json:"-"` + // EnvironmentProperties - The properties of the resource. + *EnvironmentProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Environment. +func (e Environment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if e.EnvironmentProperties != nil { + objectMap["properties"] = e.EnvironmentProperties + } + if e.Location != nil { + objectMap["location"] = e.Location + } + if e.Tags != nil { + objectMap["tags"] = e.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Environment struct. +func (e *Environment) 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 environmentProperties EnvironmentProperties + err = json.Unmarshal(*v, &environmentProperties) + if err != nil { + return err + } + e.EnvironmentProperties = &environmentProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + e.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + e.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + e.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + e.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + e.Tags = tags + } + } + } + + return nil +} + +// EnvironmentDeploymentProperties properties of an environment deployment. +type EnvironmentDeploymentProperties struct { + // ArmTemplateID - The Azure Resource Manager template's identifier. + ArmTemplateID *string `json:"armTemplateId,omitempty"` + // Parameters - The parameters of the Azure Resource Manager template. + Parameters *[]ArmTemplateParameterProperties `json:"parameters,omitempty"` +} + +// EnvironmentDeploymentPropertiesFragment properties of an environment deployment. +type EnvironmentDeploymentPropertiesFragment struct { + // ArmTemplateID - The Azure Resource Manager template's identifier. + ArmTemplateID *string `json:"armTemplateId,omitempty"` + // Parameters - The parameters of the Azure Resource Manager template. + Parameters *[]ArmTemplateParameterPropertiesFragment `json:"parameters,omitempty"` +} + +// EnvironmentFragment an environment, which is essentially an ARM template deployment. +type EnvironmentFragment struct { + // EnvironmentPropertiesFragment - The properties of the resource. + *EnvironmentPropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for EnvironmentFragment. +func (ef EnvironmentFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ef.EnvironmentPropertiesFragment != nil { + objectMap["properties"] = ef.EnvironmentPropertiesFragment + } + if ef.Tags != nil { + objectMap["tags"] = ef.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for EnvironmentFragment struct. +func (ef *EnvironmentFragment) 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 environmentPropertiesFragment EnvironmentPropertiesFragment + err = json.Unmarshal(*v, &environmentPropertiesFragment) + if err != nil { + return err + } + ef.EnvironmentPropertiesFragment = &environmentPropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + ef.Tags = tags + } + } + } + + return nil +} + +// EnvironmentList the response of a list operation. +type EnvironmentList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]Environment `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// EnvironmentListIterator provides access to a complete listing of Environment values. +type EnvironmentListIterator struct { + i int + page EnvironmentListPage +} + +// 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 *EnvironmentListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EnvironmentListIterator.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 *EnvironmentListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter EnvironmentListIterator) 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 EnvironmentListIterator) Response() EnvironmentList { + 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 EnvironmentListIterator) Value() Environment { + if !iter.page.NotDone() { + return Environment{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the EnvironmentListIterator type. +func NewEnvironmentListIterator(page EnvironmentListPage) EnvironmentListIterator { + return EnvironmentListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (el EnvironmentList) IsEmpty() bool { + return el.Value == nil || len(*el.Value) == 0 +} + +// environmentListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (el EnvironmentList) environmentListPreparer(ctx context.Context) (*http.Request, error) { + if el.NextLink == nil || len(to.String(el.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(el.NextLink))) +} + +// EnvironmentListPage contains a page of Environment values. +type EnvironmentListPage struct { + fn func(context.Context, EnvironmentList) (EnvironmentList, error) + el EnvironmentList +} + +// 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 *EnvironmentListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/EnvironmentListPage.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.el) + if err != nil { + return err + } + page.el = 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 *EnvironmentListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page EnvironmentListPage) NotDone() bool { + return !page.el.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page EnvironmentListPage) Response() EnvironmentList { + return page.el +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page EnvironmentListPage) Values() []Environment { + if page.el.IsEmpty() { + return nil + } + return *page.el.Value +} + +// Creates a new instance of the EnvironmentListPage type. +func NewEnvironmentListPage(getNextPage func(context.Context, EnvironmentList) (EnvironmentList, error)) EnvironmentListPage { + return EnvironmentListPage{fn: getNextPage} +} + +// EnvironmentProperties properties of an environment. +type EnvironmentProperties struct { + // DeploymentProperties - The deployment properties of the environment. + DeploymentProperties *EnvironmentDeploymentProperties `json:"deploymentProperties,omitempty"` + // ArmTemplateDisplayName - The display name of the Azure Resource Manager template that produced the environment. + ArmTemplateDisplayName *string `json:"armTemplateDisplayName,omitempty"` + // ResourceGroupID - READ-ONLY; The identifier of the resource group containing the environment's resources. + ResourceGroupID *string `json:"resourceGroupId,omitempty"` + // CreatedByUser - READ-ONLY; The creator of the environment. + CreatedByUser *string `json:"createdByUser,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// EnvironmentPropertiesFragment properties of an environment. +type EnvironmentPropertiesFragment struct { + // DeploymentProperties - The deployment properties of the environment. + DeploymentProperties *EnvironmentDeploymentPropertiesFragment `json:"deploymentProperties,omitempty"` + // ArmTemplateDisplayName - The display name of the Azure Resource Manager template that produced the environment. + ArmTemplateDisplayName *string `json:"armTemplateDisplayName,omitempty"` +} + +// EnvironmentsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type EnvironmentsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *EnvironmentsCreateOrUpdateFuture) Result(client EnvironmentsClient) (e Environment, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.EnvironmentsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if e.Response.Response, err = future.GetResult(sender); err == nil && e.Response.Response.StatusCode != http.StatusNoContent { + e, err = client.CreateOrUpdateResponder(e.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsCreateOrUpdateFuture", "Result", e.Response.Response, "Failure responding to request") + } + } + return +} + +// EnvironmentsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type EnvironmentsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *EnvironmentsDeleteFuture) Result(client EnvironmentsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.EnvironmentsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.EnvironmentsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// EvaluatePoliciesProperties properties for evaluating a policy set. +type EvaluatePoliciesProperties struct { + // FactName - The fact name. + FactName *string `json:"factName,omitempty"` + // FactData - The fact data. + FactData *string `json:"factData,omitempty"` + // ValueOffset - The value offset. + ValueOffset *string `json:"valueOffset,omitempty"` + // UserObjectID - The user for which policies will be evaluated + UserObjectID *string `json:"userObjectId,omitempty"` +} + +// EvaluatePoliciesRequest request body for evaluating a policy set. +type EvaluatePoliciesRequest struct { + // Policies - Policies to evaluate. + Policies *[]EvaluatePoliciesProperties `json:"policies,omitempty"` +} + +// EvaluatePoliciesResponse response body for evaluating a policy set. +type EvaluatePoliciesResponse struct { + autorest.Response `json:"-"` + // Results - Results of evaluating a policy set. + Results *[]PolicySetResult `json:"results,omitempty"` +} + +// Event an event to be notified for. +type Event struct { + // EventName - The event type for which this notification is enabled (i.e. AutoShutdown, Cost). Possible values include: 'AutoShutdown', 'Cost' + EventName NotificationChannelEventType `json:"eventName,omitempty"` +} + +// EventFragment an event to be notified for. +type EventFragment struct { + // EventName - The event type for which this notification is enabled (i.e. AutoShutdown, Cost). Possible values include: 'AutoShutdown', 'Cost' + EventName NotificationChannelEventType `json:"eventName,omitempty"` +} + +// ExportResourceUsageParameters the parameters of the export operation. +type ExportResourceUsageParameters struct { + // BlobStorageAbsoluteSasURI - The blob storage absolute sas uri with write permission to the container which the usage data needs to be uploaded to. + BlobStorageAbsoluteSasURI *string `json:"blobStorageAbsoluteSasUri,omitempty"` + // UsageStartDate - The start time of the usage. If not provided, usage will be reported since the beginning of data collection. + UsageStartDate *date.Time `json:"usageStartDate,omitempty"` +} + +// ExternalSubnet subnet information as returned by the Microsoft.Network API. +type ExternalSubnet struct { + // ID - Gets or sets the identifier. + ID *string `json:"id,omitempty"` + // Name - Gets or sets the name. + Name *string `json:"name,omitempty"` +} + +// ExternalSubnetFragment subnet information as returned by the Microsoft.Network API. +type ExternalSubnetFragment struct { + // ID - Gets or sets the identifier. + ID *string `json:"id,omitempty"` + // Name - Gets or sets the name. + Name *string `json:"name,omitempty"` +} + +// Formula a formula for creating a VM, specifying an image base and other parameters +type Formula struct { + autorest.Response `json:"-"` + // FormulaProperties - The properties of the resource. + *FormulaProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Formula. +func (f Formula) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if f.FormulaProperties != nil { + objectMap["properties"] = f.FormulaProperties + } + if f.Location != nil { + objectMap["location"] = f.Location + } + if f.Tags != nil { + objectMap["tags"] = f.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Formula struct. +func (f *Formula) 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 formulaProperties FormulaProperties + err = json.Unmarshal(*v, &formulaProperties) + if err != nil { + return err + } + f.FormulaProperties = &formulaProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + f.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + f.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + f.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + f.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + f.Tags = tags + } + } + } + + return nil +} + +// FormulaFragment a formula for creating a VM, specifying an image base and other parameters +type FormulaFragment struct { + // FormulaPropertiesFragment - The properties of the resource. + *FormulaPropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for FormulaFragment. +func (ff FormulaFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ff.FormulaPropertiesFragment != nil { + objectMap["properties"] = ff.FormulaPropertiesFragment + } + if ff.Tags != nil { + objectMap["tags"] = ff.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for FormulaFragment struct. +func (ff *FormulaFragment) 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 formulaPropertiesFragment FormulaPropertiesFragment + err = json.Unmarshal(*v, &formulaPropertiesFragment) + if err != nil { + return err + } + ff.FormulaPropertiesFragment = &formulaPropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + ff.Tags = tags + } + } + } + + return nil +} + +// FormulaList the response of a list operation. +type FormulaList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]Formula `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// FormulaListIterator provides access to a complete listing of Formula values. +type FormulaListIterator struct { + i int + page FormulaListPage +} + +// 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 *FormulaListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FormulaListIterator.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 *FormulaListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter FormulaListIterator) 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 FormulaListIterator) Response() FormulaList { + 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 FormulaListIterator) Value() Formula { + if !iter.page.NotDone() { + return Formula{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the FormulaListIterator type. +func NewFormulaListIterator(page FormulaListPage) FormulaListIterator { + return FormulaListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (fl FormulaList) IsEmpty() bool { + return fl.Value == nil || len(*fl.Value) == 0 +} + +// formulaListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (fl FormulaList) formulaListPreparer(ctx context.Context) (*http.Request, error) { + if fl.NextLink == nil || len(to.String(fl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(fl.NextLink))) +} + +// FormulaListPage contains a page of Formula values. +type FormulaListPage struct { + fn func(context.Context, FormulaList) (FormulaList, error) + fl FormulaList +} + +// 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 *FormulaListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/FormulaListPage.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.fl) + if err != nil { + return err + } + page.fl = 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 *FormulaListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page FormulaListPage) NotDone() bool { + return !page.fl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page FormulaListPage) Response() FormulaList { + return page.fl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page FormulaListPage) Values() []Formula { + if page.fl.IsEmpty() { + return nil + } + return *page.fl.Value +} + +// Creates a new instance of the FormulaListPage type. +func NewFormulaListPage(getNextPage func(context.Context, FormulaList) (FormulaList, error)) FormulaListPage { + return FormulaListPage{fn: getNextPage} +} + +// FormulaProperties properties of a formula. +type FormulaProperties struct { + // Description - The description of the formula. + Description *string `json:"description,omitempty"` + // Author - The author of the formula. + Author *string `json:"author,omitempty"` + // OsType - The OS type of the formula. + OsType *string `json:"osType,omitempty"` + // CreationDate - READ-ONLY; The creation date of the formula. + CreationDate *date.Time `json:"creationDate,omitempty"` + // FormulaContent - The content of the formula. + FormulaContent *LabVirtualMachineCreationParameter `json:"formulaContent,omitempty"` + // VM - Information about a VM from which a formula is to be created. + VM *FormulaPropertiesFromVM `json:"vm,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// FormulaPropertiesFragment properties of a formula. +type FormulaPropertiesFragment struct { + // Description - The description of the formula. + Description *string `json:"description,omitempty"` + // Author - The author of the formula. + Author *string `json:"author,omitempty"` + // OsType - The OS type of the formula. + OsType *string `json:"osType,omitempty"` + // FormulaContent - The content of the formula. + FormulaContent *LabVirtualMachineCreationParameterFragment `json:"formulaContent,omitempty"` + // VM - Information about a VM from which a formula is to be created. + VM *FormulaPropertiesFromVMFragment `json:"vm,omitempty"` +} + +// FormulaPropertiesFromVM information about a VM from which a formula is to be created. +type FormulaPropertiesFromVM struct { + // LabVMID - The identifier of the VM from which a formula is to be created. + LabVMID *string `json:"labVmId,omitempty"` +} + +// FormulaPropertiesFromVMFragment information about a VM from which a formula is to be created. +type FormulaPropertiesFromVMFragment struct { + // LabVMID - The identifier of the VM from which a formula is to be created. + LabVMID *string `json:"labVmId,omitempty"` +} + +// FormulasCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type FormulasCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *FormulasCreateOrUpdateFuture) Result(client FormulasClient) (f Formula, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.FormulasCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.FormulasCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if f.Response.Response, err = future.GetResult(sender); err == nil && f.Response.Response.StatusCode != http.StatusNoContent { + f, err = client.CreateOrUpdateResponder(f.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.FormulasCreateOrUpdateFuture", "Result", f.Response.Response, "Failure responding to request") + } + } + return +} + +// GalleryImage a gallery image. +type GalleryImage struct { + // GalleryImageProperties - The properties of the resource. + *GalleryImageProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for GalleryImage. +func (gi GalleryImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if gi.GalleryImageProperties != nil { + objectMap["properties"] = gi.GalleryImageProperties + } + if gi.Location != nil { + objectMap["location"] = gi.Location + } + if gi.Tags != nil { + objectMap["tags"] = gi.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for GalleryImage struct. +func (gi *GalleryImage) 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 galleryImageProperties GalleryImageProperties + err = json.Unmarshal(*v, &galleryImageProperties) + if err != nil { + return err + } + gi.GalleryImageProperties = &galleryImageProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + gi.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + gi.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + gi.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + gi.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + gi.Tags = tags + } + } + } + + return nil +} + +// GalleryImageList the response of a list operation. +type GalleryImageList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]GalleryImage `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// GalleryImageListIterator provides access to a complete listing of GalleryImage values. +type GalleryImageListIterator struct { + i int + page GalleryImageListPage +} + +// 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 *GalleryImageListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImageListIterator.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 *GalleryImageListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter GalleryImageListIterator) 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 GalleryImageListIterator) Response() GalleryImageList { + 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 GalleryImageListIterator) Value() GalleryImage { + if !iter.page.NotDone() { + return GalleryImage{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the GalleryImageListIterator type. +func NewGalleryImageListIterator(page GalleryImageListPage) GalleryImageListIterator { + return GalleryImageListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (gil GalleryImageList) IsEmpty() bool { + return gil.Value == nil || len(*gil.Value) == 0 +} + +// galleryImageListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (gil GalleryImageList) galleryImageListPreparer(ctx context.Context) (*http.Request, error) { + if gil.NextLink == nil || len(to.String(gil.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(gil.NextLink))) +} + +// GalleryImageListPage contains a page of GalleryImage values. +type GalleryImageListPage struct { + fn func(context.Context, GalleryImageList) (GalleryImageList, error) + gil GalleryImageList +} + +// 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 *GalleryImageListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/GalleryImageListPage.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.gil) + if err != nil { + return err + } + page.gil = 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 *GalleryImageListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page GalleryImageListPage) NotDone() bool { + return !page.gil.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page GalleryImageListPage) Response() GalleryImageList { + return page.gil +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page GalleryImageListPage) Values() []GalleryImage { + if page.gil.IsEmpty() { + return nil + } + return *page.gil.Value +} + +// Creates a new instance of the GalleryImageListPage type. +func NewGalleryImageListPage(getNextPage func(context.Context, GalleryImageList) (GalleryImageList, error)) GalleryImageListPage { + return GalleryImageListPage{fn: getNextPage} +} + +// GalleryImageProperties properties of a gallery image. +type GalleryImageProperties struct { + // Author - The author of the gallery image. + Author *string `json:"author,omitempty"` + // CreatedDate - READ-ONLY; The creation date of the gallery image. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // Description - The description of the gallery image. + Description *string `json:"description,omitempty"` + // ImageReference - The image reference of the gallery image. + ImageReference *GalleryImageReference `json:"imageReference,omitempty"` + // Icon - The icon of the gallery image. + Icon *string `json:"icon,omitempty"` + // Enabled - Indicates whether this gallery image is enabled. + Enabled *bool `json:"enabled,omitempty"` + // PlanID - The third party plan that applies to this image + PlanID *string `json:"planId,omitempty"` + // IsPlanAuthorized - Indicates if the plan has been authorized for programmatic deployment. + IsPlanAuthorized *bool `json:"isPlanAuthorized,omitempty"` +} + +// GalleryImageReference the reference information for an Azure Marketplace image. +type GalleryImageReference struct { + // Offer - The offer of the gallery image. + Offer *string `json:"offer,omitempty"` + // Publisher - The publisher of the gallery image. + Publisher *string `json:"publisher,omitempty"` + // Sku - The SKU of the gallery image. + Sku *string `json:"sku,omitempty"` + // OsType - The OS type of the gallery image. + OsType *string `json:"osType,omitempty"` + // Version - The version of the gallery image. + Version *string `json:"version,omitempty"` +} + +// GalleryImageReferenceFragment the reference information for an Azure Marketplace image. +type GalleryImageReferenceFragment struct { + // Offer - The offer of the gallery image. + Offer *string `json:"offer,omitempty"` + // Publisher - The publisher of the gallery image. + Publisher *string `json:"publisher,omitempty"` + // Sku - The SKU of the gallery image. + Sku *string `json:"sku,omitempty"` + // OsType - The OS type of the gallery image. + OsType *string `json:"osType,omitempty"` + // Version - The version of the gallery image. + Version *string `json:"version,omitempty"` +} + +// GenerateArmTemplateRequest parameters for generating an ARM template for deploying artifacts. +type GenerateArmTemplateRequest struct { + // VirtualMachineName - The resource name of the virtual machine. + VirtualMachineName *string `json:"virtualMachineName,omitempty"` + // Parameters - The parameters of the ARM template. + Parameters *[]ParameterInfo `json:"parameters,omitempty"` + // Location - The location of the virtual machine. + Location *string `json:"location,omitempty"` + // FileUploadOptions - Options for uploading the files for the artifact. UploadFilesAndGenerateSasTokens is the default value. Possible values include: 'FileUploadOptionsUploadFilesAndGenerateSasTokens', 'FileUploadOptionsNone' + FileUploadOptions FileUploadOptions `json:"fileUploadOptions,omitempty"` +} + +// GenerateUploadURIParameter properties for generating an upload URI. +type GenerateUploadURIParameter struct { + // BlobName - The blob name of the upload URI. + BlobName *string `json:"blobName,omitempty"` +} + +// GenerateUploadURIResponse response body for generating an upload URI. +type GenerateUploadURIResponse struct { + autorest.Response `json:"-"` + // UploadURI - The upload URI for the VHD. + UploadURI *string `json:"uploadUri,omitempty"` +} + +// GlobalSchedulesExecuteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type GlobalSchedulesExecuteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *GlobalSchedulesExecuteFuture) Result(client GlobalSchedulesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesExecuteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.GlobalSchedulesExecuteFuture") + return + } + ar.Response = future.Response() + return +} + +// GlobalSchedulesRetargetFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type GlobalSchedulesRetargetFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *GlobalSchedulesRetargetFuture) Result(client GlobalSchedulesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.GlobalSchedulesRetargetFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.GlobalSchedulesRetargetFuture") + return + } + ar.Response = future.Response() + return +} + +// HourDetails properties of an hourly schedule. +type HourDetails struct { + // Minute - Minutes of the hour the schedule will run. + Minute *int32 `json:"minute,omitempty"` +} + +// HourDetailsFragment properties of an hourly schedule. +type HourDetailsFragment struct { + // Minute - Minutes of the hour the schedule will run. + Minute *int32 `json:"minute,omitempty"` +} + +// IdentityProperties properties of a managed identity +type IdentityProperties struct { + // Type - Managed identity. + Type *string `json:"type,omitempty"` + // PrincipalID - The principal id of resource identity. + PrincipalID *string `json:"principalId,omitempty"` + // TenantID - The tenant identifier of resource. + TenantID *string `json:"tenantId,omitempty"` + // ClientSecretURL - The client secret URL of the identity. + ClientSecretURL *string `json:"clientSecretUrl,omitempty"` +} + +// ImportLabVirtualMachineRequest this represents the payload required to import a virtual machine from a +// different lab into the current one +type ImportLabVirtualMachineRequest struct { + // SourceVirtualMachineResourceID - The full resource ID of the virtual machine to be imported. + SourceVirtualMachineResourceID *string `json:"sourceVirtualMachineResourceId,omitempty"` + // DestinationVirtualMachineName - The name of the virtual machine in the destination lab + DestinationVirtualMachineName *string `json:"destinationVirtualMachineName,omitempty"` +} + +// InboundNatRule a rule for NAT - exposing a VM's port (backendPort) on the public IP address using a load +// balancer. +type InboundNatRule struct { + // TransportProtocol - The transport protocol for the endpoint. Possible values include: 'TCP', 'UDP' + TransportProtocol TransportProtocol `json:"transportProtocol,omitempty"` + // FrontendPort - The external endpoint port of the inbound connection. Possible values range between 1 and 65535, inclusive. If unspecified, a value will be allocated automatically. + FrontendPort *int32 `json:"frontendPort,omitempty"` + // BackendPort - The port to which the external traffic will be redirected. + BackendPort *int32 `json:"backendPort,omitempty"` +} + +// InboundNatRuleFragment a rule for NAT - exposing a VM's port (backendPort) on the public IP address +// using a load balancer. +type InboundNatRuleFragment struct { + // TransportProtocol - The transport protocol for the endpoint. Possible values include: 'TCP', 'UDP' + TransportProtocol TransportProtocol `json:"transportProtocol,omitempty"` + // FrontendPort - The external endpoint port of the inbound connection. Possible values range between 1 and 65535, inclusive. If unspecified, a value will be allocated automatically. + FrontendPort *int32 `json:"frontendPort,omitempty"` + // BackendPort - The port to which the external traffic will be redirected. + BackendPort *int32 `json:"backendPort,omitempty"` +} + +// Lab a lab. +type Lab struct { + autorest.Response `json:"-"` + // LabProperties - The properties of the resource. + *LabProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Lab. +func (l Lab) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if l.LabProperties != nil { + objectMap["properties"] = l.LabProperties + } + if l.Location != nil { + objectMap["location"] = l.Location + } + if l.Tags != nil { + objectMap["tags"] = l.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Lab struct. +func (l *Lab) 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 labProperties LabProperties + err = json.Unmarshal(*v, &labProperties) + if err != nil { + return err + } + l.LabProperties = &labProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + l.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + l.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + l.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + l.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + l.Tags = tags + } + } + } + + return nil +} + +// LabAnnouncementProperties properties of a lab's announcement banner +type LabAnnouncementProperties struct { + // Title - The plain text title for the lab announcement + Title *string `json:"title,omitempty"` + // Markdown - The markdown text (if any) that this lab displays in the UI. If left empty/null, nothing will be shown. + Markdown *string `json:"markdown,omitempty"` + // Enabled - Is the lab announcement active/enabled at this time?. Possible values include: 'EnableStatusEnabled', 'EnableStatusDisabled' + Enabled EnableStatus `json:"enabled,omitempty"` + // ExpirationDate - The time at which the announcement expires (null for never) + ExpirationDate *date.Time `json:"expirationDate,omitempty"` + // Expired - Has this announcement expired? + Expired *bool `json:"expired,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// LabAnnouncementPropertiesFragment properties of a lab's announcement banner +type LabAnnouncementPropertiesFragment struct { + // Title - The plain text title for the lab announcement + Title *string `json:"title,omitempty"` + // Markdown - The markdown text (if any) that this lab displays in the UI. If left empty/null, nothing will be shown. + Markdown *string `json:"markdown,omitempty"` + // Enabled - Is the lab announcement active/enabled at this time?. Possible values include: 'EnableStatusEnabled', 'EnableStatusDisabled' + Enabled EnableStatus `json:"enabled,omitempty"` + // ExpirationDate - The time at which the announcement expires (null for never) + ExpirationDate *date.Time `json:"expirationDate,omitempty"` + // Expired - Has this announcement expired? + Expired *bool `json:"expired,omitempty"` +} + +// LabCost a cost item. +type LabCost struct { + autorest.Response `json:"-"` + // LabCostProperties - The properties of the resource. + *LabCostProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for LabCost. +func (lc LabCost) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if lc.LabCostProperties != nil { + objectMap["properties"] = lc.LabCostProperties + } + if lc.Location != nil { + objectMap["location"] = lc.Location + } + if lc.Tags != nil { + objectMap["tags"] = lc.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for LabCost struct. +func (lc *LabCost) 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 labCostProperties LabCostProperties + err = json.Unmarshal(*v, &labCostProperties) + if err != nil { + return err + } + lc.LabCostProperties = &labCostProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + lc.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + lc.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + lc.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + lc.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + lc.Tags = tags + } + } + } + + return nil +} + +// LabCostDetailsProperties the properties of a lab cost item. +type LabCostDetailsProperties struct { + // Date - The date of the cost item. + Date *date.Time `json:"date,omitempty"` + // Cost - The cost component of the cost item. + Cost *float64 `json:"cost,omitempty"` + // CostType - The type of the cost. Possible values include: 'Unavailable', 'Reported', 'Projected' + CostType CostType `json:"costType,omitempty"` +} + +// LabCostProperties properties of a cost item. +type LabCostProperties struct { + // TargetCost - The target cost properties + TargetCost *TargetCostProperties `json:"targetCost,omitempty"` + // LabCostSummary - READ-ONLY; The lab cost summary component of the cost data. + LabCostSummary *LabCostSummaryProperties `json:"labCostSummary,omitempty"` + // LabCostDetails - READ-ONLY; The lab cost details component of the cost data. + LabCostDetails *[]LabCostDetailsProperties `json:"labCostDetails,omitempty"` + // ResourceCosts - READ-ONLY; The resource cost component of the cost data. + ResourceCosts *[]LabResourceCostProperties `json:"resourceCosts,omitempty"` + // CurrencyCode - The currency code of the cost. + CurrencyCode *string `json:"currencyCode,omitempty"` + // StartDateTime - The start time of the cost data. + StartDateTime *date.Time `json:"startDateTime,omitempty"` + // EndDateTime - The end time of the cost data. + EndDateTime *date.Time `json:"endDateTime,omitempty"` + // CreatedDate - The creation date of the cost. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// LabCostSummaryProperties the properties of the cost summary. +type LabCostSummaryProperties struct { + // EstimatedLabCost - The cost component of the cost item. + EstimatedLabCost *float64 `json:"estimatedLabCost,omitempty"` +} + +// LabFragment a lab. +type LabFragment struct { + // LabPropertiesFragment - The properties of the resource. + *LabPropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for LabFragment. +func (lf LabFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if lf.LabPropertiesFragment != nil { + objectMap["properties"] = lf.LabPropertiesFragment + } + if lf.Tags != nil { + objectMap["tags"] = lf.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for LabFragment struct. +func (lf *LabFragment) 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 labPropertiesFragment LabPropertiesFragment + err = json.Unmarshal(*v, &labPropertiesFragment) + if err != nil { + return err + } + lf.LabPropertiesFragment = &labPropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + lf.Tags = tags + } + } + } + + return nil +} + +// LabList the response of a list operation. +type LabList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]Lab `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// LabListIterator provides access to a complete listing of Lab values. +type LabListIterator struct { + i int + page LabListPage +} + +// 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 *LabListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabListIterator.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 *LabListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter LabListIterator) 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 LabListIterator) Response() LabList { + 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 LabListIterator) Value() Lab { + if !iter.page.NotDone() { + return Lab{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the LabListIterator type. +func NewLabListIterator(page LabListPage) LabListIterator { + return LabListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (ll LabList) IsEmpty() bool { + return ll.Value == nil || len(*ll.Value) == 0 +} + +// labListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (ll LabList) labListPreparer(ctx context.Context) (*http.Request, error) { + if ll.NextLink == nil || len(to.String(ll.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(ll.NextLink))) +} + +// LabListPage contains a page of Lab values. +type LabListPage struct { + fn func(context.Context, LabList) (LabList, error) + ll LabList +} + +// 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 *LabListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabListPage.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.ll) + if err != nil { + return err + } + page.ll = 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 *LabListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page LabListPage) NotDone() bool { + return !page.ll.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page LabListPage) Response() LabList { + return page.ll +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page LabListPage) Values() []Lab { + if page.ll.IsEmpty() { + return nil + } + return *page.ll.Value +} + +// Creates a new instance of the LabListPage type. +func NewLabListPage(getNextPage func(context.Context, LabList) (LabList, error)) LabListPage { + return LabListPage{fn: getNextPage} +} + +// LabProperties properties of a lab. +type LabProperties struct { + // DefaultStorageAccount - READ-ONLY; The lab's default storage account. + DefaultStorageAccount *string `json:"defaultStorageAccount,omitempty"` + // DefaultPremiumStorageAccount - READ-ONLY; The lab's default premium storage account. + DefaultPremiumStorageAccount *string `json:"defaultPremiumStorageAccount,omitempty"` + // ArtifactsStorageAccount - READ-ONLY; The lab's artifact storage account. + ArtifactsStorageAccount *string `json:"artifactsStorageAccount,omitempty"` + // PremiumDataDiskStorageAccount - READ-ONLY; The lab's premium data disk storage account. + PremiumDataDiskStorageAccount *string `json:"premiumDataDiskStorageAccount,omitempty"` + // VaultName - READ-ONLY; The lab's Key vault. + VaultName *string `json:"vaultName,omitempty"` + // LabStorageType - Type of storage used by the lab. It can be either Premium or Standard. Default is Premium. Possible values include: 'Standard', 'Premium' + LabStorageType StorageType `json:"labStorageType,omitempty"` + // MandatoryArtifactsResourceIdsLinux - The ordered list of artifact resource IDs that should be applied on all Linux VM creations by default, prior to the artifacts specified by the user. + MandatoryArtifactsResourceIdsLinux *[]string `json:"mandatoryArtifactsResourceIdsLinux,omitempty"` + // MandatoryArtifactsResourceIdsWindows - The ordered list of artifact resource IDs that should be applied on all Windows VM creations by default, prior to the artifacts specified by the user. + MandatoryArtifactsResourceIdsWindows *[]string `json:"mandatoryArtifactsResourceIdsWindows,omitempty"` + // CreatedDate - READ-ONLY; The creation date of the lab. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // PremiumDataDisks - The setting to enable usage of premium data disks. + // When its value is 'Enabled', creation of standard or premium data disks is allowed. + // When its value is 'Disabled', only creation of standard data disks is allowed. Possible values include: 'PremiumDataDiskDisabled', 'PremiumDataDiskEnabled' + PremiumDataDisks PremiumDataDisk `json:"premiumDataDisks,omitempty"` + // EnvironmentPermission - The access rights to be granted to the user when provisioning an environment. Possible values include: 'Reader', 'Contributor' + EnvironmentPermission EnvironmentPermission `json:"environmentPermission,omitempty"` + // Announcement - The properties of any lab announcement associated with this lab + Announcement *LabAnnouncementProperties `json:"announcement,omitempty"` + // Support - The properties of any lab support message associated with this lab + Support *LabSupportProperties `json:"support,omitempty"` + // VMCreationResourceGroup - READ-ONLY; The resource group in which lab virtual machines will be created in. + VMCreationResourceGroup *string `json:"vmCreationResourceGroup,omitempty"` + // PublicIPID - READ-ONLY; The public IP address for the lab's load balancer. + PublicIPID *string `json:"publicIpId,omitempty"` + // LoadBalancerID - READ-ONLY; The load balancer used to for lab VMs that use shared IP address. + LoadBalancerID *string `json:"loadBalancerId,omitempty"` + // NetworkSecurityGroupID - READ-ONLY; The Network Security Group attached to the lab VMs Network interfaces to restrict open ports. + NetworkSecurityGroupID *string `json:"networkSecurityGroupId,omitempty"` + // ExtendedProperties - Extended properties of the lab used for experimental features + ExtendedProperties map[string]*string `json:"extendedProperties"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// MarshalJSON is the custom marshaler for LabProperties. +func (lp LabProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if lp.LabStorageType != "" { + objectMap["labStorageType"] = lp.LabStorageType + } + if lp.MandatoryArtifactsResourceIdsLinux != nil { + objectMap["mandatoryArtifactsResourceIdsLinux"] = lp.MandatoryArtifactsResourceIdsLinux + } + if lp.MandatoryArtifactsResourceIdsWindows != nil { + objectMap["mandatoryArtifactsResourceIdsWindows"] = lp.MandatoryArtifactsResourceIdsWindows + } + if lp.PremiumDataDisks != "" { + objectMap["premiumDataDisks"] = lp.PremiumDataDisks + } + if lp.EnvironmentPermission != "" { + objectMap["environmentPermission"] = lp.EnvironmentPermission + } + if lp.Announcement != nil { + objectMap["announcement"] = lp.Announcement + } + if lp.Support != nil { + objectMap["support"] = lp.Support + } + if lp.ExtendedProperties != nil { + objectMap["extendedProperties"] = lp.ExtendedProperties + } + return json.Marshal(objectMap) +} + +// LabPropertiesFragment properties of a lab. +type LabPropertiesFragment struct { + // LabStorageType - Type of storage used by the lab. It can be either Premium or Standard. Default is Premium. Possible values include: 'Standard', 'Premium' + LabStorageType StorageType `json:"labStorageType,omitempty"` + // MandatoryArtifactsResourceIdsLinux - The ordered list of artifact resource IDs that should be applied on all Linux VM creations by default, prior to the artifacts specified by the user. + MandatoryArtifactsResourceIdsLinux *[]string `json:"mandatoryArtifactsResourceIdsLinux,omitempty"` + // MandatoryArtifactsResourceIdsWindows - The ordered list of artifact resource IDs that should be applied on all Windows VM creations by default, prior to the artifacts specified by the user. + MandatoryArtifactsResourceIdsWindows *[]string `json:"mandatoryArtifactsResourceIdsWindows,omitempty"` + // PremiumDataDisks - The setting to enable usage of premium data disks. + // When its value is 'Enabled', creation of standard or premium data disks is allowed. + // When its value is 'Disabled', only creation of standard data disks is allowed. Possible values include: 'PremiumDataDiskDisabled', 'PremiumDataDiskEnabled' + PremiumDataDisks PremiumDataDisk `json:"premiumDataDisks,omitempty"` + // EnvironmentPermission - The access rights to be granted to the user when provisioning an environment. Possible values include: 'Reader', 'Contributor' + EnvironmentPermission EnvironmentPermission `json:"environmentPermission,omitempty"` + // Announcement - The properties of any lab announcement associated with this lab + Announcement *LabAnnouncementPropertiesFragment `json:"announcement,omitempty"` + // Support - The properties of any lab support message associated with this lab + Support *LabSupportPropertiesFragment `json:"support,omitempty"` + // ExtendedProperties - Extended properties of the lab used for experimental features + ExtendedProperties map[string]*string `json:"extendedProperties"` +} + +// MarshalJSON is the custom marshaler for LabPropertiesFragment. +func (lpf LabPropertiesFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if lpf.LabStorageType != "" { + objectMap["labStorageType"] = lpf.LabStorageType + } + if lpf.MandatoryArtifactsResourceIdsLinux != nil { + objectMap["mandatoryArtifactsResourceIdsLinux"] = lpf.MandatoryArtifactsResourceIdsLinux + } + if lpf.MandatoryArtifactsResourceIdsWindows != nil { + objectMap["mandatoryArtifactsResourceIdsWindows"] = lpf.MandatoryArtifactsResourceIdsWindows + } + if lpf.PremiumDataDisks != "" { + objectMap["premiumDataDisks"] = lpf.PremiumDataDisks + } + if lpf.EnvironmentPermission != "" { + objectMap["environmentPermission"] = lpf.EnvironmentPermission + } + if lpf.Announcement != nil { + objectMap["announcement"] = lpf.Announcement + } + if lpf.Support != nil { + objectMap["support"] = lpf.Support + } + if lpf.ExtendedProperties != nil { + objectMap["extendedProperties"] = lpf.ExtendedProperties + } + return json.Marshal(objectMap) +} + +// LabResourceCostProperties the properties of a resource cost item. +type LabResourceCostProperties struct { + // Resourcename - The name of the resource. + Resourcename *string `json:"resourcename,omitempty"` + // ResourceUID - The unique identifier of the resource. + ResourceUID *string `json:"resourceUId,omitempty"` + // ResourceCost - The cost component of the resource cost item. + ResourceCost *float64 `json:"resourceCost,omitempty"` + // ResourceType - The logical resource type (ex. virtualmachine, storageaccount) + ResourceType *string `json:"resourceType,omitempty"` + // ResourceOwner - The owner of the resource (ex. janedoe@microsoft.com) + ResourceOwner *string `json:"resourceOwner,omitempty"` + // ResourcePricingTier - The category of the resource (ex. Premium_LRS, Standard_DS1) + ResourcePricingTier *string `json:"resourcePricingTier,omitempty"` + // ResourceStatus - The status of the resource (ex. Active) + ResourceStatus *string `json:"resourceStatus,omitempty"` + // ResourceID - The ID of the resource + ResourceID *string `json:"resourceId,omitempty"` + // ExternalResourceID - The ID of the external resource + ExternalResourceID *string `json:"externalResourceId,omitempty"` +} + +// LabsClaimAnyVMFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type LabsClaimAnyVMFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *LabsClaimAnyVMFuture) Result(client LabsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsClaimAnyVMFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.LabsClaimAnyVMFuture") + return + } + ar.Response = future.Response() + return +} + +// LabsCreateEnvironmentFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type LabsCreateEnvironmentFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *LabsCreateEnvironmentFuture) Result(client LabsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsCreateEnvironmentFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.LabsCreateEnvironmentFuture") + return + } + ar.Response = future.Response() + return +} + +// LabsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type LabsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *LabsCreateOrUpdateFuture) Result(client LabsClient) (l Lab, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.LabsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if l.Response.Response, err = future.GetResult(sender); err == nil && l.Response.Response.StatusCode != http.StatusNoContent { + l, err = client.CreateOrUpdateResponder(l.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsCreateOrUpdateFuture", "Result", l.Response.Response, "Failure responding to request") + } + } + return +} + +// LabsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type LabsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *LabsDeleteFuture) Result(client LabsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.LabsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// LabsExportResourceUsageFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type LabsExportResourceUsageFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *LabsExportResourceUsageFuture) Result(client LabsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsExportResourceUsageFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.LabsExportResourceUsageFuture") + return + } + ar.Response = future.Response() + return +} + +// LabsImportVirtualMachineFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type LabsImportVirtualMachineFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *LabsImportVirtualMachineFuture) Result(client LabsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.LabsImportVirtualMachineFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.LabsImportVirtualMachineFuture") + return + } + ar.Response = future.Response() + return +} + +// LabSupportProperties properties of a lab's support banner +type LabSupportProperties struct { + // Enabled - Is the lab support banner active/enabled at this time?. Possible values include: 'EnableStatusEnabled', 'EnableStatusDisabled' + Enabled EnableStatus `json:"enabled,omitempty"` + // Markdown - The markdown text (if any) that this lab displays in the UI. If left empty/null, nothing will be shown. + Markdown *string `json:"markdown,omitempty"` +} + +// LabSupportPropertiesFragment properties of a lab's support banner +type LabSupportPropertiesFragment struct { + // Enabled - Is the lab support banner active/enabled at this time?. Possible values include: 'EnableStatusEnabled', 'EnableStatusDisabled' + Enabled EnableStatus `json:"enabled,omitempty"` + // Markdown - The markdown text (if any) that this lab displays in the UI. If left empty/null, nothing will be shown. + Markdown *string `json:"markdown,omitempty"` +} + +// LabVhd properties of a VHD in the lab. +type LabVhd struct { + // ID - The URI to the VHD. + ID *string `json:"id,omitempty"` +} + +// LabVhdList the response of a list operation. +type LabVhdList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]LabVhd `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// LabVhdListIterator provides access to a complete listing of LabVhd values. +type LabVhdListIterator struct { + i int + page LabVhdListPage +} + +// 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 *LabVhdListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabVhdListIterator.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 *LabVhdListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter LabVhdListIterator) 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 LabVhdListIterator) Response() LabVhdList { + 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 LabVhdListIterator) Value() LabVhd { + if !iter.page.NotDone() { + return LabVhd{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the LabVhdListIterator type. +func NewLabVhdListIterator(page LabVhdListPage) LabVhdListIterator { + return LabVhdListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (lvl LabVhdList) IsEmpty() bool { + return lvl.Value == nil || len(*lvl.Value) == 0 +} + +// labVhdListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (lvl LabVhdList) labVhdListPreparer(ctx context.Context) (*http.Request, error) { + if lvl.NextLink == nil || len(to.String(lvl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(lvl.NextLink))) +} + +// LabVhdListPage contains a page of LabVhd values. +type LabVhdListPage struct { + fn func(context.Context, LabVhdList) (LabVhdList, error) + lvl LabVhdList +} + +// 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 *LabVhdListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabVhdListPage.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.lvl) + if err != nil { + return err + } + page.lvl = 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 *LabVhdListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page LabVhdListPage) NotDone() bool { + return !page.lvl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page LabVhdListPage) Response() LabVhdList { + return page.lvl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page LabVhdListPage) Values() []LabVhd { + if page.lvl.IsEmpty() { + return nil + } + return *page.lvl.Value +} + +// Creates a new instance of the LabVhdListPage type. +func NewLabVhdListPage(getNextPage func(context.Context, LabVhdList) (LabVhdList, error)) LabVhdListPage { + return LabVhdListPage{fn: getNextPage} +} + +// LabVirtualMachine a virtual machine. +type LabVirtualMachine struct { + autorest.Response `json:"-"` + // LabVirtualMachineProperties - The properties of the resource. + *LabVirtualMachineProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for LabVirtualMachine. +func (lvm LabVirtualMachine) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if lvm.LabVirtualMachineProperties != nil { + objectMap["properties"] = lvm.LabVirtualMachineProperties + } + if lvm.Location != nil { + objectMap["location"] = lvm.Location + } + if lvm.Tags != nil { + objectMap["tags"] = lvm.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for LabVirtualMachine struct. +func (lvm *LabVirtualMachine) 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 labVirtualMachineProperties LabVirtualMachineProperties + err = json.Unmarshal(*v, &labVirtualMachineProperties) + if err != nil { + return err + } + lvm.LabVirtualMachineProperties = &labVirtualMachineProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + lvm.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + lvm.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + lvm.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + lvm.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + lvm.Tags = tags + } + } + } + + return nil +} + +// LabVirtualMachineCreationParameter properties for creating a virtual machine. +type LabVirtualMachineCreationParameter struct { + // LabVirtualMachineCreationParameterProperties - The properties of the resource. + *LabVirtualMachineCreationParameterProperties `json:"properties,omitempty"` + // Name - The name of the virtual machine or environment + Name *string `json:"name,omitempty"` + // Location - The location of the new virtual machine or environment + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for LabVirtualMachineCreationParameter. +func (lvmcp LabVirtualMachineCreationParameter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if lvmcp.LabVirtualMachineCreationParameterProperties != nil { + objectMap["properties"] = lvmcp.LabVirtualMachineCreationParameterProperties + } + if lvmcp.Name != nil { + objectMap["name"] = lvmcp.Name + } + if lvmcp.Location != nil { + objectMap["location"] = lvmcp.Location + } + if lvmcp.Tags != nil { + objectMap["tags"] = lvmcp.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for LabVirtualMachineCreationParameter struct. +func (lvmcp *LabVirtualMachineCreationParameter) 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 labVirtualMachineCreationParameterProperties LabVirtualMachineCreationParameterProperties + err = json.Unmarshal(*v, &labVirtualMachineCreationParameterProperties) + if err != nil { + return err + } + lvmcp.LabVirtualMachineCreationParameterProperties = &labVirtualMachineCreationParameterProperties + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + lvmcp.Name = &name + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + lvmcp.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + lvmcp.Tags = tags + } + } + } + + return nil +} + +// LabVirtualMachineCreationParameterFragment properties for creating a virtual machine. +type LabVirtualMachineCreationParameterFragment struct { + // LabVirtualMachineCreationParameterPropertiesFragment - The properties of the resource. + *LabVirtualMachineCreationParameterPropertiesFragment `json:"properties,omitempty"` + // Name - The name of the virtual machine or environment + Name *string `json:"name,omitempty"` + // Location - The location of the new virtual machine or environment + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for LabVirtualMachineCreationParameterFragment. +func (lvmcpf LabVirtualMachineCreationParameterFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if lvmcpf.LabVirtualMachineCreationParameterPropertiesFragment != nil { + objectMap["properties"] = lvmcpf.LabVirtualMachineCreationParameterPropertiesFragment + } + if lvmcpf.Name != nil { + objectMap["name"] = lvmcpf.Name + } + if lvmcpf.Location != nil { + objectMap["location"] = lvmcpf.Location + } + if lvmcpf.Tags != nil { + objectMap["tags"] = lvmcpf.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for LabVirtualMachineCreationParameterFragment struct. +func (lvmcpf *LabVirtualMachineCreationParameterFragment) 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 labVirtualMachineCreationParameterPropertiesFragment LabVirtualMachineCreationParameterPropertiesFragment + err = json.Unmarshal(*v, &labVirtualMachineCreationParameterPropertiesFragment) + if err != nil { + return err + } + lvmcpf.LabVirtualMachineCreationParameterPropertiesFragment = &labVirtualMachineCreationParameterPropertiesFragment + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + lvmcpf.Name = &name + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + lvmcpf.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + lvmcpf.Tags = tags + } + } + } + + return nil +} + +// LabVirtualMachineCreationParameterProperties properties for virtual machine creation. +type LabVirtualMachineCreationParameterProperties struct { + // BulkCreationParameters - The number of virtual machine instances to create. + BulkCreationParameters *BulkCreationParameters `json:"bulkCreationParameters,omitempty"` + // Notes - The notes of the virtual machine. + Notes *string `json:"notes,omitempty"` + // OwnerObjectID - The object identifier of the owner of the virtual machine. + OwnerObjectID *string `json:"ownerObjectId,omitempty"` + // OwnerUserPrincipalName - The user principal name of the virtual machine owner. + OwnerUserPrincipalName *string `json:"ownerUserPrincipalName,omitempty"` + // CreatedByUserID - The object identifier of the creator of the virtual machine. + CreatedByUserID *string `json:"createdByUserId,omitempty"` + // CreatedByUser - The email address of creator of the virtual machine. + CreatedByUser *string `json:"createdByUser,omitempty"` + // CreatedDate - The creation date of the virtual machine. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // ComputeID - The resource identifier (Microsoft.Compute) of the virtual machine. + ComputeID *string `json:"computeId,omitempty"` + // CustomImageID - The custom image identifier of the virtual machine. + CustomImageID *string `json:"customImageId,omitempty"` + // OsType - The OS type of the virtual machine. + OsType *string `json:"osType,omitempty"` + // Size - The size of the virtual machine. + Size *string `json:"size,omitempty"` + // UserName - The user name of the virtual machine. + UserName *string `json:"userName,omitempty"` + // Password - The password of the virtual machine administrator. + Password *string `json:"password,omitempty"` + // SSHKey - The SSH key of the virtual machine administrator. + SSHKey *string `json:"sshKey,omitempty"` + // IsAuthenticationWithSSHKey - Indicates whether this virtual machine uses an SSH key for authentication. + IsAuthenticationWithSSHKey *bool `json:"isAuthenticationWithSshKey,omitempty"` + // Fqdn - The fully-qualified domain name of the virtual machine. + Fqdn *string `json:"fqdn,omitempty"` + // LabSubnetName - The lab subnet name of the virtual machine. + LabSubnetName *string `json:"labSubnetName,omitempty"` + // LabVirtualNetworkID - The lab virtual network identifier of the virtual machine. + LabVirtualNetworkID *string `json:"labVirtualNetworkId,omitempty"` + // DisallowPublicIPAddress - Indicates whether the virtual machine is to be created without a public IP address. + DisallowPublicIPAddress *bool `json:"disallowPublicIpAddress,omitempty"` + // Artifacts - The artifacts to be installed on the virtual machine. + Artifacts *[]ArtifactInstallProperties `json:"artifacts,omitempty"` + // ArtifactDeploymentStatus - The artifact deployment status for the virtual machine. + ArtifactDeploymentStatus *ArtifactDeploymentStatusProperties `json:"artifactDeploymentStatus,omitempty"` + // GalleryImageReference - The Microsoft Azure Marketplace image reference of the virtual machine. + GalleryImageReference *GalleryImageReference `json:"galleryImageReference,omitempty"` + // PlanID - The id of the plan associated with the virtual machine image + PlanID *string `json:"planId,omitempty"` + // NetworkInterface - The network interface properties. + NetworkInterface *NetworkInterfaceProperties `json:"networkInterface,omitempty"` + // ExpirationDate - The expiration date for VM. + ExpirationDate *date.Time `json:"expirationDate,omitempty"` + // AllowClaim - Indicates whether another user can take ownership of the virtual machine + AllowClaim *bool `json:"allowClaim,omitempty"` + // StorageType - Storage type to use for virtual machine (i.e. Standard, Premium). + StorageType *string `json:"storageType,omitempty"` + // VirtualMachineCreationSource - Tells source of creation of lab virtual machine. Output property only. Possible values include: 'FromCustomImage', 'FromGalleryImage' + VirtualMachineCreationSource VirtualMachineCreationSource `json:"virtualMachineCreationSource,omitempty"` + // EnvironmentID - The resource ID of the environment that contains this virtual machine, if any. + EnvironmentID *string `json:"environmentId,omitempty"` + // DataDiskParameters - New or existing data disks to attach to the virtual machine after creation + DataDiskParameters *[]DataDiskProperties `json:"dataDiskParameters,omitempty"` + // ScheduleParameters - Virtual Machine schedules to be created + ScheduleParameters *[]ScheduleCreationParameter `json:"scheduleParameters,omitempty"` + // LastKnownPowerState - Last known compute power state captured in DTL + LastKnownPowerState *string `json:"lastKnownPowerState,omitempty"` +} + +// LabVirtualMachineCreationParameterPropertiesFragment properties for virtual machine creation. +type LabVirtualMachineCreationParameterPropertiesFragment struct { + // BulkCreationParameters - The number of virtual machine instances to create. + BulkCreationParameters *BulkCreationParametersFragment `json:"bulkCreationParameters,omitempty"` + // Notes - The notes of the virtual machine. + Notes *string `json:"notes,omitempty"` + // OwnerObjectID - The object identifier of the owner of the virtual machine. + OwnerObjectID *string `json:"ownerObjectId,omitempty"` + // OwnerUserPrincipalName - The user principal name of the virtual machine owner. + OwnerUserPrincipalName *string `json:"ownerUserPrincipalName,omitempty"` + // CreatedByUserID - The object identifier of the creator of the virtual machine. + CreatedByUserID *string `json:"createdByUserId,omitempty"` + // CreatedByUser - The email address of creator of the virtual machine. + CreatedByUser *string `json:"createdByUser,omitempty"` + // CreatedDate - The creation date of the virtual machine. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // ComputeID - The resource identifier (Microsoft.Compute) of the virtual machine. + ComputeID *string `json:"computeId,omitempty"` + // CustomImageID - The custom image identifier of the virtual machine. + CustomImageID *string `json:"customImageId,omitempty"` + // OsType - The OS type of the virtual machine. + OsType *string `json:"osType,omitempty"` + // Size - The size of the virtual machine. + Size *string `json:"size,omitempty"` + // UserName - The user name of the virtual machine. + UserName *string `json:"userName,omitempty"` + // Password - The password of the virtual machine administrator. + Password *string `json:"password,omitempty"` + // SSHKey - The SSH key of the virtual machine administrator. + SSHKey *string `json:"sshKey,omitempty"` + // IsAuthenticationWithSSHKey - Indicates whether this virtual machine uses an SSH key for authentication. + IsAuthenticationWithSSHKey *bool `json:"isAuthenticationWithSshKey,omitempty"` + // Fqdn - The fully-qualified domain name of the virtual machine. + Fqdn *string `json:"fqdn,omitempty"` + // LabSubnetName - The lab subnet name of the virtual machine. + LabSubnetName *string `json:"labSubnetName,omitempty"` + // LabVirtualNetworkID - The lab virtual network identifier of the virtual machine. + LabVirtualNetworkID *string `json:"labVirtualNetworkId,omitempty"` + // DisallowPublicIPAddress - Indicates whether the virtual machine is to be created without a public IP address. + DisallowPublicIPAddress *bool `json:"disallowPublicIpAddress,omitempty"` + // Artifacts - The artifacts to be installed on the virtual machine. + Artifacts *[]ArtifactInstallPropertiesFragment `json:"artifacts,omitempty"` + // ArtifactDeploymentStatus - The artifact deployment status for the virtual machine. + ArtifactDeploymentStatus *ArtifactDeploymentStatusPropertiesFragment `json:"artifactDeploymentStatus,omitempty"` + // GalleryImageReference - The Microsoft Azure Marketplace image reference of the virtual machine. + GalleryImageReference *GalleryImageReferenceFragment `json:"galleryImageReference,omitempty"` + // PlanID - The id of the plan associated with the virtual machine image + PlanID *string `json:"planId,omitempty"` + // NetworkInterface - The network interface properties. + NetworkInterface *NetworkInterfacePropertiesFragment `json:"networkInterface,omitempty"` + // ExpirationDate - The expiration date for VM. + ExpirationDate *date.Time `json:"expirationDate,omitempty"` + // AllowClaim - Indicates whether another user can take ownership of the virtual machine + AllowClaim *bool `json:"allowClaim,omitempty"` + // StorageType - Storage type to use for virtual machine (i.e. Standard, Premium). + StorageType *string `json:"storageType,omitempty"` + // VirtualMachineCreationSource - Tells source of creation of lab virtual machine. Output property only. Possible values include: 'FromCustomImage', 'FromGalleryImage' + VirtualMachineCreationSource VirtualMachineCreationSource `json:"virtualMachineCreationSource,omitempty"` + // EnvironmentID - The resource ID of the environment that contains this virtual machine, if any. + EnvironmentID *string `json:"environmentId,omitempty"` + // DataDiskParameters - New or existing data disks to attach to the virtual machine after creation + DataDiskParameters *[]DataDiskPropertiesFragment `json:"dataDiskParameters,omitempty"` + // ScheduleParameters - Virtual Machine schedules to be created + ScheduleParameters *[]ScheduleCreationParameterFragment `json:"scheduleParameters,omitempty"` + // LastKnownPowerState - Last known compute power state captured in DTL + LastKnownPowerState *string `json:"lastKnownPowerState,omitempty"` +} + +// LabVirtualMachineFragment a virtual machine. +type LabVirtualMachineFragment struct { + // LabVirtualMachinePropertiesFragment - The properties of the resource. + *LabVirtualMachinePropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for LabVirtualMachineFragment. +func (lvmf LabVirtualMachineFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if lvmf.LabVirtualMachinePropertiesFragment != nil { + objectMap["properties"] = lvmf.LabVirtualMachinePropertiesFragment + } + if lvmf.Tags != nil { + objectMap["tags"] = lvmf.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for LabVirtualMachineFragment struct. +func (lvmf *LabVirtualMachineFragment) 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 labVirtualMachinePropertiesFragment LabVirtualMachinePropertiesFragment + err = json.Unmarshal(*v, &labVirtualMachinePropertiesFragment) + if err != nil { + return err + } + lvmf.LabVirtualMachinePropertiesFragment = &labVirtualMachinePropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + lvmf.Tags = tags + } + } + } + + return nil +} + +// LabVirtualMachineList the response of a list operation. +type LabVirtualMachineList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]LabVirtualMachine `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// LabVirtualMachineListIterator provides access to a complete listing of LabVirtualMachine values. +type LabVirtualMachineListIterator struct { + i int + page LabVirtualMachineListPage +} + +// 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 *LabVirtualMachineListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabVirtualMachineListIterator.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 *LabVirtualMachineListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter LabVirtualMachineListIterator) 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 LabVirtualMachineListIterator) Response() LabVirtualMachineList { + 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 LabVirtualMachineListIterator) Value() LabVirtualMachine { + if !iter.page.NotDone() { + return LabVirtualMachine{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the LabVirtualMachineListIterator type. +func NewLabVirtualMachineListIterator(page LabVirtualMachineListPage) LabVirtualMachineListIterator { + return LabVirtualMachineListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (lvml LabVirtualMachineList) IsEmpty() bool { + return lvml.Value == nil || len(*lvml.Value) == 0 +} + +// labVirtualMachineListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (lvml LabVirtualMachineList) labVirtualMachineListPreparer(ctx context.Context) (*http.Request, error) { + if lvml.NextLink == nil || len(to.String(lvml.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(lvml.NextLink))) +} + +// LabVirtualMachineListPage contains a page of LabVirtualMachine values. +type LabVirtualMachineListPage struct { + fn func(context.Context, LabVirtualMachineList) (LabVirtualMachineList, error) + lvml LabVirtualMachineList +} + +// 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 *LabVirtualMachineListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/LabVirtualMachineListPage.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.lvml) + if err != nil { + return err + } + page.lvml = 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 *LabVirtualMachineListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page LabVirtualMachineListPage) NotDone() bool { + return !page.lvml.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page LabVirtualMachineListPage) Response() LabVirtualMachineList { + return page.lvml +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page LabVirtualMachineListPage) Values() []LabVirtualMachine { + if page.lvml.IsEmpty() { + return nil + } + return *page.lvml.Value +} + +// Creates a new instance of the LabVirtualMachineListPage type. +func NewLabVirtualMachineListPage(getNextPage func(context.Context, LabVirtualMachineList) (LabVirtualMachineList, error)) LabVirtualMachineListPage { + return LabVirtualMachineListPage{fn: getNextPage} +} + +// LabVirtualMachineProperties properties of a virtual machine. +type LabVirtualMachineProperties struct { + // Notes - The notes of the virtual machine. + Notes *string `json:"notes,omitempty"` + // OwnerObjectID - The object identifier of the owner of the virtual machine. + OwnerObjectID *string `json:"ownerObjectId,omitempty"` + // OwnerUserPrincipalName - The user principal name of the virtual machine owner. + OwnerUserPrincipalName *string `json:"ownerUserPrincipalName,omitempty"` + // CreatedByUserID - The object identifier of the creator of the virtual machine. + CreatedByUserID *string `json:"createdByUserId,omitempty"` + // CreatedByUser - The email address of creator of the virtual machine. + CreatedByUser *string `json:"createdByUser,omitempty"` + // CreatedDate - The creation date of the virtual machine. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // ComputeID - The resource identifier (Microsoft.Compute) of the virtual machine. + ComputeID *string `json:"computeId,omitempty"` + // CustomImageID - The custom image identifier of the virtual machine. + CustomImageID *string `json:"customImageId,omitempty"` + // OsType - The OS type of the virtual machine. + OsType *string `json:"osType,omitempty"` + // Size - The size of the virtual machine. + Size *string `json:"size,omitempty"` + // UserName - The user name of the virtual machine. + UserName *string `json:"userName,omitempty"` + // Password - The password of the virtual machine administrator. + Password *string `json:"password,omitempty"` + // SSHKey - The SSH key of the virtual machine administrator. + SSHKey *string `json:"sshKey,omitempty"` + // IsAuthenticationWithSSHKey - Indicates whether this virtual machine uses an SSH key for authentication. + IsAuthenticationWithSSHKey *bool `json:"isAuthenticationWithSshKey,omitempty"` + // Fqdn - The fully-qualified domain name of the virtual machine. + Fqdn *string `json:"fqdn,omitempty"` + // LabSubnetName - The lab subnet name of the virtual machine. + LabSubnetName *string `json:"labSubnetName,omitempty"` + // LabVirtualNetworkID - The lab virtual network identifier of the virtual machine. + LabVirtualNetworkID *string `json:"labVirtualNetworkId,omitempty"` + // DisallowPublicIPAddress - Indicates whether the virtual machine is to be created without a public IP address. + DisallowPublicIPAddress *bool `json:"disallowPublicIpAddress,omitempty"` + // Artifacts - The artifacts to be installed on the virtual machine. + Artifacts *[]ArtifactInstallProperties `json:"artifacts,omitempty"` + // ArtifactDeploymentStatus - The artifact deployment status for the virtual machine. + ArtifactDeploymentStatus *ArtifactDeploymentStatusProperties `json:"artifactDeploymentStatus,omitempty"` + // GalleryImageReference - The Microsoft Azure Marketplace image reference of the virtual machine. + GalleryImageReference *GalleryImageReference `json:"galleryImageReference,omitempty"` + // PlanID - The id of the plan associated with the virtual machine image + PlanID *string `json:"planId,omitempty"` + // ComputeVM - READ-ONLY; The compute virtual machine properties. + ComputeVM *ComputeVMProperties `json:"computeVm,omitempty"` + // NetworkInterface - The network interface properties. + NetworkInterface *NetworkInterfaceProperties `json:"networkInterface,omitempty"` + // ApplicableSchedule - READ-ONLY; The applicable schedule for the virtual machine. + ApplicableSchedule *ApplicableSchedule `json:"applicableSchedule,omitempty"` + // ExpirationDate - The expiration date for VM. + ExpirationDate *date.Time `json:"expirationDate,omitempty"` + // AllowClaim - Indicates whether another user can take ownership of the virtual machine + AllowClaim *bool `json:"allowClaim,omitempty"` + // StorageType - Storage type to use for virtual machine (i.e. Standard, Premium). + StorageType *string `json:"storageType,omitempty"` + // VirtualMachineCreationSource - Tells source of creation of lab virtual machine. Output property only. Possible values include: 'FromCustomImage', 'FromGalleryImage' + VirtualMachineCreationSource VirtualMachineCreationSource `json:"virtualMachineCreationSource,omitempty"` + // EnvironmentID - The resource ID of the environment that contains this virtual machine, if any. + EnvironmentID *string `json:"environmentId,omitempty"` + // DataDiskParameters - New or existing data disks to attach to the virtual machine after creation + DataDiskParameters *[]DataDiskProperties `json:"dataDiskParameters,omitempty"` + // ScheduleParameters - Virtual Machine schedules to be created + ScheduleParameters *[]ScheduleCreationParameter `json:"scheduleParameters,omitempty"` + // LastKnownPowerState - Last known compute power state captured in DTL + LastKnownPowerState *string `json:"lastKnownPowerState,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// LabVirtualMachinePropertiesFragment properties of a virtual machine. +type LabVirtualMachinePropertiesFragment struct { + // Notes - The notes of the virtual machine. + Notes *string `json:"notes,omitempty"` + // OwnerObjectID - The object identifier of the owner of the virtual machine. + OwnerObjectID *string `json:"ownerObjectId,omitempty"` + // OwnerUserPrincipalName - The user principal name of the virtual machine owner. + OwnerUserPrincipalName *string `json:"ownerUserPrincipalName,omitempty"` + // CreatedByUserID - The object identifier of the creator of the virtual machine. + CreatedByUserID *string `json:"createdByUserId,omitempty"` + // CreatedByUser - The email address of creator of the virtual machine. + CreatedByUser *string `json:"createdByUser,omitempty"` + // CreatedDate - The creation date of the virtual machine. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // ComputeID - The resource identifier (Microsoft.Compute) of the virtual machine. + ComputeID *string `json:"computeId,omitempty"` + // CustomImageID - The custom image identifier of the virtual machine. + CustomImageID *string `json:"customImageId,omitempty"` + // OsType - The OS type of the virtual machine. + OsType *string `json:"osType,omitempty"` + // Size - The size of the virtual machine. + Size *string `json:"size,omitempty"` + // UserName - The user name of the virtual machine. + UserName *string `json:"userName,omitempty"` + // Password - The password of the virtual machine administrator. + Password *string `json:"password,omitempty"` + // SSHKey - The SSH key of the virtual machine administrator. + SSHKey *string `json:"sshKey,omitempty"` + // IsAuthenticationWithSSHKey - Indicates whether this virtual machine uses an SSH key for authentication. + IsAuthenticationWithSSHKey *bool `json:"isAuthenticationWithSshKey,omitempty"` + // Fqdn - The fully-qualified domain name of the virtual machine. + Fqdn *string `json:"fqdn,omitempty"` + // LabSubnetName - The lab subnet name of the virtual machine. + LabSubnetName *string `json:"labSubnetName,omitempty"` + // LabVirtualNetworkID - The lab virtual network identifier of the virtual machine. + LabVirtualNetworkID *string `json:"labVirtualNetworkId,omitempty"` + // DisallowPublicIPAddress - Indicates whether the virtual machine is to be created without a public IP address. + DisallowPublicIPAddress *bool `json:"disallowPublicIpAddress,omitempty"` + // Artifacts - The artifacts to be installed on the virtual machine. + Artifacts *[]ArtifactInstallPropertiesFragment `json:"artifacts,omitempty"` + // ArtifactDeploymentStatus - The artifact deployment status for the virtual machine. + ArtifactDeploymentStatus *ArtifactDeploymentStatusPropertiesFragment `json:"artifactDeploymentStatus,omitempty"` + // GalleryImageReference - The Microsoft Azure Marketplace image reference of the virtual machine. + GalleryImageReference *GalleryImageReferenceFragment `json:"galleryImageReference,omitempty"` + // PlanID - The id of the plan associated with the virtual machine image + PlanID *string `json:"planId,omitempty"` + // NetworkInterface - The network interface properties. + NetworkInterface *NetworkInterfacePropertiesFragment `json:"networkInterface,omitempty"` + // ExpirationDate - The expiration date for VM. + ExpirationDate *date.Time `json:"expirationDate,omitempty"` + // AllowClaim - Indicates whether another user can take ownership of the virtual machine + AllowClaim *bool `json:"allowClaim,omitempty"` + // StorageType - Storage type to use for virtual machine (i.e. Standard, Premium). + StorageType *string `json:"storageType,omitempty"` + // VirtualMachineCreationSource - Tells source of creation of lab virtual machine. Output property only. Possible values include: 'FromCustomImage', 'FromGalleryImage' + VirtualMachineCreationSource VirtualMachineCreationSource `json:"virtualMachineCreationSource,omitempty"` + // EnvironmentID - The resource ID of the environment that contains this virtual machine, if any. + EnvironmentID *string `json:"environmentId,omitempty"` + // DataDiskParameters - New or existing data disks to attach to the virtual machine after creation + DataDiskParameters *[]DataDiskPropertiesFragment `json:"dataDiskParameters,omitempty"` + // ScheduleParameters - Virtual Machine schedules to be created + ScheduleParameters *[]ScheduleCreationParameterFragment `json:"scheduleParameters,omitempty"` + // LastKnownPowerState - Last known compute power state captured in DTL + LastKnownPowerState *string `json:"lastKnownPowerState,omitempty"` +} + +// LinuxOsInfo information about a Linux OS. +type LinuxOsInfo struct { + // LinuxOsState - The state of the Linux OS (i.e. NonDeprovisioned, DeprovisionRequested, DeprovisionApplied). Possible values include: 'NonDeprovisioned', 'DeprovisionRequested', 'DeprovisionApplied' + LinuxOsState LinuxOsState `json:"linuxOsState,omitempty"` +} + +// LinuxOsInfoFragment information about a Linux OS. +type LinuxOsInfoFragment struct { + // LinuxOsState - The state of the Linux OS (i.e. NonDeprovisioned, DeprovisionRequested, DeprovisionApplied). Possible values include: 'NonDeprovisioned', 'DeprovisionRequested', 'DeprovisionApplied' + LinuxOsState LinuxOsState `json:"linuxOsState,omitempty"` +} + +// NetworkInterfaceProperties properties of a network interface. +type NetworkInterfaceProperties struct { + // VirtualNetworkID - The resource ID of the virtual network. + VirtualNetworkID *string `json:"virtualNetworkId,omitempty"` + // SubnetID - The resource ID of the sub net. + SubnetID *string `json:"subnetId,omitempty"` + // PublicIPAddressID - The resource ID of the public IP address. + PublicIPAddressID *string `json:"publicIpAddressId,omitempty"` + // PublicIPAddress - The public IP address. + PublicIPAddress *string `json:"publicIpAddress,omitempty"` + // PrivateIPAddress - The private IP address. + PrivateIPAddress *string `json:"privateIpAddress,omitempty"` + // DNSName - The DNS name. + DNSName *string `json:"dnsName,omitempty"` + // RdpAuthority - The RdpAuthority property is a server DNS host name or IP address followed by the service port number for RDP (Remote Desktop Protocol). + RdpAuthority *string `json:"rdpAuthority,omitempty"` + // SSHAuthority - The SshAuthority property is a server DNS host name or IP address followed by the service port number for SSH. + SSHAuthority *string `json:"sshAuthority,omitempty"` + // SharedPublicIPAddressConfiguration - The configuration for sharing a public IP address across multiple virtual machines. + SharedPublicIPAddressConfiguration *SharedPublicIPAddressConfiguration `json:"sharedPublicIpAddressConfiguration,omitempty"` +} + +// NetworkInterfacePropertiesFragment properties of a network interface. +type NetworkInterfacePropertiesFragment struct { + // VirtualNetworkID - The resource ID of the virtual network. + VirtualNetworkID *string `json:"virtualNetworkId,omitempty"` + // SubnetID - The resource ID of the sub net. + SubnetID *string `json:"subnetId,omitempty"` + // PublicIPAddressID - The resource ID of the public IP address. + PublicIPAddressID *string `json:"publicIpAddressId,omitempty"` + // PublicIPAddress - The public IP address. + PublicIPAddress *string `json:"publicIpAddress,omitempty"` + // PrivateIPAddress - The private IP address. + PrivateIPAddress *string `json:"privateIpAddress,omitempty"` + // DNSName - The DNS name. + DNSName *string `json:"dnsName,omitempty"` + // RdpAuthority - The RdpAuthority property is a server DNS host name or IP address followed by the service port number for RDP (Remote Desktop Protocol). + RdpAuthority *string `json:"rdpAuthority,omitempty"` + // SSHAuthority - The SshAuthority property is a server DNS host name or IP address followed by the service port number for SSH. + SSHAuthority *string `json:"sshAuthority,omitempty"` + // SharedPublicIPAddressConfiguration - The configuration for sharing a public IP address across multiple virtual machines. + SharedPublicIPAddressConfiguration *SharedPublicIPAddressConfigurationFragment `json:"sharedPublicIpAddressConfiguration,omitempty"` +} + +// NotificationChannel a notification. +type NotificationChannel struct { + autorest.Response `json:"-"` + // NotificationChannelProperties - The properties of the resource. + *NotificationChannelProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for NotificationChannel. +func (nc NotificationChannel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if nc.NotificationChannelProperties != nil { + objectMap["properties"] = nc.NotificationChannelProperties + } + if nc.Location != nil { + objectMap["location"] = nc.Location + } + if nc.Tags != nil { + objectMap["tags"] = nc.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for NotificationChannel struct. +func (nc *NotificationChannel) 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 notificationChannelProperties NotificationChannelProperties + err = json.Unmarshal(*v, ¬ificationChannelProperties) + if err != nil { + return err + } + nc.NotificationChannelProperties = ¬ificationChannelProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + nc.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + nc.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + nc.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + nc.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + nc.Tags = tags + } + } + } + + return nil +} + +// NotificationChannelFragment a notification. +type NotificationChannelFragment struct { + // NotificationChannelPropertiesFragment - The properties of the resource. + *NotificationChannelPropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for NotificationChannelFragment. +func (ncf NotificationChannelFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ncf.NotificationChannelPropertiesFragment != nil { + objectMap["properties"] = ncf.NotificationChannelPropertiesFragment + } + if ncf.Tags != nil { + objectMap["tags"] = ncf.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for NotificationChannelFragment struct. +func (ncf *NotificationChannelFragment) 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 notificationChannelPropertiesFragment NotificationChannelPropertiesFragment + err = json.Unmarshal(*v, ¬ificationChannelPropertiesFragment) + if err != nil { + return err + } + ncf.NotificationChannelPropertiesFragment = ¬ificationChannelPropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + ncf.Tags = tags + } + } + } + + return nil +} + +// NotificationChannelList the response of a list operation. +type NotificationChannelList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]NotificationChannel `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// NotificationChannelListIterator provides access to a complete listing of NotificationChannel values. +type NotificationChannelListIterator struct { + i int + page NotificationChannelListPage +} + +// 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 *NotificationChannelListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/NotificationChannelListIterator.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 *NotificationChannelListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter NotificationChannelListIterator) 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 NotificationChannelListIterator) Response() NotificationChannelList { + 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 NotificationChannelListIterator) Value() NotificationChannel { + if !iter.page.NotDone() { + return NotificationChannel{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the NotificationChannelListIterator type. +func NewNotificationChannelListIterator(page NotificationChannelListPage) NotificationChannelListIterator { + return NotificationChannelListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (ncl NotificationChannelList) IsEmpty() bool { + return ncl.Value == nil || len(*ncl.Value) == 0 +} + +// notificationChannelListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (ncl NotificationChannelList) notificationChannelListPreparer(ctx context.Context) (*http.Request, error) { + if ncl.NextLink == nil || len(to.String(ncl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(ncl.NextLink))) +} + +// NotificationChannelListPage contains a page of NotificationChannel values. +type NotificationChannelListPage struct { + fn func(context.Context, NotificationChannelList) (NotificationChannelList, error) + ncl NotificationChannelList +} + +// 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 *NotificationChannelListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/NotificationChannelListPage.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.ncl) + if err != nil { + return err + } + page.ncl = 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 *NotificationChannelListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page NotificationChannelListPage) NotDone() bool { + return !page.ncl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page NotificationChannelListPage) Response() NotificationChannelList { + return page.ncl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page NotificationChannelListPage) Values() []NotificationChannel { + if page.ncl.IsEmpty() { + return nil + } + return *page.ncl.Value +} + +// Creates a new instance of the NotificationChannelListPage type. +func NewNotificationChannelListPage(getNextPage func(context.Context, NotificationChannelList) (NotificationChannelList, error)) NotificationChannelListPage { + return NotificationChannelListPage{fn: getNextPage} +} + +// NotificationChannelProperties properties of a schedule. +type NotificationChannelProperties struct { + // WebHookURL - The webhook URL to send notifications to. + WebHookURL *string `json:"webHookUrl,omitempty"` + // EmailRecipient - The email recipient to send notifications to (can be a list of semi-colon separated email addresses). + EmailRecipient *string `json:"emailRecipient,omitempty"` + // NotificationLocale - The locale to use when sending a notification (fallback for unsupported languages is EN). + NotificationLocale *string `json:"notificationLocale,omitempty"` + // Description - Description of notification. + Description *string `json:"description,omitempty"` + // Events - The list of event for which this notification is enabled. + Events *[]Event `json:"events,omitempty"` + // CreatedDate - READ-ONLY; The creation date of the notification channel. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// NotificationChannelPropertiesFragment properties of a schedule. +type NotificationChannelPropertiesFragment struct { + // WebHookURL - The webhook URL to send notifications to. + WebHookURL *string `json:"webHookUrl,omitempty"` + // EmailRecipient - The email recipient to send notifications to (can be a list of semi-colon separated email addresses). + EmailRecipient *string `json:"emailRecipient,omitempty"` + // NotificationLocale - The locale to use when sending a notification (fallback for unsupported languages is EN). + NotificationLocale *string `json:"notificationLocale,omitempty"` + // Description - Description of notification. + Description *string `json:"description,omitempty"` + // Events - The list of event for which this notification is enabled. + Events *[]EventFragment `json:"events,omitempty"` +} + +// NotificationSettings notification settings for a schedule. +type NotificationSettings struct { + // Status - If notifications are enabled for this schedule (i.e. Enabled, Disabled). Possible values include: 'EnableStatusEnabled', 'EnableStatusDisabled' + Status EnableStatus `json:"status,omitempty"` + // TimeInMinutes - Time in minutes before event at which notification will be sent. + TimeInMinutes *int32 `json:"timeInMinutes,omitempty"` + // WebhookURL - The webhook URL to which the notification will be sent. + WebhookURL *string `json:"webhookUrl,omitempty"` + // EmailRecipient - The email recipient to send notifications to (can be a list of semi-colon separated email addresses). + EmailRecipient *string `json:"emailRecipient,omitempty"` + // NotificationLocale - The locale to use when sending a notification (fallback for unsupported languages is EN). + NotificationLocale *string `json:"notificationLocale,omitempty"` +} + +// NotificationSettingsFragment notification settings for a schedule. +type NotificationSettingsFragment struct { + // Status - If notifications are enabled for this schedule (i.e. Enabled, Disabled). Possible values include: 'EnableStatusEnabled', 'EnableStatusDisabled' + Status EnableStatus `json:"status,omitempty"` + // TimeInMinutes - Time in minutes before event at which notification will be sent. + TimeInMinutes *int32 `json:"timeInMinutes,omitempty"` + // WebhookURL - The webhook URL to which the notification will be sent. + WebhookURL *string `json:"webhookUrl,omitempty"` + // EmailRecipient - The email recipient to send notifications to (can be a list of semi-colon separated email addresses). + EmailRecipient *string `json:"emailRecipient,omitempty"` + // NotificationLocale - The locale to use when sending a notification (fallback for unsupported languages is EN). + NotificationLocale *string `json:"notificationLocale,omitempty"` +} + +// NotifyParameters properties for generating a Notification. +type NotifyParameters struct { + // EventName - The type of event (i.e. AutoShutdown, Cost). Possible values include: 'AutoShutdown', 'Cost' + EventName NotificationChannelEventType `json:"eventName,omitempty"` + // JSONPayload - Properties for the notification in json format. + JSONPayload *string `json:"jsonPayload,omitempty"` +} + +// OperationError error details for the operation in case of a failure. +type OperationError struct { + // Code - The error code of the operation error. + Code *string `json:"code,omitempty"` + // Message - The error message of the operation error. + Message *string `json:"message,omitempty"` +} + +// OperationMetadata the REST API operation supported by DevTestLab ResourceProvider. +type OperationMetadata struct { + // Name - Operation name: {provider}/{resource}/{operation} + Name *string `json:"name,omitempty"` + // Display - The object that describes the operations + Display *OperationMetadataDisplay `json:"display,omitempty"` +} + +// OperationMetadataDisplay the object that describes the operations +type OperationMetadataDisplay struct { + // Provider - Friendly name of the resource provider + Provider *string `json:"provider,omitempty"` + // Resource - Resource type on which the operation is performed. + Resource *string `json:"resource,omitempty"` + // Operation - Operation type: read, write, delete, listKeys/action, etc. + Operation *string `json:"operation,omitempty"` + // Description - Friendly name of the operation + Description *string `json:"description,omitempty"` +} + +// OperationResult an Operation Result +type OperationResult struct { + autorest.Response `json:"-"` + // Status - The operation status. + Status *string `json:"status,omitempty"` + // StatusCode - The status code for the operation. Possible values include: 'Continue', 'SwitchingProtocols', 'OK', 'Created', 'Accepted', 'NonAuthoritativeInformation', 'NoContent', 'ResetContent', 'PartialContent', 'MultipleChoices', 'MovedPermanently', 'Redirect', 'SeeOther', 'NotModified', 'UseProxy', 'Unused', 'TemporaryRedirect', 'BadRequest', 'Unauthorized', 'PaymentRequired', 'Forbidden', 'NotFound', 'MethodNotAllowed', 'NotAcceptable', 'ProxyAuthenticationRequired', 'RequestTimeout', 'Conflict', 'Gone', 'LengthRequired', 'PreconditionFailed', 'RequestEntityTooLarge', 'RequestURITooLong', 'UnsupportedMediaType', 'RequestedRangeNotSatisfiable', 'ExpectationFailed', 'UpgradeRequired', 'InternalServerError', 'NotImplemented', 'BadGateway', 'ServiceUnavailable', 'GatewayTimeout', 'HTTPVersionNotSupported' + StatusCode HTTPStatusCode `json:"statusCode,omitempty"` + // Error - Error details for the operation in case of a failure. + Error *OperationError `json:"error,omitempty"` +} + +// ParameterInfo information about an artifact's parameter. +type ParameterInfo struct { + // Name - The name of the artifact parameter. + Name *string `json:"name,omitempty"` + // Value - The value of the artifact parameter. + Value *string `json:"value,omitempty"` +} + +// ParametersValueFileInfo a file containing a set of parameter values for an ARM template. +type ParametersValueFileInfo struct { + // FileName - File name. + FileName *string `json:"fileName,omitempty"` + // ParametersValueInfo - Contents of the file. + ParametersValueInfo interface{} `json:"parametersValueInfo,omitempty"` +} + +// PercentageCostThresholdProperties properties of a percentage cost threshold. +type PercentageCostThresholdProperties struct { + // ThresholdValue - The cost threshold value. + ThresholdValue *float64 `json:"thresholdValue,omitempty"` +} + +// Policy a Policy. +type Policy struct { + autorest.Response `json:"-"` + // PolicyProperties - The properties of the resource. + *PolicyProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Policy. +func (p Policy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if p.PolicyProperties != nil { + objectMap["properties"] = p.PolicyProperties + } + if p.Location != nil { + objectMap["location"] = p.Location + } + if p.Tags != nil { + objectMap["tags"] = p.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Policy struct. +func (p *Policy) 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 policyProperties PolicyProperties + err = json.Unmarshal(*v, &policyProperties) + if err != nil { + return err + } + p.PolicyProperties = &policyProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + p.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + p.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + p.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + p.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + p.Tags = tags + } + } + } + + return nil +} + +// PolicyFragment a Policy. +type PolicyFragment struct { + // PolicyPropertiesFragment - The properties of the resource. + *PolicyPropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for PolicyFragment. +func (pf PolicyFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pf.PolicyPropertiesFragment != nil { + objectMap["properties"] = pf.PolicyPropertiesFragment + } + if pf.Tags != nil { + objectMap["tags"] = pf.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for PolicyFragment struct. +func (pf *PolicyFragment) 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 policyPropertiesFragment PolicyPropertiesFragment + err = json.Unmarshal(*v, &policyPropertiesFragment) + if err != nil { + return err + } + pf.PolicyPropertiesFragment = &policyPropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + pf.Tags = tags + } + } + } + + return nil +} + +// PolicyList the response of a list operation. +type PolicyList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]Policy `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// PolicyListIterator provides access to a complete listing of Policy values. +type PolicyListIterator struct { + i int + page PolicyListPage +} + +// 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 *PolicyListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PolicyListIterator.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 *PolicyListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter PolicyListIterator) 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 PolicyListIterator) Response() PolicyList { + 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 PolicyListIterator) Value() Policy { + if !iter.page.NotDone() { + return Policy{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the PolicyListIterator type. +func NewPolicyListIterator(page PolicyListPage) PolicyListIterator { + return PolicyListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (pl PolicyList) IsEmpty() bool { + return pl.Value == nil || len(*pl.Value) == 0 +} + +// policyListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (pl PolicyList) policyListPreparer(ctx context.Context) (*http.Request, error) { + if pl.NextLink == nil || len(to.String(pl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(pl.NextLink))) +} + +// PolicyListPage contains a page of Policy values. +type PolicyListPage struct { + fn func(context.Context, PolicyList) (PolicyList, error) + pl PolicyList +} + +// 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 *PolicyListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PolicyListPage.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.pl) + if err != nil { + return err + } + page.pl = 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 *PolicyListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page PolicyListPage) NotDone() bool { + return !page.pl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page PolicyListPage) Response() PolicyList { + return page.pl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page PolicyListPage) Values() []Policy { + if page.pl.IsEmpty() { + return nil + } + return *page.pl.Value +} + +// Creates a new instance of the PolicyListPage type. +func NewPolicyListPage(getNextPage func(context.Context, PolicyList) (PolicyList, error)) PolicyListPage { + return PolicyListPage{fn: getNextPage} +} + +// PolicyProperties properties of a Policy. +type PolicyProperties struct { + // Description - The description of the policy. + Description *string `json:"description,omitempty"` + // Status - The status of the policy. Possible values include: 'PolicyStatusEnabled', 'PolicyStatusDisabled' + Status PolicyStatus `json:"status,omitempty"` + // FactName - The fact name of the policy (e.g. LabVmCount, LabVmSize, MaxVmsAllowedPerLab, etc. Possible values include: 'PolicyFactNameUserOwnedLabVMCount', 'PolicyFactNameUserOwnedLabPremiumVMCount', 'PolicyFactNameLabVMCount', 'PolicyFactNameLabPremiumVMCount', 'PolicyFactNameLabVMSize', 'PolicyFactNameGalleryImage', 'PolicyFactNameUserOwnedLabVMCountInSubnet', 'PolicyFactNameLabTargetCost', 'PolicyFactNameEnvironmentTemplate', 'PolicyFactNameScheduleEditPermission' + FactName PolicyFactName `json:"factName,omitempty"` + // FactData - The fact data of the policy. + FactData *string `json:"factData,omitempty"` + // Threshold - The threshold of the policy (i.e. a number for MaxValuePolicy, and a JSON array of values for AllowedValuesPolicy). + Threshold *string `json:"threshold,omitempty"` + // EvaluatorType - The evaluator type of the policy (i.e. AllowedValuesPolicy, MaxValuePolicy). Possible values include: 'AllowedValuesPolicy', 'MaxValuePolicy' + EvaluatorType PolicyEvaluatorType `json:"evaluatorType,omitempty"` + // CreatedDate - READ-ONLY; The creation date of the policy. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// PolicyPropertiesFragment properties of a Policy. +type PolicyPropertiesFragment struct { + // Description - The description of the policy. + Description *string `json:"description,omitempty"` + // Status - The status of the policy. Possible values include: 'PolicyStatusEnabled', 'PolicyStatusDisabled' + Status PolicyStatus `json:"status,omitempty"` + // FactName - The fact name of the policy (e.g. LabVmCount, LabVmSize, MaxVmsAllowedPerLab, etc. Possible values include: 'PolicyFactNameUserOwnedLabVMCount', 'PolicyFactNameUserOwnedLabPremiumVMCount', 'PolicyFactNameLabVMCount', 'PolicyFactNameLabPremiumVMCount', 'PolicyFactNameLabVMSize', 'PolicyFactNameGalleryImage', 'PolicyFactNameUserOwnedLabVMCountInSubnet', 'PolicyFactNameLabTargetCost', 'PolicyFactNameEnvironmentTemplate', 'PolicyFactNameScheduleEditPermission' + FactName PolicyFactName `json:"factName,omitempty"` + // FactData - The fact data of the policy. + FactData *string `json:"factData,omitempty"` + // Threshold - The threshold of the policy (i.e. a number for MaxValuePolicy, and a JSON array of values for AllowedValuesPolicy). + Threshold *string `json:"threshold,omitempty"` + // EvaluatorType - The evaluator type of the policy (i.e. AllowedValuesPolicy, MaxValuePolicy). Possible values include: 'AllowedValuesPolicy', 'MaxValuePolicy' + EvaluatorType PolicyEvaluatorType `json:"evaluatorType,omitempty"` +} + +// PolicySetResult result of a policy set evaluation. +type PolicySetResult struct { + // HasError - A value indicating whether this policy set evaluation has discovered violations. + HasError *bool `json:"hasError,omitempty"` + // PolicyViolations - The list of policy violations. + PolicyViolations *[]PolicyViolation `json:"policyViolations,omitempty"` +} + +// PolicyViolation policy violation. +type PolicyViolation struct { + // Code - The code of the policy violation. + Code *string `json:"code,omitempty"` + // Message - The message of the policy violation. + Message *string `json:"message,omitempty"` +} + +// Port properties of a network port. +type Port struct { + // TransportProtocol - Protocol type of the port. Possible values include: 'TCP', 'UDP' + TransportProtocol TransportProtocol `json:"transportProtocol,omitempty"` + // BackendPort - Backend port of the target virtual machine. + BackendPort *int32 `json:"backendPort,omitempty"` +} + +// PortFragment properties of a network port. +type PortFragment struct { + // TransportProtocol - Protocol type of the port. Possible values include: 'TCP', 'UDP' + TransportProtocol TransportProtocol `json:"transportProtocol,omitempty"` + // BackendPort - Backend port of the target virtual machine. + BackendPort *int32 `json:"backendPort,omitempty"` +} + +// ProviderOperationResult result of the request to list REST API operations +type ProviderOperationResult struct { + autorest.Response `json:"-"` + // Value - List of operations supported by the resource provider. + Value *[]OperationMetadata `json:"value,omitempty"` + // NextLink - READ-ONLY; URL to get the next set of operation list results if there are any. + NextLink *string `json:"nextLink,omitempty"` +} + +// ProviderOperationResultIterator provides access to a complete listing of OperationMetadata values. +type ProviderOperationResultIterator struct { + i int + page ProviderOperationResultPage +} + +// 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 *ProviderOperationResultIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ProviderOperationResultIterator.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 *ProviderOperationResultIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ProviderOperationResultIterator) 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 ProviderOperationResultIterator) Response() ProviderOperationResult { + 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 ProviderOperationResultIterator) Value() OperationMetadata { + if !iter.page.NotDone() { + return OperationMetadata{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ProviderOperationResultIterator type. +func NewProviderOperationResultIterator(page ProviderOperationResultPage) ProviderOperationResultIterator { + return ProviderOperationResultIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (por ProviderOperationResult) IsEmpty() bool { + return por.Value == nil || len(*por.Value) == 0 +} + +// providerOperationResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (por ProviderOperationResult) providerOperationResultPreparer(ctx context.Context) (*http.Request, error) { + if por.NextLink == nil || len(to.String(por.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(por.NextLink))) +} + +// ProviderOperationResultPage contains a page of OperationMetadata values. +type ProviderOperationResultPage struct { + fn func(context.Context, ProviderOperationResult) (ProviderOperationResult, error) + por ProviderOperationResult +} + +// 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 *ProviderOperationResultPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ProviderOperationResultPage.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.por) + if err != nil { + return err + } + page.por = 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 *ProviderOperationResultPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ProviderOperationResultPage) NotDone() bool { + return !page.por.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ProviderOperationResultPage) Response() ProviderOperationResult { + return page.por +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ProviderOperationResultPage) Values() []OperationMetadata { + if page.por.IsEmpty() { + return nil + } + return *page.por.Value +} + +// Creates a new instance of the ProviderOperationResultPage type. +func NewProviderOperationResultPage(getNextPage func(context.Context, ProviderOperationResult) (ProviderOperationResult, error)) ProviderOperationResultPage { + return ProviderOperationResultPage{fn: getNextPage} +} + +// RdpConnection represents a .rdp file +type RdpConnection struct { + autorest.Response `json:"-"` + // Contents - The contents of the .rdp file + Contents *string `json:"contents,omitempty"` +} + +// ResizeLabVirtualMachineProperties request body for resizing a virtual machine. +type ResizeLabVirtualMachineProperties struct { + // Size - Specifies the size of the virtual machine. + Size *string `json:"size,omitempty"` +} + +// Resource an Azure resource. +type Resource struct { + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if r.Location != nil { + objectMap["location"] = r.Location + } + if r.Tags != nil { + objectMap["tags"] = r.Tags + } + return json.Marshal(objectMap) +} + +// RetargetScheduleProperties properties for retargeting a virtual machine schedule. +type RetargetScheduleProperties struct { + // CurrentResourceID - The resource Id of the virtual machine on which the schedule operates + CurrentResourceID *string `json:"currentResourceId,omitempty"` + // TargetResourceID - The resource Id of the virtual machine that the schedule should be retargeted to + TargetResourceID *string `json:"targetResourceId,omitempty"` +} + +// Schedule a schedule. +type Schedule struct { + autorest.Response `json:"-"` + // ScheduleProperties - The properties of the resource. + *ScheduleProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Schedule. +func (s Schedule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if s.ScheduleProperties != nil { + objectMap["properties"] = s.ScheduleProperties + } + if s.Location != nil { + objectMap["location"] = s.Location + } + if s.Tags != nil { + objectMap["tags"] = s.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Schedule struct. +func (s *Schedule) 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 scheduleProperties ScheduleProperties + err = json.Unmarshal(*v, &scheduleProperties) + if err != nil { + return err + } + s.ScheduleProperties = &scheduleProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + s.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + s.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + s.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + s.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + s.Tags = tags + } + } + } + + return nil +} + +// ScheduleCreationParameter properties for creating a schedule. +type ScheduleCreationParameter struct { + // ScheduleCreationParameterProperties - The properties of the schedule. + *ScheduleCreationParameterProperties `json:"properties,omitempty"` + // Name - The name of the virtual machine or environment + Name *string `json:"name,omitempty"` + // Location - The location of the new virtual machine or environment + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ScheduleCreationParameter. +func (scp ScheduleCreationParameter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if scp.ScheduleCreationParameterProperties != nil { + objectMap["properties"] = scp.ScheduleCreationParameterProperties + } + if scp.Name != nil { + objectMap["name"] = scp.Name + } + if scp.Location != nil { + objectMap["location"] = scp.Location + } + if scp.Tags != nil { + objectMap["tags"] = scp.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ScheduleCreationParameter struct. +func (scp *ScheduleCreationParameter) 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 scheduleCreationParameterProperties ScheduleCreationParameterProperties + err = json.Unmarshal(*v, &scheduleCreationParameterProperties) + if err != nil { + return err + } + scp.ScheduleCreationParameterProperties = &scheduleCreationParameterProperties + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + scp.Name = &name + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + scp.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + scp.Tags = tags + } + } + } + + return nil +} + +// ScheduleCreationParameterFragment properties for creating a schedule. +type ScheduleCreationParameterFragment struct { + // ScheduleCreationParameterPropertiesFragment - The properties of the schedule. + *ScheduleCreationParameterPropertiesFragment `json:"properties,omitempty"` + // Name - The name of the virtual machine or environment + Name *string `json:"name,omitempty"` + // Location - The location of the new virtual machine or environment + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ScheduleCreationParameterFragment. +func (scpf ScheduleCreationParameterFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if scpf.ScheduleCreationParameterPropertiesFragment != nil { + objectMap["properties"] = scpf.ScheduleCreationParameterPropertiesFragment + } + if scpf.Name != nil { + objectMap["name"] = scpf.Name + } + if scpf.Location != nil { + objectMap["location"] = scpf.Location + } + if scpf.Tags != nil { + objectMap["tags"] = scpf.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ScheduleCreationParameterFragment struct. +func (scpf *ScheduleCreationParameterFragment) 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 scheduleCreationParameterPropertiesFragment ScheduleCreationParameterPropertiesFragment + err = json.Unmarshal(*v, &scheduleCreationParameterPropertiesFragment) + if err != nil { + return err + } + scpf.ScheduleCreationParameterPropertiesFragment = &scheduleCreationParameterPropertiesFragment + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + scpf.Name = &name + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + scpf.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + scpf.Tags = tags + } + } + } + + return nil +} + +// ScheduleCreationParameterProperties properties for schedule creation. +type ScheduleCreationParameterProperties struct { + // Status - The status of the schedule (i.e. Enabled, Disabled). Possible values include: 'EnableStatusEnabled', 'EnableStatusDisabled' + Status EnableStatus `json:"status,omitempty"` + // TaskType - The task type of the schedule (e.g. LabVmsShutdownTask, LabVmAutoStart). + TaskType *string `json:"taskType,omitempty"` + // WeeklyRecurrence - If the schedule will occur only some days of the week, specify the weekly recurrence. + WeeklyRecurrence *WeekDetails `json:"weeklyRecurrence,omitempty"` + // DailyRecurrence - If the schedule will occur once each day of the week, specify the daily recurrence. + DailyRecurrence *DayDetails `json:"dailyRecurrence,omitempty"` + // HourlyRecurrence - If the schedule will occur multiple times a day, specify the hourly recurrence. + HourlyRecurrence *HourDetails `json:"hourlyRecurrence,omitempty"` + // TimeZoneID - The time zone ID (e.g. Pacific Standard time). + TimeZoneID *string `json:"timeZoneId,omitempty"` + // NotificationSettings - Notification settings. + NotificationSettings *NotificationSettings `json:"notificationSettings,omitempty"` + // TargetResourceID - The resource ID to which the schedule belongs + TargetResourceID *string `json:"targetResourceId,omitempty"` +} + +// ScheduleCreationParameterPropertiesFragment properties for schedule creation. +type ScheduleCreationParameterPropertiesFragment struct { + // Status - The status of the schedule (i.e. Enabled, Disabled). Possible values include: 'EnableStatusEnabled', 'EnableStatusDisabled' + Status EnableStatus `json:"status,omitempty"` + // TaskType - The task type of the schedule (e.g. LabVmsShutdownTask, LabVmAutoStart). + TaskType *string `json:"taskType,omitempty"` + // WeeklyRecurrence - If the schedule will occur only some days of the week, specify the weekly recurrence. + WeeklyRecurrence *WeekDetailsFragment `json:"weeklyRecurrence,omitempty"` + // DailyRecurrence - If the schedule will occur once each day of the week, specify the daily recurrence. + DailyRecurrence *DayDetailsFragment `json:"dailyRecurrence,omitempty"` + // HourlyRecurrence - If the schedule will occur multiple times a day, specify the hourly recurrence. + HourlyRecurrence *HourDetailsFragment `json:"hourlyRecurrence,omitempty"` + // TimeZoneID - The time zone ID (e.g. Pacific Standard time). + TimeZoneID *string `json:"timeZoneId,omitempty"` + // NotificationSettings - Notification settings. + NotificationSettings *NotificationSettingsFragment `json:"notificationSettings,omitempty"` + // TargetResourceID - The resource ID to which the schedule belongs + TargetResourceID *string `json:"targetResourceId,omitempty"` +} + +// ScheduleFragment a schedule. +type ScheduleFragment struct { + // SchedulePropertiesFragment - The properties of the resource. + *SchedulePropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ScheduleFragment. +func (sf ScheduleFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if sf.SchedulePropertiesFragment != nil { + objectMap["properties"] = sf.SchedulePropertiesFragment + } + if sf.Tags != nil { + objectMap["tags"] = sf.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ScheduleFragment struct. +func (sf *ScheduleFragment) 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 schedulePropertiesFragment SchedulePropertiesFragment + err = json.Unmarshal(*v, &schedulePropertiesFragment) + if err != nil { + return err + } + sf.SchedulePropertiesFragment = &schedulePropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + sf.Tags = tags + } + } + } + + return nil +} + +// ScheduleList the response of a list operation. +type ScheduleList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]Schedule `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ScheduleListIterator provides access to a complete listing of Schedule values. +type ScheduleListIterator struct { + i int + page ScheduleListPage +} + +// 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 *ScheduleListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ScheduleListIterator.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 *ScheduleListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ScheduleListIterator) 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 ScheduleListIterator) Response() ScheduleList { + 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 ScheduleListIterator) Value() Schedule { + if !iter.page.NotDone() { + return Schedule{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ScheduleListIterator type. +func NewScheduleListIterator(page ScheduleListPage) ScheduleListIterator { + return ScheduleListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (sl ScheduleList) IsEmpty() bool { + return sl.Value == nil || len(*sl.Value) == 0 +} + +// scheduleListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (sl ScheduleList) scheduleListPreparer(ctx context.Context) (*http.Request, error) { + if sl.NextLink == nil || len(to.String(sl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(sl.NextLink))) +} + +// ScheduleListPage contains a page of Schedule values. +type ScheduleListPage struct { + fn func(context.Context, ScheduleList) (ScheduleList, error) + sl ScheduleList +} + +// 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 *ScheduleListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ScheduleListPage.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.sl) + if err != nil { + return err + } + page.sl = 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 *ScheduleListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ScheduleListPage) NotDone() bool { + return !page.sl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ScheduleListPage) Response() ScheduleList { + return page.sl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ScheduleListPage) Values() []Schedule { + if page.sl.IsEmpty() { + return nil + } + return *page.sl.Value +} + +// Creates a new instance of the ScheduleListPage type. +func NewScheduleListPage(getNextPage func(context.Context, ScheduleList) (ScheduleList, error)) ScheduleListPage { + return ScheduleListPage{fn: getNextPage} +} + +// ScheduleProperties properties of a schedule. +type ScheduleProperties struct { + // Status - The status of the schedule (i.e. Enabled, Disabled). Possible values include: 'EnableStatusEnabled', 'EnableStatusDisabled' + Status EnableStatus `json:"status,omitempty"` + // TaskType - The task type of the schedule (e.g. LabVmsShutdownTask, LabVmAutoStart). + TaskType *string `json:"taskType,omitempty"` + // WeeklyRecurrence - If the schedule will occur only some days of the week, specify the weekly recurrence. + WeeklyRecurrence *WeekDetails `json:"weeklyRecurrence,omitempty"` + // DailyRecurrence - If the schedule will occur once each day of the week, specify the daily recurrence. + DailyRecurrence *DayDetails `json:"dailyRecurrence,omitempty"` + // HourlyRecurrence - If the schedule will occur multiple times a day, specify the hourly recurrence. + HourlyRecurrence *HourDetails `json:"hourlyRecurrence,omitempty"` + // TimeZoneID - The time zone ID (e.g. Pacific Standard time). + TimeZoneID *string `json:"timeZoneId,omitempty"` + // NotificationSettings - Notification settings. + NotificationSettings *NotificationSettings `json:"notificationSettings,omitempty"` + // CreatedDate - READ-ONLY; The creation date of the schedule. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // TargetResourceID - The resource ID to which the schedule belongs + TargetResourceID *string `json:"targetResourceId,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// SchedulePropertiesFragment properties of a schedule. +type SchedulePropertiesFragment struct { + // Status - The status of the schedule (i.e. Enabled, Disabled). Possible values include: 'EnableStatusEnabled', 'EnableStatusDisabled' + Status EnableStatus `json:"status,omitempty"` + // TaskType - The task type of the schedule (e.g. LabVmsShutdownTask, LabVmAutoStart). + TaskType *string `json:"taskType,omitempty"` + // WeeklyRecurrence - If the schedule will occur only some days of the week, specify the weekly recurrence. + WeeklyRecurrence *WeekDetailsFragment `json:"weeklyRecurrence,omitempty"` + // DailyRecurrence - If the schedule will occur once each day of the week, specify the daily recurrence. + DailyRecurrence *DayDetailsFragment `json:"dailyRecurrence,omitempty"` + // HourlyRecurrence - If the schedule will occur multiple times a day, specify the hourly recurrence. + HourlyRecurrence *HourDetailsFragment `json:"hourlyRecurrence,omitempty"` + // TimeZoneID - The time zone ID (e.g. Pacific Standard time). + TimeZoneID *string `json:"timeZoneId,omitempty"` + // NotificationSettings - Notification settings. + NotificationSettings *NotificationSettingsFragment `json:"notificationSettings,omitempty"` + // TargetResourceID - The resource ID to which the schedule belongs + TargetResourceID *string `json:"targetResourceId,omitempty"` +} + +// SchedulesExecuteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type SchedulesExecuteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *SchedulesExecuteFuture) Result(client SchedulesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesExecuteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.SchedulesExecuteFuture") + return + } + ar.Response = future.Response() + return +} + +// Secret a secret. +type Secret struct { + autorest.Response `json:"-"` + // SecretProperties - The properties of the resource. + *SecretProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Secret. +func (s Secret) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if s.SecretProperties != nil { + objectMap["properties"] = s.SecretProperties + } + if s.Location != nil { + objectMap["location"] = s.Location + } + if s.Tags != nil { + objectMap["tags"] = s.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Secret struct. +func (s *Secret) 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 secretProperties SecretProperties + err = json.Unmarshal(*v, &secretProperties) + if err != nil { + return err + } + s.SecretProperties = &secretProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + s.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + s.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + s.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + s.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + s.Tags = tags + } + } + } + + return nil +} + +// SecretFragment a secret. +type SecretFragment struct { + // SecretPropertiesFragment - The properties of the resource. + *SecretPropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for SecretFragment. +func (sf SecretFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if sf.SecretPropertiesFragment != nil { + objectMap["properties"] = sf.SecretPropertiesFragment + } + if sf.Tags != nil { + objectMap["tags"] = sf.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for SecretFragment struct. +func (sf *SecretFragment) 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 secretPropertiesFragment SecretPropertiesFragment + err = json.Unmarshal(*v, &secretPropertiesFragment) + if err != nil { + return err + } + sf.SecretPropertiesFragment = &secretPropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + sf.Tags = tags + } + } + } + + return nil +} + +// SecretList the response of a list operation. +type SecretList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]Secret `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// SecretListIterator provides access to a complete listing of Secret values. +type SecretListIterator struct { + i int + page SecretListPage +} + +// 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 *SecretListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SecretListIterator.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 *SecretListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter SecretListIterator) 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 SecretListIterator) Response() SecretList { + 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 SecretListIterator) Value() Secret { + if !iter.page.NotDone() { + return Secret{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the SecretListIterator type. +func NewSecretListIterator(page SecretListPage) SecretListIterator { + return SecretListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (sl SecretList) IsEmpty() bool { + return sl.Value == nil || len(*sl.Value) == 0 +} + +// secretListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (sl SecretList) secretListPreparer(ctx context.Context) (*http.Request, error) { + if sl.NextLink == nil || len(to.String(sl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(sl.NextLink))) +} + +// SecretListPage contains a page of Secret values. +type SecretListPage struct { + fn func(context.Context, SecretList) (SecretList, error) + sl SecretList +} + +// 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 *SecretListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SecretListPage.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.sl) + if err != nil { + return err + } + page.sl = 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 *SecretListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page SecretListPage) NotDone() bool { + return !page.sl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page SecretListPage) Response() SecretList { + return page.sl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page SecretListPage) Values() []Secret { + if page.sl.IsEmpty() { + return nil + } + return *page.sl.Value +} + +// Creates a new instance of the SecretListPage type. +func NewSecretListPage(getNextPage func(context.Context, SecretList) (SecretList, error)) SecretListPage { + return SecretListPage{fn: getNextPage} +} + +// SecretProperties properties of a secret. +type SecretProperties struct { + // Value - The value of the secret for secret creation. + Value *string `json:"value,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// SecretPropertiesFragment properties of a secret. +type SecretPropertiesFragment struct { + // Value - The value of the secret for secret creation. + Value *string `json:"value,omitempty"` +} + +// SecretsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type SecretsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *SecretsCreateOrUpdateFuture) Result(client SecretsClient) (s Secret, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SecretsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.SecretsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { + s, err = client.CreateOrUpdateResponder(s.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SecretsCreateOrUpdateFuture", "Result", s.Response.Response, "Failure responding to request") + } + } + return +} + +// ServiceFabric a Service Fabric. +type ServiceFabric struct { + autorest.Response `json:"-"` + // ServiceFabricProperties - The properties of the resource. + *ServiceFabricProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ServiceFabric. +func (sf ServiceFabric) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if sf.ServiceFabricProperties != nil { + objectMap["properties"] = sf.ServiceFabricProperties + } + if sf.Location != nil { + objectMap["location"] = sf.Location + } + if sf.Tags != nil { + objectMap["tags"] = sf.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ServiceFabric struct. +func (sf *ServiceFabric) 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 serviceFabricProperties ServiceFabricProperties + err = json.Unmarshal(*v, &serviceFabricProperties) + if err != nil { + return err + } + sf.ServiceFabricProperties = &serviceFabricProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + sf.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + sf.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + sf.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + sf.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + sf.Tags = tags + } + } + } + + return nil +} + +// ServiceFabricFragment a Service Fabric. +type ServiceFabricFragment struct { + // ServiceFabricPropertiesFragment - The properties of the resource. + *ServiceFabricPropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ServiceFabricFragment. +func (sff ServiceFabricFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if sff.ServiceFabricPropertiesFragment != nil { + objectMap["properties"] = sff.ServiceFabricPropertiesFragment + } + if sff.Tags != nil { + objectMap["tags"] = sff.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ServiceFabricFragment struct. +func (sff *ServiceFabricFragment) 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 serviceFabricPropertiesFragment ServiceFabricPropertiesFragment + err = json.Unmarshal(*v, &serviceFabricPropertiesFragment) + if err != nil { + return err + } + sff.ServiceFabricPropertiesFragment = &serviceFabricPropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + sff.Tags = tags + } + } + } + + return nil +} + +// ServiceFabricList the response of a list operation. +type ServiceFabricList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]ServiceFabric `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ServiceFabricListIterator provides access to a complete listing of ServiceFabric values. +type ServiceFabricListIterator struct { + i int + page ServiceFabricListPage +} + +// 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 *ServiceFabricListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricListIterator.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 *ServiceFabricListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ServiceFabricListIterator) 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 ServiceFabricListIterator) Response() ServiceFabricList { + 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 ServiceFabricListIterator) Value() ServiceFabric { + if !iter.page.NotDone() { + return ServiceFabric{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ServiceFabricListIterator type. +func NewServiceFabricListIterator(page ServiceFabricListPage) ServiceFabricListIterator { + return ServiceFabricListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (sfl ServiceFabricList) IsEmpty() bool { + return sfl.Value == nil || len(*sfl.Value) == 0 +} + +// serviceFabricListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (sfl ServiceFabricList) serviceFabricListPreparer(ctx context.Context) (*http.Request, error) { + if sfl.NextLink == nil || len(to.String(sfl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(sfl.NextLink))) +} + +// ServiceFabricListPage contains a page of ServiceFabric values. +type ServiceFabricListPage struct { + fn func(context.Context, ServiceFabricList) (ServiceFabricList, error) + sfl ServiceFabricList +} + +// 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 *ServiceFabricListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricListPage.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.sfl) + if err != nil { + return err + } + page.sfl = 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 *ServiceFabricListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ServiceFabricListPage) NotDone() bool { + return !page.sfl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ServiceFabricListPage) Response() ServiceFabricList { + return page.sfl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ServiceFabricListPage) Values() []ServiceFabric { + if page.sfl.IsEmpty() { + return nil + } + return *page.sfl.Value +} + +// Creates a new instance of the ServiceFabricListPage type. +func NewServiceFabricListPage(getNextPage func(context.Context, ServiceFabricList) (ServiceFabricList, error)) ServiceFabricListPage { + return ServiceFabricListPage{fn: getNextPage} +} + +// ServiceFabricProperties properties of a service fabric. +type ServiceFabricProperties struct { + // ExternalServiceFabricID - The backing service fabric resource's id + ExternalServiceFabricID *string `json:"externalServiceFabricId,omitempty"` + // EnvironmentID - The resource id of the environment under which the service fabric resource is present + EnvironmentID *string `json:"environmentId,omitempty"` + // ApplicableSchedule - READ-ONLY; The applicable schedule for the virtual machine. + ApplicableSchedule *ApplicableSchedule `json:"applicableSchedule,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// ServiceFabricPropertiesFragment properties of a service fabric. +type ServiceFabricPropertiesFragment struct { + // ExternalServiceFabricID - The backing service fabric resource's id + ExternalServiceFabricID *string `json:"externalServiceFabricId,omitempty"` + // EnvironmentID - The resource id of the environment under which the service fabric resource is present + EnvironmentID *string `json:"environmentId,omitempty"` +} + +// ServiceFabricSchedulesExecuteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ServiceFabricSchedulesExecuteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ServiceFabricSchedulesExecuteFuture) Result(client ServiceFabricSchedulesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesExecuteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.ServiceFabricSchedulesExecuteFuture") + return + } + ar.Response = future.Response() + return +} + +// ServiceFabricsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type ServiceFabricsCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ServiceFabricsCreateOrUpdateFuture) Result(client ServiceFabricsClient) (sf ServiceFabric, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.ServiceFabricsCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if sf.Response.Response, err = future.GetResult(sender); err == nil && sf.Response.Response.StatusCode != http.StatusNoContent { + sf, err = client.CreateOrUpdateResponder(sf.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsCreateOrUpdateFuture", "Result", sf.Response.Response, "Failure responding to request") + } + } + return +} + +// ServiceFabricsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ServiceFabricsDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ServiceFabricsDeleteFuture) Result(client ServiceFabricsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.ServiceFabricsDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// ServiceFabricsStartFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ServiceFabricsStartFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ServiceFabricsStartFuture) Result(client ServiceFabricsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsStartFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.ServiceFabricsStartFuture") + return + } + ar.Response = future.Response() + return +} + +// ServiceFabricsStopFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type ServiceFabricsStopFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *ServiceFabricsStopFuture) Result(client ServiceFabricsClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsStopFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.ServiceFabricsStopFuture") + return + } + ar.Response = future.Response() + return +} + +// ServiceRunner a container for a managed identity to execute DevTest lab services. +type ServiceRunner struct { + autorest.Response `json:"-"` + // Identity - The identity of the resource. + Identity *IdentityProperties `json:"identity,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for ServiceRunner. +func (sr ServiceRunner) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if sr.Identity != nil { + objectMap["identity"] = sr.Identity + } + if sr.Location != nil { + objectMap["location"] = sr.Location + } + if sr.Tags != nil { + objectMap["tags"] = sr.Tags + } + return json.Marshal(objectMap) +} + +// ServiceRunnerList the response of a list operation. +type ServiceRunnerList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]ServiceRunner `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ServiceRunnerListIterator provides access to a complete listing of ServiceRunner values. +type ServiceRunnerListIterator struct { + i int + page ServiceRunnerListPage +} + +// 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 *ServiceRunnerListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRunnerListIterator.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 *ServiceRunnerListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ServiceRunnerListIterator) 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 ServiceRunnerListIterator) Response() ServiceRunnerList { + 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 ServiceRunnerListIterator) Value() ServiceRunner { + if !iter.page.NotDone() { + return ServiceRunner{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the ServiceRunnerListIterator type. +func NewServiceRunnerListIterator(page ServiceRunnerListPage) ServiceRunnerListIterator { + return ServiceRunnerListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (srl ServiceRunnerList) IsEmpty() bool { + return srl.Value == nil || len(*srl.Value) == 0 +} + +// serviceRunnerListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (srl ServiceRunnerList) serviceRunnerListPreparer(ctx context.Context) (*http.Request, error) { + if srl.NextLink == nil || len(to.String(srl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(srl.NextLink))) +} + +// ServiceRunnerListPage contains a page of ServiceRunner values. +type ServiceRunnerListPage struct { + fn func(context.Context, ServiceRunnerList) (ServiceRunnerList, error) + srl ServiceRunnerList +} + +// 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 *ServiceRunnerListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRunnerListPage.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.srl) + if err != nil { + return err + } + page.srl = 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 *ServiceRunnerListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ServiceRunnerListPage) NotDone() bool { + return !page.srl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ServiceRunnerListPage) Response() ServiceRunnerList { + return page.srl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ServiceRunnerListPage) Values() []ServiceRunner { + if page.srl.IsEmpty() { + return nil + } + return *page.srl.Value +} + +// Creates a new instance of the ServiceRunnerListPage type. +func NewServiceRunnerListPage(getNextPage func(context.Context, ServiceRunnerList) (ServiceRunnerList, error)) ServiceRunnerListPage { + return ServiceRunnerListPage{fn: getNextPage} +} + +// SharedPublicIPAddressConfiguration properties of a virtual machine that determine how it is connected to +// a load balancer. +type SharedPublicIPAddressConfiguration struct { + // InboundNatRules - The incoming NAT rules + InboundNatRules *[]InboundNatRule `json:"inboundNatRules,omitempty"` +} + +// SharedPublicIPAddressConfigurationFragment properties of a virtual machine that determine how it is +// connected to a load balancer. +type SharedPublicIPAddressConfigurationFragment struct { + // InboundNatRules - The incoming NAT rules + InboundNatRules *[]InboundNatRuleFragment `json:"inboundNatRules,omitempty"` +} + +// ShutdownNotificationContent the contents of a shutdown notification. Webhooks can use this type to +// deserialize the request body when they get notified of an imminent shutdown. +type ShutdownNotificationContent struct { + // SkipURL - The URL to skip auto-shutdown. + SkipURL *string `json:"skipUrl,omitempty"` + // DelayURL60 - The URL to delay shutdown by 60 minutes. + DelayURL60 *string `json:"delayUrl60,omitempty"` + // DelayURL120 - The URL to delay shutdown by 2 hours. + DelayURL120 *string `json:"delayUrl120,omitempty"` + // VMName - The virtual machine to be shut down. + VMName *string `json:"vmName,omitempty"` + // GUID - The GUID for the virtual machine to be shut down. + GUID *string `json:"guid,omitempty"` + // Owner - The owner of the virtual machine. + Owner *string `json:"owner,omitempty"` + // VMURL - The URL of the virtual machine. + VMURL *string `json:"vmUrl,omitempty"` + // MinutesUntilShutdown - Minutes remaining until shutdown + MinutesUntilShutdown *string `json:"minutesUntilShutdown,omitempty"` + // EventType - The event for which a notification will be sent. + EventType *string `json:"eventType,omitempty"` + // Text - The text for the notification. + Text *string `json:"text,omitempty"` + // SubscriptionID - The subscription ID for the schedule. + SubscriptionID *string `json:"subscriptionId,omitempty"` + // ResourceGroupName - The resource group name for the schedule. + ResourceGroupName *string `json:"resourceGroupName,omitempty"` + // LabName - The lab for the schedule. + LabName *string `json:"labName,omitempty"` +} + +// Subnet subnet information. +type Subnet struct { + // ResourceID - The resource ID of the subnet. + ResourceID *string `json:"resourceId,omitempty"` + // LabSubnetName - The name of the subnet as seen in the lab. + LabSubnetName *string `json:"labSubnetName,omitempty"` + // AllowPublicIP - The permission policy of the subnet for allowing public IP addresses (i.e. Allow, Deny)). Possible values include: 'Default', 'Deny', 'Allow' + AllowPublicIP UsagePermissionType `json:"allowPublicIp,omitempty"` +} + +// SubnetFragment subnet information. +type SubnetFragment struct { + // ResourceID - The resource ID of the subnet. + ResourceID *string `json:"resourceId,omitempty"` + // LabSubnetName - The name of the subnet as seen in the lab. + LabSubnetName *string `json:"labSubnetName,omitempty"` + // AllowPublicIP - The permission policy of the subnet for allowing public IP addresses (i.e. Allow, Deny)). Possible values include: 'Default', 'Deny', 'Allow' + AllowPublicIP UsagePermissionType `json:"allowPublicIp,omitempty"` +} + +// SubnetOverride property overrides on a subnet of a virtual network. +type SubnetOverride struct { + // ResourceID - The resource ID of the subnet. + ResourceID *string `json:"resourceId,omitempty"` + // LabSubnetName - The name given to the subnet within the lab. + LabSubnetName *string `json:"labSubnetName,omitempty"` + // UseInVMCreationPermission - Indicates whether this subnet can be used during virtual machine creation (i.e. Allow, Deny). Possible values include: 'Default', 'Deny', 'Allow' + UseInVMCreationPermission UsagePermissionType `json:"useInVmCreationPermission,omitempty"` + // UsePublicIPAddressPermission - Indicates whether public IP addresses can be assigned to virtual machines on this subnet (i.e. Allow, Deny). Possible values include: 'Default', 'Deny', 'Allow' + UsePublicIPAddressPermission UsagePermissionType `json:"usePublicIpAddressPermission,omitempty"` + // SharedPublicIPAddressConfiguration - Properties that virtual machines on this subnet will share. + SharedPublicIPAddressConfiguration *SubnetSharedPublicIPAddressConfiguration `json:"sharedPublicIpAddressConfiguration,omitempty"` + // VirtualNetworkPoolName - The virtual network pool associated with this subnet. + VirtualNetworkPoolName *string `json:"virtualNetworkPoolName,omitempty"` +} + +// SubnetOverrideFragment property overrides on a subnet of a virtual network. +type SubnetOverrideFragment struct { + // ResourceID - The resource ID of the subnet. + ResourceID *string `json:"resourceId,omitempty"` + // LabSubnetName - The name given to the subnet within the lab. + LabSubnetName *string `json:"labSubnetName,omitempty"` + // UseInVMCreationPermission - Indicates whether this subnet can be used during virtual machine creation (i.e. Allow, Deny). Possible values include: 'Default', 'Deny', 'Allow' + UseInVMCreationPermission UsagePermissionType `json:"useInVmCreationPermission,omitempty"` + // UsePublicIPAddressPermission - Indicates whether public IP addresses can be assigned to virtual machines on this subnet (i.e. Allow, Deny). Possible values include: 'Default', 'Deny', 'Allow' + UsePublicIPAddressPermission UsagePermissionType `json:"usePublicIpAddressPermission,omitempty"` + // SharedPublicIPAddressConfiguration - Properties that virtual machines on this subnet will share. + SharedPublicIPAddressConfiguration *SubnetSharedPublicIPAddressConfigurationFragment `json:"sharedPublicIpAddressConfiguration,omitempty"` + // VirtualNetworkPoolName - The virtual network pool associated with this subnet. + VirtualNetworkPoolName *string `json:"virtualNetworkPoolName,omitempty"` +} + +// SubnetSharedPublicIPAddressConfiguration configuration for public IP address sharing. +type SubnetSharedPublicIPAddressConfiguration struct { + // AllowedPorts - Backend ports that virtual machines on this subnet are allowed to expose + AllowedPorts *[]Port `json:"allowedPorts,omitempty"` +} + +// SubnetSharedPublicIPAddressConfigurationFragment configuration for public IP address sharing. +type SubnetSharedPublicIPAddressConfigurationFragment struct { + // AllowedPorts - Backend ports that virtual machines on this subnet are allowed to expose + AllowedPorts *[]PortFragment `json:"allowedPorts,omitempty"` +} + +// TargetCostProperties properties of a cost target. +type TargetCostProperties struct { + // Status - Target cost status. Possible values include: 'TargetCostStatusEnabled', 'TargetCostStatusDisabled' + Status TargetCostStatus `json:"status,omitempty"` + // Target - Lab target cost + Target *int32 `json:"target,omitempty"` + // CostThresholds - Cost thresholds. + CostThresholds *[]CostThresholdProperties `json:"costThresholds,omitempty"` + // CycleStartDateTime - Reporting cycle start date. + CycleStartDateTime *date.Time `json:"cycleStartDateTime,omitempty"` + // CycleEndDateTime - Reporting cycle end date. + CycleEndDateTime *date.Time `json:"cycleEndDateTime,omitempty"` + // CycleType - Reporting cycle type. Possible values include: 'CalendarMonth', 'Custom' + CycleType ReportingCycleType `json:"cycleType,omitempty"` +} + +// UpdateResource represents an update resource +type UpdateResource struct { + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for UpdateResource. +func (ur UpdateResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ur.Tags != nil { + objectMap["tags"] = ur.Tags + } + return json.Marshal(objectMap) +} + +// User profile of a lab user. +type User struct { + autorest.Response `json:"-"` + // UserProperties - The properties of the resource. + *UserProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for User. +func (u User) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if u.UserProperties != nil { + objectMap["properties"] = u.UserProperties + } + if u.Location != nil { + objectMap["location"] = u.Location + } + if u.Tags != nil { + objectMap["tags"] = u.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for User struct. +func (u *User) 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 userProperties UserProperties + err = json.Unmarshal(*v, &userProperties) + if err != nil { + return err + } + u.UserProperties = &userProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + u.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + u.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + u.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + u.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + u.Tags = tags + } + } + } + + return nil +} + +// UserFragment profile of a lab user. +type UserFragment struct { + // UserPropertiesFragment - The properties of the resource. + *UserPropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for UserFragment. +func (uf UserFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if uf.UserPropertiesFragment != nil { + objectMap["properties"] = uf.UserPropertiesFragment + } + if uf.Tags != nil { + objectMap["tags"] = uf.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for UserFragment struct. +func (uf *UserFragment) 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 userPropertiesFragment UserPropertiesFragment + err = json.Unmarshal(*v, &userPropertiesFragment) + if err != nil { + return err + } + uf.UserPropertiesFragment = &userPropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + uf.Tags = tags + } + } + } + + return nil +} + +// UserIdentity identity attributes of a lab user. +type UserIdentity struct { + // PrincipalName - Set to the principal name / UPN of the client JWT making the request. + PrincipalName *string `json:"principalName,omitempty"` + // PrincipalID - Set to the principal Id of the client JWT making the request. Service principal will not have the principal Id. + PrincipalID *string `json:"principalId,omitempty"` + // TenantID - Set to the tenant ID of the client JWT making the request. + TenantID *string `json:"tenantId,omitempty"` + // ObjectID - Set to the object Id of the client JWT making the request. Not all users have object Id. For CSP (reseller) scenarios for example, object Id is not available. + ObjectID *string `json:"objectId,omitempty"` + // AppID - Set to the app Id of the client JWT making the request. + AppID *string `json:"appId,omitempty"` +} + +// UserIdentityFragment identity attributes of a lab user. +type UserIdentityFragment struct { + // PrincipalName - Set to the principal name / UPN of the client JWT making the request. + PrincipalName *string `json:"principalName,omitempty"` + // PrincipalID - Set to the principal Id of the client JWT making the request. Service principal will not have the principal Id. + PrincipalID *string `json:"principalId,omitempty"` + // TenantID - Set to the tenant ID of the client JWT making the request. + TenantID *string `json:"tenantId,omitempty"` + // ObjectID - Set to the object Id of the client JWT making the request. Not all users have object Id. For CSP (reseller) scenarios for example, object Id is not available. + ObjectID *string `json:"objectId,omitempty"` + // AppID - Set to the app Id of the client JWT making the request. + AppID *string `json:"appId,omitempty"` +} + +// UserList the response of a list operation. +type UserList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]User `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// UserListIterator provides access to a complete listing of User values. +type UserListIterator struct { + i int + page UserListPage +} + +// 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 *UserListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UserListIterator.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 *UserListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter UserListIterator) 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 UserListIterator) Response() UserList { + 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 UserListIterator) Value() User { + if !iter.page.NotDone() { + return User{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the UserListIterator type. +func NewUserListIterator(page UserListPage) UserListIterator { + return UserListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (ul UserList) IsEmpty() bool { + return ul.Value == nil || len(*ul.Value) == 0 +} + +// userListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (ul UserList) userListPreparer(ctx context.Context) (*http.Request, error) { + if ul.NextLink == nil || len(to.String(ul.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(ul.NextLink))) +} + +// UserListPage contains a page of User values. +type UserListPage struct { + fn func(context.Context, UserList) (UserList, error) + ul UserList +} + +// 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 *UserListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UserListPage.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.ul) + if err != nil { + return err + } + page.ul = 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 *UserListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page UserListPage) NotDone() bool { + return !page.ul.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page UserListPage) Response() UserList { + return page.ul +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page UserListPage) Values() []User { + if page.ul.IsEmpty() { + return nil + } + return *page.ul.Value +} + +// Creates a new instance of the UserListPage type. +func NewUserListPage(getNextPage func(context.Context, UserList) (UserList, error)) UserListPage { + return UserListPage{fn: getNextPage} +} + +// UserProperties properties of a lab user profile. +type UserProperties struct { + // Identity - The identity of the user. + Identity *UserIdentity `json:"identity,omitempty"` + // SecretStore - The secret store of the user. + SecretStore *UserSecretStore `json:"secretStore,omitempty"` + // CreatedDate - READ-ONLY; The creation date of the user profile. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// UserPropertiesFragment properties of a lab user profile. +type UserPropertiesFragment struct { + // Identity - The identity of the user. + Identity *UserIdentityFragment `json:"identity,omitempty"` + // SecretStore - The secret store of the user. + SecretStore *UserSecretStoreFragment `json:"secretStore,omitempty"` +} + +// UsersCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type UsersCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *UsersCreateOrUpdateFuture) Result(client UsersClient) (u User, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.UsersCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if u.Response.Response, err = future.GetResult(sender); err == nil && u.Response.Response.StatusCode != http.StatusNoContent { + u, err = client.CreateOrUpdateResponder(u.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersCreateOrUpdateFuture", "Result", u.Response.Response, "Failure responding to request") + } + } + return +} + +// UsersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type UsersDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *UsersDeleteFuture) Result(client UsersClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.UsersDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// UserSecretStore properties of a user's secret store. +type UserSecretStore struct { + // KeyVaultURI - The URI of the user's Key vault. + KeyVaultURI *string `json:"keyVaultUri,omitempty"` + // KeyVaultID - The ID of the user's Key vault. + KeyVaultID *string `json:"keyVaultId,omitempty"` +} + +// UserSecretStoreFragment properties of a user's secret store. +type UserSecretStoreFragment struct { + // KeyVaultURI - The URI of the user's Key vault. + KeyVaultURI *string `json:"keyVaultUri,omitempty"` + // KeyVaultID - The ID of the user's Key vault. + KeyVaultID *string `json:"keyVaultId,omitempty"` +} + +// VirtualMachinesAddDataDiskFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type VirtualMachinesAddDataDiskFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachinesAddDataDiskFuture) Result(client VirtualMachinesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesAddDataDiskFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachinesAddDataDiskFuture") + return + } + ar.Response = future.Response() + return +} + +// VirtualMachinesApplyArtifactsFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type VirtualMachinesApplyArtifactsFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachinesApplyArtifactsFuture) Result(client VirtualMachinesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesApplyArtifactsFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachinesApplyArtifactsFuture") + return + } + ar.Response = future.Response() + return +} + +// VirtualMachineSchedulesExecuteFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type VirtualMachineSchedulesExecuteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachineSchedulesExecuteFuture) Result(client VirtualMachineSchedulesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesExecuteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachineSchedulesExecuteFuture") + return + } + ar.Response = future.Response() + return +} + +// VirtualMachinesClaimFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type VirtualMachinesClaimFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachinesClaimFuture) Result(client VirtualMachinesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClaimFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachinesClaimFuture") + return + } + ar.Response = future.Response() + return +} + +// VirtualMachinesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type VirtualMachinesCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachinesCreateOrUpdateFuture) Result(client VirtualMachinesClient) (lvm LabVirtualMachine, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachinesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if lvm.Response.Response, err = future.GetResult(sender); err == nil && lvm.Response.Response.StatusCode != http.StatusNoContent { + lvm, err = client.CreateOrUpdateResponder(lvm.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesCreateOrUpdateFuture", "Result", lvm.Response.Response, "Failure responding to request") + } + } + return +} + +// VirtualMachinesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type VirtualMachinesDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachinesDeleteFuture) Result(client VirtualMachinesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachinesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// VirtualMachinesDetachDataDiskFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type VirtualMachinesDetachDataDiskFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachinesDetachDataDiskFuture) Result(client VirtualMachinesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesDetachDataDiskFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachinesDetachDataDiskFuture") + return + } + ar.Response = future.Response() + return +} + +// VirtualMachinesRedeployFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type VirtualMachinesRedeployFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachinesRedeployFuture) Result(client VirtualMachinesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesRedeployFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachinesRedeployFuture") + return + } + ar.Response = future.Response() + return +} + +// VirtualMachinesResizeFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type VirtualMachinesResizeFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachinesResizeFuture) Result(client VirtualMachinesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesResizeFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachinesResizeFuture") + return + } + ar.Response = future.Response() + return +} + +// VirtualMachinesRestartFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type VirtualMachinesRestartFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachinesRestartFuture) Result(client VirtualMachinesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesRestartFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachinesRestartFuture") + return + } + ar.Response = future.Response() + return +} + +// VirtualMachinesStartFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type VirtualMachinesStartFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachinesStartFuture) Result(client VirtualMachinesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesStartFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachinesStartFuture") + return + } + ar.Response = future.Response() + return +} + +// VirtualMachinesStopFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type VirtualMachinesStopFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachinesStopFuture) Result(client VirtualMachinesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesStopFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachinesStopFuture") + return + } + ar.Response = future.Response() + return +} + +// VirtualMachinesTransferDisksFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type VirtualMachinesTransferDisksFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachinesTransferDisksFuture) Result(client VirtualMachinesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesTransferDisksFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachinesTransferDisksFuture") + return + } + ar.Response = future.Response() + return +} + +// VirtualMachinesUnClaimFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type VirtualMachinesUnClaimFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualMachinesUnClaimFuture) Result(client VirtualMachinesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesUnClaimFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualMachinesUnClaimFuture") + return + } + ar.Response = future.Response() + return +} + +// VirtualNetwork a virtual network. +type VirtualNetwork struct { + autorest.Response `json:"-"` + // VirtualNetworkProperties - The properties of the resource. + *VirtualNetworkProperties `json:"properties,omitempty"` + // ID - READ-ONLY; The identifier of the resource. + ID *string `json:"id,omitempty"` + // Name - READ-ONLY; The name of the resource. + Name *string `json:"name,omitempty"` + // Type - READ-ONLY; The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for VirtualNetwork. +func (vn VirtualNetwork) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if vn.VirtualNetworkProperties != nil { + objectMap["properties"] = vn.VirtualNetworkProperties + } + if vn.Location != nil { + objectMap["location"] = vn.Location + } + if vn.Tags != nil { + objectMap["tags"] = vn.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for VirtualNetwork struct. +func (vn *VirtualNetwork) 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 virtualNetworkProperties VirtualNetworkProperties + err = json.Unmarshal(*v, &virtualNetworkProperties) + if err != nil { + return err + } + vn.VirtualNetworkProperties = &virtualNetworkProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + vn.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + vn.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + vn.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + vn.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + vn.Tags = tags + } + } + } + + return nil +} + +// VirtualNetworkFragment a virtual network. +type VirtualNetworkFragment struct { + // VirtualNetworkPropertiesFragment - The properties of the resource. + *VirtualNetworkPropertiesFragment `json:"properties,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for VirtualNetworkFragment. +func (vnf VirtualNetworkFragment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if vnf.VirtualNetworkPropertiesFragment != nil { + objectMap["properties"] = vnf.VirtualNetworkPropertiesFragment + } + if vnf.Tags != nil { + objectMap["tags"] = vnf.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for VirtualNetworkFragment struct. +func (vnf *VirtualNetworkFragment) 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 virtualNetworkPropertiesFragment VirtualNetworkPropertiesFragment + err = json.Unmarshal(*v, &virtualNetworkPropertiesFragment) + if err != nil { + return err + } + vnf.VirtualNetworkPropertiesFragment = &virtualNetworkPropertiesFragment + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + vnf.Tags = tags + } + } + } + + return nil +} + +// VirtualNetworkList the response of a list operation. +type VirtualNetworkList struct { + autorest.Response `json:"-"` + // Value - Results of the list operation. + Value *[]VirtualNetwork `json:"value,omitempty"` + // NextLink - Link for next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// VirtualNetworkListIterator provides access to a complete listing of VirtualNetwork values. +type VirtualNetworkListIterator struct { + i int + page VirtualNetworkListPage +} + +// 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 *VirtualNetworkListIterator) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkListIterator.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 *VirtualNetworkListIterator) Next() error { + return iter.NextWithContext(context.Background()) +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter VirtualNetworkListIterator) 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 VirtualNetworkListIterator) Response() VirtualNetworkList { + 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 VirtualNetworkListIterator) Value() VirtualNetwork { + if !iter.page.NotDone() { + return VirtualNetwork{} + } + return iter.page.Values()[iter.i] +} + +// Creates a new instance of the VirtualNetworkListIterator type. +func NewVirtualNetworkListIterator(page VirtualNetworkListPage) VirtualNetworkListIterator { + return VirtualNetworkListIterator{page: page} +} + +// IsEmpty returns true if the ListResult contains no values. +func (vnl VirtualNetworkList) IsEmpty() bool { + return vnl.Value == nil || len(*vnl.Value) == 0 +} + +// virtualNetworkListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (vnl VirtualNetworkList) virtualNetworkListPreparer(ctx context.Context) (*http.Request, error) { + if vnl.NextLink == nil || len(to.String(vnl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare((&http.Request{}).WithContext(ctx), + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(vnl.NextLink))) +} + +// VirtualNetworkListPage contains a page of VirtualNetwork values. +type VirtualNetworkListPage struct { + fn func(context.Context, VirtualNetworkList) (VirtualNetworkList, error) + vnl VirtualNetworkList +} + +// 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 *VirtualNetworkListPage) NextWithContext(ctx context.Context) (err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkListPage.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.vnl) + if err != nil { + return err + } + page.vnl = 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 *VirtualNetworkListPage) Next() error { + return page.NextWithContext(context.Background()) +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page VirtualNetworkListPage) NotDone() bool { + return !page.vnl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page VirtualNetworkListPage) Response() VirtualNetworkList { + return page.vnl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page VirtualNetworkListPage) Values() []VirtualNetwork { + if page.vnl.IsEmpty() { + return nil + } + return *page.vnl.Value +} + +// Creates a new instance of the VirtualNetworkListPage type. +func NewVirtualNetworkListPage(getNextPage func(context.Context, VirtualNetworkList) (VirtualNetworkList, error)) VirtualNetworkListPage { + return VirtualNetworkListPage{fn: getNextPage} +} + +// VirtualNetworkProperties properties of a virtual network. +type VirtualNetworkProperties struct { + // AllowedSubnets - The allowed subnets of the virtual network. + AllowedSubnets *[]Subnet `json:"allowedSubnets,omitempty"` + // Description - The description of the virtual network. + Description *string `json:"description,omitempty"` + // ExternalProviderResourceID - The Microsoft.Network resource identifier of the virtual network. + ExternalProviderResourceID *string `json:"externalProviderResourceId,omitempty"` + // ExternalSubnets - READ-ONLY; The external subnet properties. + ExternalSubnets *[]ExternalSubnet `json:"externalSubnets,omitempty"` + // SubnetOverrides - The subnet overrides of the virtual network. + SubnetOverrides *[]SubnetOverride `json:"subnetOverrides,omitempty"` + // CreatedDate - READ-ONLY; The creation date of the virtual network. + CreatedDate *date.Time `json:"createdDate,omitempty"` + // ProvisioningState - READ-ONLY; The provisioning status of the resource. + ProvisioningState *string `json:"provisioningState,omitempty"` + // UniqueIdentifier - READ-ONLY; The unique immutable identifier of a resource (Guid). + UniqueIdentifier *string `json:"uniqueIdentifier,omitempty"` +} + +// VirtualNetworkPropertiesFragment properties of a virtual network. +type VirtualNetworkPropertiesFragment struct { + // AllowedSubnets - The allowed subnets of the virtual network. + AllowedSubnets *[]SubnetFragment `json:"allowedSubnets,omitempty"` + // Description - The description of the virtual network. + Description *string `json:"description,omitempty"` + // ExternalProviderResourceID - The Microsoft.Network resource identifier of the virtual network. + ExternalProviderResourceID *string `json:"externalProviderResourceId,omitempty"` + // SubnetOverrides - The subnet overrides of the virtual network. + SubnetOverrides *[]SubnetOverrideFragment `json:"subnetOverrides,omitempty"` +} + +// VirtualNetworksCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type VirtualNetworksCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualNetworksCreateOrUpdateFuture) Result(client VirtualNetworksClient) (vn VirtualNetwork, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualNetworksCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if vn.Response.Response, err = future.GetResult(sender); err == nil && vn.Response.Response.StatusCode != http.StatusNoContent { + vn, err = client.CreateOrUpdateResponder(vn.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksCreateOrUpdateFuture", "Result", vn.Response.Response, "Failure responding to request") + } + } + return +} + +// VirtualNetworksDeleteFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type VirtualNetworksDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *VirtualNetworksDeleteFuture) Result(client VirtualNetworksClient) (ar autorest.Response, err error) { + var done bool + done, err = future.DoneWithContext(context.Background(), client) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("dtl.VirtualNetworksDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// WeekDetails properties of a weekly schedule. +type WeekDetails struct { + // Weekdays - The days of the week for which the schedule is set (e.g. Sunday, Monday, Tuesday, etc.). + Weekdays *[]string `json:"weekdays,omitempty"` + // Time - The time of the day the schedule will occur. + Time *string `json:"time,omitempty"` +} + +// WeekDetailsFragment properties of a weekly schedule. +type WeekDetailsFragment struct { + // Weekdays - The days of the week for which the schedule is set (e.g. Sunday, Monday, Tuesday, etc.). + Weekdays *[]string `json:"weekdays,omitempty"` + // Time - The time of the day the schedule will occur. + Time *string `json:"time,omitempty"` +} + +// WindowsOsInfo information about a Windows OS. +type WindowsOsInfo struct { + // WindowsOsState - The state of the Windows OS (i.e. NonSysprepped, SysprepRequested, SysprepApplied). Possible values include: 'NonSysprepped', 'SysprepRequested', 'SysprepApplied' + WindowsOsState WindowsOsState `json:"windowsOsState,omitempty"` +} + +// WindowsOsInfoFragment information about a Windows OS. +type WindowsOsInfoFragment struct { + // WindowsOsState - The state of the Windows OS (i.e. NonSysprepped, SysprepRequested, SysprepApplied). Possible values include: 'NonSysprepped', 'SysprepRequested', 'SysprepApplied' + WindowsOsState WindowsOsState `json:"windowsOsState,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/notificationchannels.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/notificationchannels.go new file mode 100644 index 000000000..40c7e0f64 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/notificationchannels.go @@ -0,0 +1,585 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// NotificationChannelsClient is the the DevTest Labs Client. +type NotificationChannelsClient struct { + BaseClient +} + +// NewNotificationChannelsClient creates an instance of the NotificationChannelsClient client. +func NewNotificationChannelsClient(subscriptionID string) NotificationChannelsClient { + return NewNotificationChannelsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewNotificationChannelsClientWithBaseURI creates an instance of the NotificationChannelsClient client. +func NewNotificationChannelsClientWithBaseURI(baseURI string, subscriptionID string) NotificationChannelsClient { + return NotificationChannelsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing notificationChannel. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the notificationChannel. +// notificationChannel - a notification. +func (client NotificationChannelsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, name string, notificationChannel NotificationChannel) (result NotificationChannel, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/NotificationChannelsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: notificationChannel, + Constraints: []validation.Constraint{{Target: "notificationChannel.NotificationChannelProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("dtl.NotificationChannelsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, name, notificationChannel) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client NotificationChannelsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, notificationChannel NotificationChannel) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/notificationchannels/{name}", pathParameters), + autorest.WithJSON(notificationChannel), + 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 NotificationChannelsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client NotificationChannelsClient) CreateOrUpdateResponder(resp *http.Response) (result NotificationChannel, 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 delete notification channel. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the notificationChannel. +func (client NotificationChannelsClient) Delete(ctx context.Context, resourceGroupName string, labName string, name string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/NotificationChannelsClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client NotificationChannelsClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels/{name}", 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 NotificationChannelsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client NotificationChannelsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get notification channel. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the notificationChannel. +// expand - specify the $expand query. Example: 'properties($select=webHookUrl)' +func (client NotificationChannelsClient) Get(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (result NotificationChannel, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/NotificationChannelsClient.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, labName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client NotificationChannelsClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/notificationchannels/{name}", 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 NotificationChannelsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client NotificationChannelsClient) GetResponder(resp *http.Response) (result NotificationChannel, 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 list notification channels in a given lab. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// expand - specify the $expand query. Example: 'properties($select=webHookUrl)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client NotificationChannelsClient) List(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result NotificationChannelListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/NotificationChannelsClient.List") + defer func() { + sc := -1 + if result.ncl.Response.Response != nil { + sc = result.ncl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.ncl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "List", resp, "Failure sending request") + return + } + + result.ncl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client NotificationChannelsClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels", 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 NotificationChannelsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client NotificationChannelsClient) ListResponder(resp *http.Response) (result NotificationChannelList, 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 NotificationChannelsClient) listNextResults(ctx context.Context, lastResults NotificationChannelList) (result NotificationChannelList, err error) { + req, err := lastResults.notificationChannelListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "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, "dtl.NotificationChannelsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client NotificationChannelsClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result NotificationChannelListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/NotificationChannelsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, expand, filter, top, orderby) + return +} + +// Notify send notification to provided channel. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the notificationChannel. +// notifyParameters - properties for generating a Notification. +func (client NotificationChannelsClient) Notify(ctx context.Context, resourceGroupName string, labName string, name string, notifyParameters NotifyParameters) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/NotificationChannelsClient.Notify") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.NotifyPreparer(ctx, resourceGroupName, labName, name, notifyParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "Notify", nil, "Failure preparing request") + return + } + + resp, err := client.NotifySender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "Notify", resp, "Failure sending request") + return + } + + result, err = client.NotifyResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "Notify", resp, "Failure responding to request") + } + + return +} + +// NotifyPreparer prepares the Notify request. +func (client NotificationChannelsClient) NotifyPreparer(ctx context.Context, resourceGroupName string, labName string, name string, notifyParameters NotifyParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels/{name}/notify", pathParameters), + autorest.WithJSON(notifyParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// NotifySender sends the Notify request. The method will close the +// http.Response Body if it receives an error. +func (client NotificationChannelsClient) NotifySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// NotifyResponder handles the response to the Notify request. The method always +// closes the http.Response Body. +func (client NotificationChannelsClient) NotifyResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Update modify properties of notification channels. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the notificationChannel. +// notificationChannel - a notification. +func (client NotificationChannelsClient) Update(ctx context.Context, resourceGroupName string, labName string, name string, notificationChannel NotificationChannelFragment) (result NotificationChannel, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/NotificationChannelsClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, name, notificationChannel) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.NotificationChannelsClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client NotificationChannelsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, notificationChannel NotificationChannelFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/notificationchannels/{name}", pathParameters), + autorest.WithJSON(notificationChannel), + 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 NotificationChannelsClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client NotificationChannelsClient) UpdateResponder(resp *http.Response) (result NotificationChannel, 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/devtestlabs/mgmt/2018-09-15/dtl/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/operations.go new file mode 100644 index 000000000..cf5bcd889 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/operations.go @@ -0,0 +1,118 @@ +package dtl + +// 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 DevTest Labs Client. +type OperationsClient struct { + BaseClient +} + +// NewOperationsClient creates an instance of the OperationsClient client. +func NewOperationsClient(subscriptionID string) OperationsClient { + return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client. +func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { + return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Get get operation. +// Parameters: +// locationName - the name of the location. +// name - the name of the operation. +func (client OperationsClient) Get(ctx context.Context, locationName string, name string) (result OperationResult, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.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, locationName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.OperationsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.OperationsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.OperationsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client OperationsClient) GetPreparer(ctx context.Context, locationName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "locationName": autorest.Encode("path", locationName), + "name": autorest.Encode("path", name), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.DevTestLab/locations/{locationName}/operations/{name}", 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 OperationsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client OperationsClient) GetResponder(resp *http.Response) (result OperationResult, 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/devtestlabs/mgmt/2018-09-15/dtl/policies.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/policies.go new file mode 100644 index 000000000..356d6ca01 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/policies.go @@ -0,0 +1,514 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// PoliciesClient is the the DevTest Labs Client. +type PoliciesClient struct { + BaseClient +} + +// NewPoliciesClient creates an instance of the PoliciesClient client. +func NewPoliciesClient(subscriptionID string) PoliciesClient { + return NewPoliciesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPoliciesClientWithBaseURI creates an instance of the PoliciesClient client. +func NewPoliciesClientWithBaseURI(baseURI string, subscriptionID string) PoliciesClient { + return PoliciesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing policy. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// policySetName - the name of the policy set. +// name - the name of the policy. +// policy - a Policy. +func (client PoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, policySetName string, name string, policy Policy) (result Policy, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PoliciesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: policy, + Constraints: []validation.Constraint{{Target: "policy.PolicyProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("dtl.PoliciesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, policySetName, name, policy) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client PoliciesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, policySetName string, name string, policy Policy) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "policySetName": autorest.Encode("path", policySetName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/policysets/{policySetName}/policies/{name}", pathParameters), + autorest.WithJSON(policy), + 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 PoliciesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client PoliciesClient) CreateOrUpdateResponder(resp *http.Response) (result Policy, 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 delete policy. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// policySetName - the name of the policy set. +// name - the name of the policy. +func (client PoliciesClient) Delete(ctx context.Context, resourceGroupName string, labName string, policySetName string, name string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PoliciesClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, policySetName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client PoliciesClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, policySetName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "policySetName": autorest.Encode("path", policySetName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{policySetName}/policies/{name}", 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 PoliciesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client PoliciesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get policy. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// policySetName - the name of the policy set. +// name - the name of the policy. +// expand - specify the $expand query. Example: 'properties($select=description)' +func (client PoliciesClient) Get(ctx context.Context, resourceGroupName string, labName string, policySetName string, name string, expand string) (result Policy, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PoliciesClient.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, labName, policySetName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client PoliciesClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, policySetName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "policySetName": autorest.Encode("path", policySetName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/policysets/{policySetName}/policies/{name}", 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 PoliciesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client PoliciesClient) GetResponder(resp *http.Response) (result Policy, 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 list policies in a given policy set. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// policySetName - the name of the policy set. +// expand - specify the $expand query. Example: 'properties($select=description)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client PoliciesClient) List(ctx context.Context, resourceGroupName string, labName string, policySetName string, expand string, filter string, top *int32, orderby string) (result PolicyListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PoliciesClient.List") + defer func() { + sc := -1 + if result.pl.Response.Response != nil { + sc = result.pl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, policySetName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.pl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "List", resp, "Failure sending request") + return + } + + result.pl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client PoliciesClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, policySetName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "policySetName": autorest.Encode("path", policySetName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{policySetName}/policies", 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 PoliciesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client PoliciesClient) ListResponder(resp *http.Response) (result PolicyList, 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 PoliciesClient) listNextResults(ctx context.Context, lastResults PolicyList) (result PolicyList, err error) { + req, err := lastResults.policyListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.PoliciesClient", "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, "dtl.PoliciesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client PoliciesClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, policySetName string, expand string, filter string, top *int32, orderby string) (result PolicyListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PoliciesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, policySetName, expand, filter, top, orderby) + return +} + +// Update modify properties of policies. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// policySetName - the name of the policy set. +// name - the name of the policy. +// policy - a Policy. +func (client PoliciesClient) Update(ctx context.Context, resourceGroupName string, labName string, policySetName string, name string, policy PolicyFragment) (result Policy, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PoliciesClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, policySetName, name, policy) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.PoliciesClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client PoliciesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, policySetName string, name string, policy PolicyFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "policySetName": autorest.Encode("path", policySetName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/policysets/{policySetName}/policies/{name}", pathParameters), + autorest.WithJSON(policy), + 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 PoliciesClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client PoliciesClient) UpdateResponder(resp *http.Response) (result Policy, 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/devtestlabs/mgmt/2018-09-15/dtl/policysets.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/policysets.go new file mode 100644 index 000000000..d9e313e2e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/policysets.go @@ -0,0 +1,123 @@ +package dtl + +// 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" +) + +// PolicySetsClient is the the DevTest Labs Client. +type PolicySetsClient struct { + BaseClient +} + +// NewPolicySetsClient creates an instance of the PolicySetsClient client. +func NewPolicySetsClient(subscriptionID string) PolicySetsClient { + return NewPolicySetsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPolicySetsClientWithBaseURI creates an instance of the PolicySetsClient client. +func NewPolicySetsClientWithBaseURI(baseURI string, subscriptionID string) PolicySetsClient { + return PolicySetsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// EvaluatePolicies evaluates lab policy. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the policy set. +// evaluatePoliciesRequest - request body for evaluating a policy set. +func (client PolicySetsClient) EvaluatePolicies(ctx context.Context, resourceGroupName string, labName string, name string, evaluatePoliciesRequest EvaluatePoliciesRequest) (result EvaluatePoliciesResponse, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/PolicySetsClient.EvaluatePolicies") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.EvaluatePoliciesPreparer(ctx, resourceGroupName, labName, name, evaluatePoliciesRequest) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.PolicySetsClient", "EvaluatePolicies", nil, "Failure preparing request") + return + } + + resp, err := client.EvaluatePoliciesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.PolicySetsClient", "EvaluatePolicies", resp, "Failure sending request") + return + } + + result, err = client.EvaluatePoliciesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.PolicySetsClient", "EvaluatePolicies", resp, "Failure responding to request") + } + + return +} + +// EvaluatePoliciesPreparer prepares the EvaluatePolicies request. +func (client PolicySetsClient) EvaluatePoliciesPreparer(ctx context.Context, resourceGroupName string, labName string, name string, evaluatePoliciesRequest EvaluatePoliciesRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{name}/evaluatePolicies", pathParameters), + autorest.WithJSON(evaluatePoliciesRequest), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// EvaluatePoliciesSender sends the EvaluatePolicies request. The method will close the +// http.Response Body if it receives an error. +func (client PolicySetsClient) EvaluatePoliciesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// EvaluatePoliciesResponder handles the response to the EvaluatePolicies request. The method always +// closes the http.Response Body. +func (client PolicySetsClient) EvaluatePoliciesResponder(resp *http.Response) (result EvaluatePoliciesResponse, 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/devtestlabs/mgmt/2018-09-15/dtl/provideroperations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/provideroperations.go new file mode 100644 index 000000000..ecb780286 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/provideroperations.go @@ -0,0 +1,147 @@ +package dtl + +// 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" +) + +// ProviderOperationsClient is the the DevTest Labs Client. +type ProviderOperationsClient struct { + BaseClient +} + +// NewProviderOperationsClient creates an instance of the ProviderOperationsClient client. +func NewProviderOperationsClient(subscriptionID string) ProviderOperationsClient { + return NewProviderOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewProviderOperationsClientWithBaseURI creates an instance of the ProviderOperationsClient client. +func NewProviderOperationsClientWithBaseURI(baseURI string, subscriptionID string) ProviderOperationsClient { + return ProviderOperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List result of the request to list REST API operations +func (client ProviderOperationsClient) List(ctx context.Context) (result ProviderOperationResultPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ProviderOperationsClient.List") + defer func() { + sc := -1 + if result.por.Response.Response != nil { + sc = result.por.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ProviderOperationsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.por.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ProviderOperationsClient", "List", resp, "Failure sending request") + return + } + + result.por, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ProviderOperationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ProviderOperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.DevTestLab/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 ProviderOperationsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ProviderOperationsClient) ListResponder(resp *http.Response) (result ProviderOperationResult, 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 ProviderOperationsClient) listNextResults(ctx context.Context, lastResults ProviderOperationResult) (result ProviderOperationResult, err error) { + req, err := lastResults.providerOperationResultPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.ProviderOperationsClient", "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, "dtl.ProviderOperationsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ProviderOperationsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ProviderOperationsClient) ListComplete(ctx context.Context) (result ProviderOperationResultIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ProviderOperationsClient.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/devtestlabs/mgmt/2018-09-15/dtl/schedules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/schedules.go new file mode 100644 index 000000000..d33991149 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/schedules.go @@ -0,0 +1,699 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// SchedulesClient is the the DevTest Labs Client. +type SchedulesClient struct { + BaseClient +} + +// NewSchedulesClient creates an instance of the SchedulesClient client. +func NewSchedulesClient(subscriptionID string) SchedulesClient { + return NewSchedulesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewSchedulesClientWithBaseURI creates an instance of the SchedulesClient client. +func NewSchedulesClientWithBaseURI(baseURI string, subscriptionID string) SchedulesClient { + return SchedulesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing schedule. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the schedule. +// schedule - a schedule. +func (client SchedulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, name string, schedule Schedule) (result Schedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SchedulesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: schedule, + Constraints: []validation.Constraint{{Target: "schedule.ScheduleProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("dtl.SchedulesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, name, schedule) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client SchedulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, schedule Schedule) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/schedules/{name}", pathParameters), + autorest.WithJSON(schedule), + 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 SchedulesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client SchedulesClient) CreateOrUpdateResponder(resp *http.Response) (result Schedule, 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 delete schedule. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the schedule. +func (client SchedulesClient) Delete(ctx context.Context, resourceGroupName string, labName string, name string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SchedulesClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client SchedulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/schedules/{name}", 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 SchedulesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client SchedulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Execute execute a schedule. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the schedule. +func (client SchedulesClient) Execute(ctx context.Context, resourceGroupName string, labName string, name string) (result SchedulesExecuteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SchedulesClient.Execute") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ExecutePreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "Execute", nil, "Failure preparing request") + return + } + + result, err = client.ExecuteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "Execute", result.Response(), "Failure sending request") + return + } + + return +} + +// ExecutePreparer prepares the Execute request. +func (client SchedulesClient) ExecutePreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/schedules/{name}/execute", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ExecuteSender sends the Execute request. The method will close the +// http.Response Body if it receives an error. +func (client SchedulesClient) ExecuteSender(req *http.Request) (future SchedulesExecuteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// ExecuteResponder handles the response to the Execute request. The method always +// closes the http.Response Body. +func (client SchedulesClient) ExecuteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get schedule. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the schedule. +// expand - specify the $expand query. Example: 'properties($select=status)' +func (client SchedulesClient) Get(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (result Schedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SchedulesClient.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, labName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client SchedulesClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/schedules/{name}", 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 SchedulesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client SchedulesClient) GetResponder(resp *http.Response) (result Schedule, 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 list schedules in a given lab. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// expand - specify the $expand query. Example: 'properties($select=status)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client SchedulesClient) List(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result ScheduleListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SchedulesClient.List") + defer func() { + sc := -1 + if result.sl.Response.Response != nil { + sc = result.sl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.sl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "List", resp, "Failure sending request") + return + } + + result.sl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client SchedulesClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/schedules", 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 SchedulesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client SchedulesClient) ListResponder(resp *http.Response) (result ScheduleList, 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 SchedulesClient) listNextResults(ctx context.Context, lastResults ScheduleList) (result ScheduleList, err error) { + req, err := lastResults.scheduleListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.SchedulesClient", "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, "dtl.SchedulesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client SchedulesClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result ScheduleListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SchedulesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, expand, filter, top, orderby) + return +} + +// ListApplicable lists all applicable schedules +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the schedule. +func (client SchedulesClient) ListApplicable(ctx context.Context, resourceGroupName string, labName string, name string) (result ScheduleListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SchedulesClient.ListApplicable") + defer func() { + sc := -1 + if result.sl.Response.Response != nil { + sc = result.sl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listApplicableNextResults + req, err := client.ListApplicablePreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "ListApplicable", nil, "Failure preparing request") + return + } + + resp, err := client.ListApplicableSender(req) + if err != nil { + result.sl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "ListApplicable", resp, "Failure sending request") + return + } + + result.sl, err = client.ListApplicableResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "ListApplicable", resp, "Failure responding to request") + } + + return +} + +// ListApplicablePreparer prepares the ListApplicable request. +func (client SchedulesClient) ListApplicablePreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/schedules/{name}/listApplicable", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListApplicableSender sends the ListApplicable request. The method will close the +// http.Response Body if it receives an error. +func (client SchedulesClient) ListApplicableSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListApplicableResponder handles the response to the ListApplicable request. The method always +// closes the http.Response Body. +func (client SchedulesClient) ListApplicableResponder(resp *http.Response) (result ScheduleList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listApplicableNextResults retrieves the next set of results, if any. +func (client SchedulesClient) listApplicableNextResults(ctx context.Context, lastResults ScheduleList) (result ScheduleList, err error) { + req, err := lastResults.scheduleListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.SchedulesClient", "listApplicableNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListApplicableSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "dtl.SchedulesClient", "listApplicableNextResults", resp, "Failure sending next results request") + } + result, err = client.ListApplicableResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "listApplicableNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListApplicableComplete enumerates all values, automatically crossing page boundaries as required. +func (client SchedulesClient) ListApplicableComplete(ctx context.Context, resourceGroupName string, labName string, name string) (result ScheduleListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SchedulesClient.ListApplicable") + 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.ListApplicable(ctx, resourceGroupName, labName, name) + return +} + +// Update modify properties of schedules. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the schedule. +// schedule - a schedule. +func (client SchedulesClient) Update(ctx context.Context, resourceGroupName string, labName string, name string, schedule ScheduleFragment) (result Schedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SchedulesClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, name, schedule) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SchedulesClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client SchedulesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, schedule ScheduleFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/schedules/{name}", pathParameters), + autorest.WithJSON(schedule), + 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 SchedulesClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client SchedulesClient) UpdateResponder(resp *http.Response) (result Schedule, 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/devtestlabs/mgmt/2018-09-15/dtl/secrets.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/secrets.go new file mode 100644 index 000000000..ced061e89 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/secrets.go @@ -0,0 +1,514 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// SecretsClient is the the DevTest Labs Client. +type SecretsClient struct { + BaseClient +} + +// NewSecretsClient creates an instance of the SecretsClient client. +func NewSecretsClient(subscriptionID string) SecretsClient { + return NewSecretsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewSecretsClientWithBaseURI creates an instance of the SecretsClient client. +func NewSecretsClientWithBaseURI(baseURI string, subscriptionID string) SecretsClient { + return SecretsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing secret. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the secret. +// secret - a secret. +func (client SecretsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, userName string, name string, secret Secret) (result SecretsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SecretsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: secret, + Constraints: []validation.Constraint{{Target: "secret.SecretProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("dtl.SecretsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, userName, name, secret) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client SecretsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, secret Secret) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/secrets/{name}", pathParameters), + autorest.WithJSON(secret), + 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 SecretsClient) CreateOrUpdateSender(req *http.Request) (future SecretsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 SecretsClient) CreateOrUpdateResponder(resp *http.Response) (result Secret, 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 delete secret. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the secret. +func (client SecretsClient) Delete(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SecretsClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, userName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client SecretsClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/secrets/{name}", 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 SecretsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client SecretsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get secret. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the secret. +// expand - specify the $expand query. Example: 'properties($select=value)' +func (client SecretsClient) Get(ctx context.Context, resourceGroupName string, labName string, userName string, name string, expand string) (result Secret, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SecretsClient.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, labName, userName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client SecretsClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/secrets/{name}", 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 SecretsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client SecretsClient) GetResponder(resp *http.Response) (result Secret, 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 list secrets in a given user profile. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// expand - specify the $expand query. Example: 'properties($select=value)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client SecretsClient) List(ctx context.Context, resourceGroupName string, labName string, userName string, expand string, filter string, top *int32, orderby string) (result SecretListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SecretsClient.List") + defer func() { + sc := -1 + if result.sl.Response.Response != nil { + sc = result.sl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, userName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.sl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "List", resp, "Failure sending request") + return + } + + result.sl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client SecretsClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/secrets", 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 SecretsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client SecretsClient) ListResponder(resp *http.Response) (result SecretList, 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 SecretsClient) listNextResults(ctx context.Context, lastResults SecretList) (result SecretList, err error) { + req, err := lastResults.secretListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.SecretsClient", "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, "dtl.SecretsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client SecretsClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, userName string, expand string, filter string, top *int32, orderby string) (result SecretListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SecretsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, userName, expand, filter, top, orderby) + return +} + +// Update modify properties of secrets. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the secret. +// secret - a secret. +func (client SecretsClient) Update(ctx context.Context, resourceGroupName string, labName string, userName string, name string, secret SecretFragment) (result Secret, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/SecretsClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, userName, name, secret) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.SecretsClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client SecretsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, secret SecretFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/secrets/{name}", pathParameters), + autorest.WithJSON(secret), + 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 SecretsClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client SecretsClient) UpdateResponder(resp *http.Response) (result Secret, 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/devtestlabs/mgmt/2018-09-15/dtl/servicefabrics.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/servicefabrics.go new file mode 100644 index 000000000..7ca72b7ce --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/servicefabrics.go @@ -0,0 +1,764 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ServiceFabricsClient is the the DevTest Labs Client. +type ServiceFabricsClient struct { + BaseClient +} + +// NewServiceFabricsClient creates an instance of the ServiceFabricsClient client. +func NewServiceFabricsClient(subscriptionID string) ServiceFabricsClient { + return NewServiceFabricsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewServiceFabricsClientWithBaseURI creates an instance of the ServiceFabricsClient client. +func NewServiceFabricsClientWithBaseURI(baseURI string, subscriptionID string) ServiceFabricsClient { + return ServiceFabricsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing Service Fabric. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the service Fabric. +// serviceFabric - a Service Fabric. +func (client ServiceFabricsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, userName string, name string, serviceFabric ServiceFabric) (result ServiceFabricsCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricsClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: serviceFabric, + Constraints: []validation.Constraint{{Target: "serviceFabric.ServiceFabricProperties", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "serviceFabric.ServiceFabricProperties.ApplicableSchedule", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "serviceFabric.ServiceFabricProperties.ApplicableSchedule.ApplicableScheduleProperties", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "serviceFabric.ServiceFabricProperties.ApplicableSchedule.ApplicableScheduleProperties.LabVmsShutdown", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "serviceFabric.ServiceFabricProperties.ApplicableSchedule.ApplicableScheduleProperties.LabVmsShutdown.ScheduleProperties", Name: validation.Null, Rule: true, Chain: nil}}}, + {Target: "serviceFabric.ServiceFabricProperties.ApplicableSchedule.ApplicableScheduleProperties.LabVmsStartup", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "serviceFabric.ServiceFabricProperties.ApplicableSchedule.ApplicableScheduleProperties.LabVmsStartup.ScheduleProperties", Name: validation.Null, Rule: true, Chain: nil}}}, + }}, + }}, + }}}}}); err != nil { + return result, validation.NewError("dtl.ServiceFabricsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, userName, name, serviceFabric) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ServiceFabricsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, serviceFabric ServiceFabric) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/servicefabrics/{name}", pathParameters), + autorest.WithJSON(serviceFabric), + 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 ServiceFabricsClient) CreateOrUpdateSender(req *http.Request) (future ServiceFabricsCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 ServiceFabricsClient) CreateOrUpdateResponder(resp *http.Response) (result ServiceFabric, 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 delete service fabric. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the service Fabric. +func (client ServiceFabricsClient) Delete(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (result ServiceFabricsDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricsClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, userName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ServiceFabricsClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/servicefabrics/{name}", 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 ServiceFabricsClient) DeleteSender(req *http.Request) (future ServiceFabricsDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 ServiceFabricsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get service fabric. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the service Fabric. +// expand - specify the $expand query. Example: 'properties($expand=applicableSchedule)' +func (client ServiceFabricsClient) Get(ctx context.Context, resourceGroupName string, labName string, userName string, name string, expand string) (result ServiceFabric, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricsClient.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, labName, userName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ServiceFabricsClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/servicefabrics/{name}", 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 ServiceFabricsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ServiceFabricsClient) GetResponder(resp *http.Response) (result ServiceFabric, 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 list service fabrics in a given user profile. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// expand - specify the $expand query. Example: 'properties($expand=applicableSchedule)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client ServiceFabricsClient) List(ctx context.Context, resourceGroupName string, labName string, userName string, expand string, filter string, top *int32, orderby string) (result ServiceFabricListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricsClient.List") + defer func() { + sc := -1 + if result.sfl.Response.Response != nil { + sc = result.sfl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, userName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.sfl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "List", resp, "Failure sending request") + return + } + + result.sfl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ServiceFabricsClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/servicefabrics", 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 ServiceFabricsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ServiceFabricsClient) ListResponder(resp *http.Response) (result ServiceFabricList, 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 ServiceFabricsClient) listNextResults(ctx context.Context, lastResults ServiceFabricList) (result ServiceFabricList, err error) { + req, err := lastResults.serviceFabricListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "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, "dtl.ServiceFabricsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ServiceFabricsClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, userName string, expand string, filter string, top *int32, orderby string) (result ServiceFabricListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricsClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, userName, expand, filter, top, orderby) + return +} + +// ListApplicableSchedules lists the applicable start/stop schedules, if any. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the service Fabric. +func (client ServiceFabricsClient) ListApplicableSchedules(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (result ApplicableSchedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricsClient.ListApplicableSchedules") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListApplicableSchedulesPreparer(ctx, resourceGroupName, labName, userName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "ListApplicableSchedules", nil, "Failure preparing request") + return + } + + resp, err := client.ListApplicableSchedulesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "ListApplicableSchedules", resp, "Failure sending request") + return + } + + result, err = client.ListApplicableSchedulesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "ListApplicableSchedules", resp, "Failure responding to request") + } + + return +} + +// ListApplicableSchedulesPreparer prepares the ListApplicableSchedules request. +func (client ServiceFabricsClient) ListApplicableSchedulesPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/servicefabrics/{name}/listApplicableSchedules", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListApplicableSchedulesSender sends the ListApplicableSchedules request. The method will close the +// http.Response Body if it receives an error. +func (client ServiceFabricsClient) ListApplicableSchedulesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListApplicableSchedulesResponder handles the response to the ListApplicableSchedules request. The method always +// closes the http.Response Body. +func (client ServiceFabricsClient) ListApplicableSchedulesResponder(resp *http.Response) (result ApplicableSchedule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Start start a service fabric. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the service Fabric. +func (client ServiceFabricsClient) Start(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (result ServiceFabricsStartFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricsClient.Start") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.StartPreparer(ctx, resourceGroupName, labName, userName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "Start", nil, "Failure preparing request") + return + } + + result, err = client.StartSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "Start", result.Response(), "Failure sending request") + return + } + + return +} + +// StartPreparer prepares the Start request. +func (client ServiceFabricsClient) StartPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/servicefabrics/{name}/start", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// StartSender sends the Start request. The method will close the +// http.Response Body if it receives an error. +func (client ServiceFabricsClient) StartSender(req *http.Request) (future ServiceFabricsStartFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// StartResponder handles the response to the Start request. The method always +// closes the http.Response Body. +func (client ServiceFabricsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Stop stop a service fabric This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the service Fabric. +func (client ServiceFabricsClient) Stop(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (result ServiceFabricsStopFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricsClient.Stop") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.StopPreparer(ctx, resourceGroupName, labName, userName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "Stop", nil, "Failure preparing request") + return + } + + result, err = client.StopSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "Stop", result.Response(), "Failure sending request") + return + } + + return +} + +// StopPreparer prepares the Stop request. +func (client ServiceFabricsClient) StopPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/servicefabrics/{name}/stop", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// StopSender sends the Stop request. The method will close the +// http.Response Body if it receives an error. +func (client ServiceFabricsClient) StopSender(req *http.Request) (future ServiceFabricsStopFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// StopResponder handles the response to the Stop request. The method always +// closes the http.Response Body. +func (client ServiceFabricsClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Update modify properties of service fabrics. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// name - the name of the service Fabric. +// serviceFabric - a Service Fabric. +func (client ServiceFabricsClient) Update(ctx context.Context, resourceGroupName string, labName string, userName string, name string, serviceFabric ServiceFabricFragment) (result ServiceFabric, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricsClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, userName, name, serviceFabric) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricsClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client ServiceFabricsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, name string, serviceFabric ServiceFabricFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/servicefabrics/{name}", pathParameters), + autorest.WithJSON(serviceFabric), + 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 ServiceFabricsClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client ServiceFabricsClient) UpdateResponder(resp *http.Response) (result ServiceFabric, 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/devtestlabs/mgmt/2018-09-15/dtl/servicefabricschedules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/servicefabricschedules.go new file mode 100644 index 000000000..59763a2f5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/servicefabricschedules.go @@ -0,0 +1,606 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// ServiceFabricSchedulesClient is the the DevTest Labs Client. +type ServiceFabricSchedulesClient struct { + BaseClient +} + +// NewServiceFabricSchedulesClient creates an instance of the ServiceFabricSchedulesClient client. +func NewServiceFabricSchedulesClient(subscriptionID string) ServiceFabricSchedulesClient { + return NewServiceFabricSchedulesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewServiceFabricSchedulesClientWithBaseURI creates an instance of the ServiceFabricSchedulesClient client. +func NewServiceFabricSchedulesClientWithBaseURI(baseURI string, subscriptionID string) ServiceFabricSchedulesClient { + return ServiceFabricSchedulesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing schedule. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// serviceFabricName - the name of the service Fabric. +// name - the name of the schedule. +// schedule - a schedule. +func (client ServiceFabricSchedulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, userName string, serviceFabricName string, name string, schedule Schedule) (result Schedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricSchedulesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: schedule, + Constraints: []validation.Constraint{{Target: "schedule.ScheduleProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("dtl.ServiceFabricSchedulesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, userName, serviceFabricName, name, schedule) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ServiceFabricSchedulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, serviceFabricName string, name string, schedule Schedule) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceFabricName": autorest.Encode("path", serviceFabricName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/servicefabrics/{serviceFabricName}/schedules/{name}", pathParameters), + autorest.WithJSON(schedule), + 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 ServiceFabricSchedulesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ServiceFabricSchedulesClient) CreateOrUpdateResponder(resp *http.Response) (result Schedule, 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 delete schedule. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// serviceFabricName - the name of the service Fabric. +// name - the name of the schedule. +func (client ServiceFabricSchedulesClient) Delete(ctx context.Context, resourceGroupName string, labName string, userName string, serviceFabricName string, name string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricSchedulesClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, userName, serviceFabricName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ServiceFabricSchedulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, serviceFabricName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceFabricName": autorest.Encode("path", serviceFabricName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/servicefabrics/{serviceFabricName}/schedules/{name}", 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 ServiceFabricSchedulesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ServiceFabricSchedulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Execute execute a schedule. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// serviceFabricName - the name of the service Fabric. +// name - the name of the schedule. +func (client ServiceFabricSchedulesClient) Execute(ctx context.Context, resourceGroupName string, labName string, userName string, serviceFabricName string, name string) (result ServiceFabricSchedulesExecuteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricSchedulesClient.Execute") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ExecutePreparer(ctx, resourceGroupName, labName, userName, serviceFabricName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "Execute", nil, "Failure preparing request") + return + } + + result, err = client.ExecuteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "Execute", result.Response(), "Failure sending request") + return + } + + return +} + +// ExecutePreparer prepares the Execute request. +func (client ServiceFabricSchedulesClient) ExecutePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, serviceFabricName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceFabricName": autorest.Encode("path", serviceFabricName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/servicefabrics/{serviceFabricName}/schedules/{name}/execute", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ExecuteSender sends the Execute request. The method will close the +// http.Response Body if it receives an error. +func (client ServiceFabricSchedulesClient) ExecuteSender(req *http.Request) (future ServiceFabricSchedulesExecuteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// ExecuteResponder handles the response to the Execute request. The method always +// closes the http.Response Body. +func (client ServiceFabricSchedulesClient) ExecuteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get schedule. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// serviceFabricName - the name of the service Fabric. +// name - the name of the schedule. +// expand - specify the $expand query. Example: 'properties($select=status)' +func (client ServiceFabricSchedulesClient) Get(ctx context.Context, resourceGroupName string, labName string, userName string, serviceFabricName string, name string, expand string) (result Schedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricSchedulesClient.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, labName, userName, serviceFabricName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ServiceFabricSchedulesClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, serviceFabricName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceFabricName": autorest.Encode("path", serviceFabricName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/servicefabrics/{serviceFabricName}/schedules/{name}", 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 ServiceFabricSchedulesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ServiceFabricSchedulesClient) GetResponder(resp *http.Response) (result Schedule, 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 list schedules in a given service fabric. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// serviceFabricName - the name of the service Fabric. +// expand - specify the $expand query. Example: 'properties($select=status)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client ServiceFabricSchedulesClient) List(ctx context.Context, resourceGroupName string, labName string, userName string, serviceFabricName string, expand string, filter string, top *int32, orderby string) (result ScheduleListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricSchedulesClient.List") + defer func() { + sc := -1 + if result.sl.Response.Response != nil { + sc = result.sl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, userName, serviceFabricName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.sl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "List", resp, "Failure sending request") + return + } + + result.sl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ServiceFabricSchedulesClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, userName string, serviceFabricName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceFabricName": autorest.Encode("path", serviceFabricName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/servicefabrics/{serviceFabricName}/schedules", 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 ServiceFabricSchedulesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ServiceFabricSchedulesClient) ListResponder(resp *http.Response) (result ScheduleList, 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 ServiceFabricSchedulesClient) listNextResults(ctx context.Context, lastResults ScheduleList) (result ScheduleList, err error) { + req, err := lastResults.scheduleListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "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, "dtl.ServiceFabricSchedulesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ServiceFabricSchedulesClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, userName string, serviceFabricName string, expand string, filter string, top *int32, orderby string) (result ScheduleListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricSchedulesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, userName, serviceFabricName, expand, filter, top, orderby) + return +} + +// Update modify properties of schedules. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// userName - the name of the user profile. +// serviceFabricName - the name of the service Fabric. +// name - the name of the schedule. +// schedule - a schedule. +func (client ServiceFabricSchedulesClient) Update(ctx context.Context, resourceGroupName string, labName string, userName string, serviceFabricName string, name string, schedule ScheduleFragment) (result Schedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceFabricSchedulesClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, userName, serviceFabricName, name, schedule) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceFabricSchedulesClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client ServiceFabricSchedulesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, userName string, serviceFabricName string, name string, schedule ScheduleFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "serviceFabricName": autorest.Encode("path", serviceFabricName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "userName": autorest.Encode("path", userName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{userName}/servicefabrics/{serviceFabricName}/schedules/{name}", pathParameters), + autorest.WithJSON(schedule), + 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 ServiceFabricSchedulesClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client ServiceFabricSchedulesClient) UpdateResponder(resp *http.Response) (result Schedule, 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/devtestlabs/mgmt/2018-09-15/dtl/servicerunners.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/servicerunners.go new file mode 100644 index 000000000..611b39938 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/servicerunners.go @@ -0,0 +1,407 @@ +package dtl + +// 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" +) + +// ServiceRunnersClient is the the DevTest Labs Client. +type ServiceRunnersClient struct { + BaseClient +} + +// NewServiceRunnersClient creates an instance of the ServiceRunnersClient client. +func NewServiceRunnersClient(subscriptionID string) ServiceRunnersClient { + return NewServiceRunnersClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewServiceRunnersClientWithBaseURI creates an instance of the ServiceRunnersClient client. +func NewServiceRunnersClientWithBaseURI(baseURI string, subscriptionID string) ServiceRunnersClient { + return ServiceRunnersClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing Service runner. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the service runner. +// serviceRunner - a container for a managed identity to execute DevTest lab services. +func (client ServiceRunnersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, name string, serviceRunner ServiceRunner) (result ServiceRunner, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRunnersClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, name, serviceRunner) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ServiceRunnersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, serviceRunner ServiceRunner) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/servicerunners/{name}", pathParameters), + autorest.WithJSON(serviceRunner), + 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 ServiceRunnersClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ServiceRunnersClient) CreateOrUpdateResponder(resp *http.Response) (result ServiceRunner, 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 delete service runner. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the service runner. +func (client ServiceRunnersClient) Delete(ctx context.Context, resourceGroupName string, labName string, name string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRunnersClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ServiceRunnersClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/servicerunners/{name}", 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 ServiceRunnersClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ServiceRunnersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get service runner. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the service runner. +func (client ServiceRunnersClient) Get(ctx context.Context, resourceGroupName string, labName string, name string) (result ServiceRunner, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRunnersClient.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, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ServiceRunnersClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/servicerunners/{name}", 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 ServiceRunnersClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ServiceRunnersClient) GetResponder(resp *http.Response) (result ServiceRunner, 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 list service runners in a given lab. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client ServiceRunnersClient) List(ctx context.Context, resourceGroupName string, labName string, filter string, top *int32, orderby string) (result ServiceRunnerListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRunnersClient.List") + defer func() { + sc := -1 + if result.srl.Response.Response != nil { + sc = result.srl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.srl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "List", resp, "Failure sending request") + return + } + + result.srl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ServiceRunnersClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/servicerunners", 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 ServiceRunnersClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ServiceRunnersClient) ListResponder(resp *http.Response) (result ServiceRunnerList, 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 ServiceRunnersClient) listNextResults(ctx context.Context, lastResults ServiceRunnerList) (result ServiceRunnerList, err error) { + req, err := lastResults.serviceRunnerListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "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, "dtl.ServiceRunnersClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.ServiceRunnersClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ServiceRunnersClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, filter string, top *int32, orderby string) (result ServiceRunnerListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/ServiceRunnersClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, filter, top, orderby) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/users.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/users.go new file mode 100644 index 000000000..048f59029 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/users.go @@ -0,0 +1,497 @@ +package dtl + +// 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" +) + +// UsersClient is the the DevTest Labs Client. +type UsersClient struct { + BaseClient +} + +// NewUsersClient creates an instance of the UsersClient client. +func NewUsersClient(subscriptionID string) UsersClient { + return NewUsersClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewUsersClientWithBaseURI creates an instance of the UsersClient client. +func NewUsersClientWithBaseURI(baseURI string, subscriptionID string) UsersClient { + return UsersClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing user profile. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the user profile. +// userParameter - profile of a lab user. +func (client UsersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, name string, userParameter User) (result UsersCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, name, userParameter) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client UsersClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, userParameter User) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{name}", pathParameters), + autorest.WithJSON(userParameter), + 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 UsersClient) CreateOrUpdateSender(req *http.Request) (future UsersCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 UsersClient) CreateOrUpdateResponder(resp *http.Response) (result User, 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 delete user profile. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the user profile. +func (client UsersClient) Delete(ctx context.Context, resourceGroupName string, labName string, name string) (result UsersDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client UsersClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{name}", 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 UsersClient) DeleteSender(req *http.Request) (future UsersDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 UsersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get user profile. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the user profile. +// expand - specify the $expand query. Example: 'properties($select=identity)' +func (client UsersClient) Get(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (result User, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.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, labName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client UsersClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{name}", 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 UsersClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client UsersClient) GetResponder(resp *http.Response) (result User, 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 list user profiles in a given lab. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// expand - specify the $expand query. Example: 'properties($select=identity)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client UsersClient) List(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result UserListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.List") + defer func() { + sc := -1 + if result.ul.Response.Response != nil { + sc = result.ul.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.ul.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "List", resp, "Failure sending request") + return + } + + result.ul, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client UsersClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users", 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 UsersClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client UsersClient) ListResponder(resp *http.Response) (result UserList, 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 UsersClient) listNextResults(ctx context.Context, lastResults UserList) (result UserList, err error) { + req, err := lastResults.userListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.UsersClient", "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, "dtl.UsersClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client UsersClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result UserListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, expand, filter, top, orderby) + return +} + +// Update modify properties of user profiles. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the user profile. +// userParameter - profile of a lab user. +func (client UsersClient) Update(ctx context.Context, resourceGroupName string, labName string, name string, userParameter UserFragment) (result User, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/UsersClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, name, userParameter) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.UsersClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client UsersClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, userParameter UserFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/users/{name}", pathParameters), + autorest.WithJSON(userParameter), + 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 UsersClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client UsersClient) UpdateResponder(resp *http.Response) (result User, 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/devtestlabs/mgmt/2018-09-15/dtl/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/version.go new file mode 100644 index 000000000..5a36aff8c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/version.go @@ -0,0 +1,30 @@ +package dtl + +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 + " dtl/2018-09-15" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return version.Number +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/virtualmachines.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/virtualmachines.go new file mode 100644 index 000000000..271ab79f1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/virtualmachines.go @@ -0,0 +1,1544 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// VirtualMachinesClient is the the DevTest Labs Client. +type VirtualMachinesClient struct { + BaseClient +} + +// NewVirtualMachinesClient creates an instance of the VirtualMachinesClient client. +func NewVirtualMachinesClient(subscriptionID string) VirtualMachinesClient { + return NewVirtualMachinesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewVirtualMachinesClientWithBaseURI creates an instance of the VirtualMachinesClient client. +func NewVirtualMachinesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachinesClient { + return VirtualMachinesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// AddDataDisk attach a new or existing data disk to virtual machine. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +// dataDiskProperties - request body for adding a new or existing data disk to a virtual machine. +func (client VirtualMachinesClient) AddDataDisk(ctx context.Context, resourceGroupName string, labName string, name string, dataDiskProperties DataDiskProperties) (result VirtualMachinesAddDataDiskFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.AddDataDisk") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.AddDataDiskPreparer(ctx, resourceGroupName, labName, name, dataDiskProperties) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "AddDataDisk", nil, "Failure preparing request") + return + } + + result, err = client.AddDataDiskSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "AddDataDisk", result.Response(), "Failure sending request") + return + } + + return +} + +// AddDataDiskPreparer prepares the AddDataDisk request. +func (client VirtualMachinesClient) AddDataDiskPreparer(ctx context.Context, resourceGroupName string, labName string, name string, dataDiskProperties DataDiskProperties) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/addDataDisk", pathParameters), + autorest.WithJSON(dataDiskProperties), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// AddDataDiskSender sends the AddDataDisk request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) AddDataDiskSender(req *http.Request) (future VirtualMachinesAddDataDiskFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// AddDataDiskResponder handles the response to the AddDataDisk request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) AddDataDiskResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// ApplyArtifacts apply artifacts to virtual machine. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +// applyArtifactsRequest - request body for applying artifacts to a virtual machine. +func (client VirtualMachinesClient) ApplyArtifacts(ctx context.Context, resourceGroupName string, labName string, name string, applyArtifactsRequest ApplyArtifactsRequest) (result VirtualMachinesApplyArtifactsFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.ApplyArtifacts") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ApplyArtifactsPreparer(ctx, resourceGroupName, labName, name, applyArtifactsRequest) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "ApplyArtifacts", nil, "Failure preparing request") + return + } + + result, err = client.ApplyArtifactsSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "ApplyArtifacts", result.Response(), "Failure sending request") + return + } + + return +} + +// ApplyArtifactsPreparer prepares the ApplyArtifacts request. +func (client VirtualMachinesClient) ApplyArtifactsPreparer(ctx context.Context, resourceGroupName string, labName string, name string, applyArtifactsRequest ApplyArtifactsRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/applyArtifacts", pathParameters), + autorest.WithJSON(applyArtifactsRequest), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ApplyArtifactsSender sends the ApplyArtifacts request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) ApplyArtifactsSender(req *http.Request) (future VirtualMachinesApplyArtifactsFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// ApplyArtifactsResponder handles the response to the ApplyArtifacts request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) ApplyArtifactsResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Claim take ownership of an existing virtual machine This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +func (client VirtualMachinesClient) Claim(ctx context.Context, resourceGroupName string, labName string, name string) (result VirtualMachinesClaimFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Claim") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ClaimPreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Claim", nil, "Failure preparing request") + return + } + + result, err = client.ClaimSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Claim", result.Response(), "Failure sending request") + return + } + + return +} + +// ClaimPreparer prepares the Claim request. +func (client VirtualMachinesClient) ClaimPreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/claim", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ClaimSender sends the Claim request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) ClaimSender(req *http.Request) (future VirtualMachinesClaimFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// ClaimResponder handles the response to the Claim request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) ClaimResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// CreateOrUpdate create or replace an existing Virtual machine. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +// labVirtualMachine - a virtual machine. +func (client VirtualMachinesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, name string, labVirtualMachine LabVirtualMachine) (result VirtualMachinesCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: labVirtualMachine, + Constraints: []validation.Constraint{{Target: "labVirtualMachine.LabVirtualMachineProperties", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "labVirtualMachine.LabVirtualMachineProperties.ApplicableSchedule", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "labVirtualMachine.LabVirtualMachineProperties.ApplicableSchedule.ApplicableScheduleProperties", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "labVirtualMachine.LabVirtualMachineProperties.ApplicableSchedule.ApplicableScheduleProperties.LabVmsShutdown", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "labVirtualMachine.LabVirtualMachineProperties.ApplicableSchedule.ApplicableScheduleProperties.LabVmsShutdown.ScheduleProperties", Name: validation.Null, Rule: true, Chain: nil}}}, + {Target: "labVirtualMachine.LabVirtualMachineProperties.ApplicableSchedule.ApplicableScheduleProperties.LabVmsStartup", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "labVirtualMachine.LabVirtualMachineProperties.ApplicableSchedule.ApplicableScheduleProperties.LabVmsStartup.ScheduleProperties", Name: validation.Null, Rule: true, Chain: nil}}}, + }}, + }}, + }}}}}); err != nil { + return result, validation.NewError("dtl.VirtualMachinesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, name, labVirtualMachine) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client VirtualMachinesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, labVirtualMachine LabVirtualMachine) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/virtualmachines/{name}", pathParameters), + autorest.WithJSON(labVirtualMachine), + 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 VirtualMachinesClient) CreateOrUpdateSender(req *http.Request) (future VirtualMachinesCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 VirtualMachinesClient) CreateOrUpdateResponder(resp *http.Response) (result LabVirtualMachine, 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 delete virtual machine. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +func (client VirtualMachinesClient) Delete(ctx context.Context, resourceGroupName string, labName string, name string) (result VirtualMachinesDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client VirtualMachinesClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}", 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 VirtualMachinesClient) DeleteSender(req *http.Request) (future VirtualMachinesDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 VirtualMachinesClient) 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 +} + +// DetachDataDisk detach the specified disk from the virtual machine. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +// detachDataDiskProperties - request body for detaching data disk from a virtual machine. +func (client VirtualMachinesClient) DetachDataDisk(ctx context.Context, resourceGroupName string, labName string, name string, detachDataDiskProperties DetachDataDiskProperties) (result VirtualMachinesDetachDataDiskFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.DetachDataDisk") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DetachDataDiskPreparer(ctx, resourceGroupName, labName, name, detachDataDiskProperties) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "DetachDataDisk", nil, "Failure preparing request") + return + } + + result, err = client.DetachDataDiskSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "DetachDataDisk", result.Response(), "Failure sending request") + return + } + + return +} + +// DetachDataDiskPreparer prepares the DetachDataDisk request. +func (client VirtualMachinesClient) DetachDataDiskPreparer(ctx context.Context, resourceGroupName string, labName string, name string, detachDataDiskProperties DetachDataDiskProperties) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/detachDataDisk", pathParameters), + autorest.WithJSON(detachDataDiskProperties), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DetachDataDiskSender sends the DetachDataDisk request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) DetachDataDiskSender(req *http.Request) (future VirtualMachinesDetachDataDiskFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DetachDataDiskResponder handles the response to the DetachDataDisk request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) DetachDataDiskResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get virtual machine. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +// expand - specify the $expand query. Example: +// 'properties($expand=artifacts,computeVm,networkInterface,applicableSchedule)' +func (client VirtualMachinesClient) Get(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (result LabVirtualMachine, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.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, labName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VirtualMachinesClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/virtualmachines/{name}", 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 VirtualMachinesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) GetResponder(resp *http.Response) (result LabVirtualMachine, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetRdpFileContents gets a string that represents the contents of the RDP file for the virtual machine +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +func (client VirtualMachinesClient) GetRdpFileContents(ctx context.Context, resourceGroupName string, labName string, name string) (result RdpConnection, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.GetRdpFileContents") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.GetRdpFileContentsPreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "GetRdpFileContents", nil, "Failure preparing request") + return + } + + resp, err := client.GetRdpFileContentsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "GetRdpFileContents", resp, "Failure sending request") + return + } + + result, err = client.GetRdpFileContentsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "GetRdpFileContents", resp, "Failure responding to request") + } + + return +} + +// GetRdpFileContentsPreparer prepares the GetRdpFileContents request. +func (client VirtualMachinesClient) GetRdpFileContentsPreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/getRdpFileContents", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetRdpFileContentsSender sends the GetRdpFileContents request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) GetRdpFileContentsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetRdpFileContentsResponder handles the response to the GetRdpFileContents request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) GetRdpFileContentsResponder(resp *http.Response) (result RdpConnection, 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 list virtual machines in a given lab. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// expand - specify the $expand query. Example: +// 'properties($expand=artifacts,computeVm,networkInterface,applicableSchedule)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client VirtualMachinesClient) List(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result LabVirtualMachineListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.List") + defer func() { + sc := -1 + if result.lvml.Response.Response != nil { + sc = result.lvml.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.lvml.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "List", resp, "Failure sending request") + return + } + + result.lvml, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client VirtualMachinesClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines", 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 VirtualMachinesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) ListResponder(resp *http.Response) (result LabVirtualMachineList, 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 VirtualMachinesClient) listNextResults(ctx context.Context, lastResults LabVirtualMachineList) (result LabVirtualMachineList, err error) { + req, err := lastResults.labVirtualMachineListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "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, "dtl.VirtualMachinesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client VirtualMachinesClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result LabVirtualMachineListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, expand, filter, top, orderby) + return +} + +// ListApplicableSchedules lists the applicable start/stop schedules, if any. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +func (client VirtualMachinesClient) ListApplicableSchedules(ctx context.Context, resourceGroupName string, labName string, name string) (result ApplicableSchedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.ListApplicableSchedules") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ListApplicableSchedulesPreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "ListApplicableSchedules", nil, "Failure preparing request") + return + } + + resp, err := client.ListApplicableSchedulesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "ListApplicableSchedules", resp, "Failure sending request") + return + } + + result, err = client.ListApplicableSchedulesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "ListApplicableSchedules", resp, "Failure responding to request") + } + + return +} + +// ListApplicableSchedulesPreparer prepares the ListApplicableSchedules request. +func (client VirtualMachinesClient) ListApplicableSchedulesPreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/listApplicableSchedules", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListApplicableSchedulesSender sends the ListApplicableSchedules request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) ListApplicableSchedulesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListApplicableSchedulesResponder handles the response to the ListApplicableSchedules request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) ListApplicableSchedulesResponder(resp *http.Response) (result ApplicableSchedule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Redeploy redeploy a virtual machine This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +func (client VirtualMachinesClient) Redeploy(ctx context.Context, resourceGroupName string, labName string, name string) (result VirtualMachinesRedeployFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Redeploy") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.RedeployPreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Redeploy", nil, "Failure preparing request") + return + } + + result, err = client.RedeploySender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Redeploy", result.Response(), "Failure sending request") + return + } + + return +} + +// RedeployPreparer prepares the Redeploy request. +func (client VirtualMachinesClient) RedeployPreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/redeploy", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RedeploySender sends the Redeploy request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) RedeploySender(req *http.Request) (future VirtualMachinesRedeployFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// RedeployResponder handles the response to the Redeploy request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) RedeployResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Resize resize Virtual Machine. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +// resizeLabVirtualMachineProperties - request body for resizing a virtual machine. +func (client VirtualMachinesClient) Resize(ctx context.Context, resourceGroupName string, labName string, name string, resizeLabVirtualMachineProperties ResizeLabVirtualMachineProperties) (result VirtualMachinesResizeFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Resize") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ResizePreparer(ctx, resourceGroupName, labName, name, resizeLabVirtualMachineProperties) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Resize", nil, "Failure preparing request") + return + } + + result, err = client.ResizeSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Resize", result.Response(), "Failure sending request") + return + } + + return +} + +// ResizePreparer prepares the Resize request. +func (client VirtualMachinesClient) ResizePreparer(ctx context.Context, resourceGroupName string, labName string, name string, resizeLabVirtualMachineProperties ResizeLabVirtualMachineProperties) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/resize", pathParameters), + autorest.WithJSON(resizeLabVirtualMachineProperties), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ResizeSender sends the Resize request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) ResizeSender(req *http.Request) (future VirtualMachinesResizeFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// ResizeResponder handles the response to the Resize request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) ResizeResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Restart restart a virtual machine. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +func (client VirtualMachinesClient) Restart(ctx context.Context, resourceGroupName string, labName string, name string) (result VirtualMachinesRestartFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Restart") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.RestartPreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Restart", nil, "Failure preparing request") + return + } + + result, err = client.RestartSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Restart", result.Response(), "Failure sending request") + return + } + + return +} + +// RestartPreparer prepares the Restart request. +func (client VirtualMachinesClient) RestartPreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/restart", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RestartSender sends the Restart request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) RestartSender(req *http.Request) (future VirtualMachinesRestartFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// RestartResponder handles the response to the Restart request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Start start a virtual machine. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +func (client VirtualMachinesClient) Start(ctx context.Context, resourceGroupName string, labName string, name string) (result VirtualMachinesStartFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Start") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.StartPreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Start", nil, "Failure preparing request") + return + } + + result, err = client.StartSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Start", result.Response(), "Failure sending request") + return + } + + return +} + +// StartPreparer prepares the Start request. +func (client VirtualMachinesClient) StartPreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/start", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// StartSender sends the Start request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) StartSender(req *http.Request) (future VirtualMachinesStartFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// StartResponder handles the response to the Start request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Stop stop a virtual machine This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +func (client VirtualMachinesClient) Stop(ctx context.Context, resourceGroupName string, labName string, name string) (result VirtualMachinesStopFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Stop") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.StopPreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Stop", nil, "Failure preparing request") + return + } + + result, err = client.StopSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Stop", result.Response(), "Failure sending request") + return + } + + return +} + +// StopPreparer prepares the Stop request. +func (client VirtualMachinesClient) StopPreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/stop", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// StopSender sends the Stop request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) StopSender(req *http.Request) (future VirtualMachinesStopFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// StopResponder handles the response to the Stop request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// TransferDisks transfers all data disks attached to the virtual machine to be owned by the current user. This +// operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +func (client VirtualMachinesClient) TransferDisks(ctx context.Context, resourceGroupName string, labName string, name string) (result VirtualMachinesTransferDisksFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.TransferDisks") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.TransferDisksPreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "TransferDisks", nil, "Failure preparing request") + return + } + + result, err = client.TransferDisksSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "TransferDisks", result.Response(), "Failure sending request") + return + } + + return +} + +// TransferDisksPreparer prepares the TransferDisks request. +func (client VirtualMachinesClient) TransferDisksPreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/transferDisks", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// TransferDisksSender sends the TransferDisks request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) TransferDisksSender(req *http.Request) (future VirtualMachinesTransferDisksFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// TransferDisksResponder handles the response to the TransferDisks request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) TransferDisksResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// UnClaim release ownership of an existing virtual machine This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +func (client VirtualMachinesClient) UnClaim(ctx context.Context, resourceGroupName string, labName string, name string) (result VirtualMachinesUnClaimFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.UnClaim") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UnClaimPreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "UnClaim", nil, "Failure preparing request") + return + } + + result, err = client.UnClaimSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "UnClaim", result.Response(), "Failure sending request") + return + } + + return +} + +// UnClaimPreparer prepares the UnClaim request. +func (client VirtualMachinesClient) UnClaimPreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/unClaim", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UnClaimSender sends the UnClaim request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) UnClaimSender(req *http.Request) (future VirtualMachinesUnClaimFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// UnClaimResponder handles the response to the UnClaim request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) UnClaimResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Update modify properties of virtual machines. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual machine. +// labVirtualMachine - a virtual machine. +func (client VirtualMachinesClient) Update(ctx context.Context, resourceGroupName string, labName string, name string, labVirtualMachine LabVirtualMachineFragment) (result LabVirtualMachine, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachinesClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, name, labVirtualMachine) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachinesClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client VirtualMachinesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, labVirtualMachine LabVirtualMachineFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/virtualmachines/{name}", pathParameters), + autorest.WithJSON(labVirtualMachine), + 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 VirtualMachinesClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) UpdateResponder(resp *http.Response) (result LabVirtualMachine, 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/devtestlabs/mgmt/2018-09-15/dtl/virtualmachineschedules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/virtualmachineschedules.go new file mode 100644 index 000000000..b49c7e6ff --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/virtualmachineschedules.go @@ -0,0 +1,594 @@ +package dtl + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "github.com/Azure/go-autorest/tracing" + "net/http" +) + +// VirtualMachineSchedulesClient is the the DevTest Labs Client. +type VirtualMachineSchedulesClient struct { + BaseClient +} + +// NewVirtualMachineSchedulesClient creates an instance of the VirtualMachineSchedulesClient client. +func NewVirtualMachineSchedulesClient(subscriptionID string) VirtualMachineSchedulesClient { + return NewVirtualMachineSchedulesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewVirtualMachineSchedulesClientWithBaseURI creates an instance of the VirtualMachineSchedulesClient client. +func NewVirtualMachineSchedulesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineSchedulesClient { + return VirtualMachineSchedulesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing schedule. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// virtualMachineName - the name of the virtual machine. +// name - the name of the schedule. +// schedule - a schedule. +func (client VirtualMachineSchedulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, virtualMachineName string, name string, schedule Schedule) (result Schedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineSchedulesClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + if err := validation.Validate([]validation.Validation{ + {TargetValue: schedule, + Constraints: []validation.Constraint{{Target: "schedule.ScheduleProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("dtl.VirtualMachineSchedulesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, virtualMachineName, name, schedule) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client VirtualMachineSchedulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, virtualMachineName string, name string, schedule Schedule) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualMachineName": autorest.Encode("path", virtualMachineName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/virtualmachines/{virtualMachineName}/schedules/{name}", pathParameters), + autorest.WithJSON(schedule), + 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 VirtualMachineSchedulesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client VirtualMachineSchedulesClient) CreateOrUpdateResponder(resp *http.Response) (result Schedule, 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 delete schedule. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// virtualMachineName - the name of the virtual machine. +// name - the name of the schedule. +func (client VirtualMachineSchedulesClient) Delete(ctx context.Context, resourceGroupName string, labName string, virtualMachineName string, name string) (result autorest.Response, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineSchedulesClient.Delete") + defer func() { + sc := -1 + if result.Response != nil { + sc = result.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, virtualMachineName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client VirtualMachineSchedulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, virtualMachineName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualMachineName": autorest.Encode("path", virtualMachineName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{virtualMachineName}/schedules/{name}", 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 VirtualMachineSchedulesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client VirtualMachineSchedulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Execute execute a schedule. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// virtualMachineName - the name of the virtual machine. +// name - the name of the schedule. +func (client VirtualMachineSchedulesClient) Execute(ctx context.Context, resourceGroupName string, labName string, virtualMachineName string, name string) (result VirtualMachineSchedulesExecuteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineSchedulesClient.Execute") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.ExecutePreparer(ctx, resourceGroupName, labName, virtualMachineName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "Execute", nil, "Failure preparing request") + return + } + + result, err = client.ExecuteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "Execute", result.Response(), "Failure sending request") + return + } + + return +} + +// ExecutePreparer prepares the Execute request. +func (client VirtualMachineSchedulesClient) ExecutePreparer(ctx context.Context, resourceGroupName string, labName string, virtualMachineName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualMachineName": autorest.Encode("path", virtualMachineName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{virtualMachineName}/schedules/{name}/execute", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ExecuteSender sends the Execute request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineSchedulesClient) ExecuteSender(req *http.Request) (future VirtualMachineSchedulesExecuteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// ExecuteResponder handles the response to the Execute request. The method always +// closes the http.Response Body. +func (client VirtualMachineSchedulesClient) ExecuteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get schedule. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// virtualMachineName - the name of the virtual machine. +// name - the name of the schedule. +// expand - specify the $expand query. Example: 'properties($select=status)' +func (client VirtualMachineSchedulesClient) Get(ctx context.Context, resourceGroupName string, labName string, virtualMachineName string, name string, expand string) (result Schedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineSchedulesClient.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, labName, virtualMachineName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VirtualMachineSchedulesClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, virtualMachineName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualMachineName": autorest.Encode("path", virtualMachineName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/virtualmachines/{virtualMachineName}/schedules/{name}", 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 VirtualMachineSchedulesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VirtualMachineSchedulesClient) GetResponder(resp *http.Response) (result Schedule, 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 list schedules in a given virtual machine. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// virtualMachineName - the name of the virtual machine. +// expand - specify the $expand query. Example: 'properties($select=status)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client VirtualMachineSchedulesClient) List(ctx context.Context, resourceGroupName string, labName string, virtualMachineName string, expand string, filter string, top *int32, orderby string) (result ScheduleListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineSchedulesClient.List") + defer func() { + sc := -1 + if result.sl.Response.Response != nil { + sc = result.sl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, virtualMachineName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.sl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "List", resp, "Failure sending request") + return + } + + result.sl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client VirtualMachineSchedulesClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, virtualMachineName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualMachineName": autorest.Encode("path", virtualMachineName), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{virtualMachineName}/schedules", 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 VirtualMachineSchedulesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client VirtualMachineSchedulesClient) ListResponder(resp *http.Response) (result ScheduleList, 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 VirtualMachineSchedulesClient) listNextResults(ctx context.Context, lastResults ScheduleList) (result ScheduleList, err error) { + req, err := lastResults.scheduleListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "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, "dtl.VirtualMachineSchedulesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client VirtualMachineSchedulesClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, virtualMachineName string, expand string, filter string, top *int32, orderby string) (result ScheduleListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineSchedulesClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, virtualMachineName, expand, filter, top, orderby) + return +} + +// Update modify properties of schedules. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// virtualMachineName - the name of the virtual machine. +// name - the name of the schedule. +// schedule - a schedule. +func (client VirtualMachineSchedulesClient) Update(ctx context.Context, resourceGroupName string, labName string, virtualMachineName string, name string, schedule ScheduleFragment) (result Schedule, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualMachineSchedulesClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, virtualMachineName, name, schedule) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualMachineSchedulesClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client VirtualMachineSchedulesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, virtualMachineName string, name string, schedule ScheduleFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualMachineName": autorest.Encode("path", virtualMachineName), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/virtualmachines/{virtualMachineName}/schedules/{name}", pathParameters), + autorest.WithJSON(schedule), + 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 VirtualMachineSchedulesClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client VirtualMachineSchedulesClient) UpdateResponder(resp *http.Response) (result Schedule, 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/devtestlabs/mgmt/2018-09-15/dtl/virtualnetworks.go b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/virtualnetworks.go new file mode 100644 index 000000000..bbc570151 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl/virtualnetworks.go @@ -0,0 +1,497 @@ +package dtl + +// 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" +) + +// VirtualNetworksClient is the the DevTest Labs Client. +type VirtualNetworksClient struct { + BaseClient +} + +// NewVirtualNetworksClient creates an instance of the VirtualNetworksClient client. +func NewVirtualNetworksClient(subscriptionID string) VirtualNetworksClient { + return NewVirtualNetworksClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewVirtualNetworksClientWithBaseURI creates an instance of the VirtualNetworksClient client. +func NewVirtualNetworksClientWithBaseURI(baseURI string, subscriptionID string) VirtualNetworksClient { + return VirtualNetworksClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or replace an existing virtual network. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual network. +// virtualNetwork - a virtual network. +func (client VirtualNetworksClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, labName string, name string, virtualNetwork VirtualNetwork) (result VirtualNetworksCreateOrUpdateFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.CreateOrUpdate") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, labName, name, virtualNetwork) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client VirtualNetworksClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, virtualNetwork VirtualNetwork) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/virtualnetworks/{name}", pathParameters), + autorest.WithJSON(virtualNetwork), + 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 VirtualNetworksClient) CreateOrUpdateSender(req *http.Request) (future VirtualNetworksCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 VirtualNetworksClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetwork, 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 delete virtual network. This operation can take a while to complete. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual network. +func (client VirtualNetworksClient) Delete(ctx context.Context, resourceGroupName string, labName string, name string) (result VirtualNetworksDeleteFuture, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.Delete") + defer func() { + sc := -1 + if result.Response() != nil { + sc = result.Response().StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.DeletePreparer(ctx, resourceGroupName, labName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client VirtualNetworksClient) DeletePreparer(ctx context.Context, resourceGroupName string, labName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}", 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 VirtualNetworksClient) DeleteSender(req *http.Request) (future VirtualNetworksDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, 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 VirtualNetworksClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get virtual network. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual network. +// expand - specify the $expand query. Example: 'properties($expand=externalSubnets)' +func (client VirtualNetworksClient) Get(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (result VirtualNetwork, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.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, labName, name, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VirtualNetworksClient) GetPreparer(ctx context.Context, resourceGroupName string, labName string, name string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/virtualnetworks/{name}", 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 VirtualNetworksClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VirtualNetworksClient) GetResponder(resp *http.Response) (result VirtualNetwork, 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 list virtual networks in a given lab. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// expand - specify the $expand query. Example: 'properties($expand=externalSubnets)' +// filter - the filter to apply to the operation. Example: '$filter=contains(name,'myName') +// top - the maximum number of resources to return from the operation. Example: '$top=10' +// orderby - the ordering expression for the results, using OData notation. Example: '$orderby=name desc' +func (client VirtualNetworksClient) List(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result VirtualNetworkListPage, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.List") + defer func() { + sc := -1 + if result.vnl.Response.Response != nil { + sc = result.vnl.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, labName, expand, filter, top, orderby) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.vnl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "List", resp, "Failure sending request") + return + } + + result.vnl, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client VirtualNetworksClient) ListPreparer(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + if len(orderby) > 0 { + queryParameters["$orderby"] = autorest.Encode("query", orderby) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks", 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 VirtualNetworksClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client VirtualNetworksClient) ListResponder(resp *http.Response) (result VirtualNetworkList, 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 VirtualNetworksClient) listNextResults(ctx context.Context, lastResults VirtualNetworkList) (result VirtualNetworkList, err error) { + req, err := lastResults.virtualNetworkListPreparer(ctx) + if err != nil { + return result, autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "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, "dtl.VirtualNetworksClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client VirtualNetworksClient) ListComplete(ctx context.Context, resourceGroupName string, labName string, expand string, filter string, top *int32, orderby string) (result VirtualNetworkListIterator, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.List") + defer func() { + sc := -1 + if result.Response().Response.Response != nil { + sc = result.page.Response().Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + result.page, err = client.List(ctx, resourceGroupName, labName, expand, filter, top, orderby) + return +} + +// Update modify properties of virtual networks. +// Parameters: +// resourceGroupName - the name of the resource group. +// labName - the name of the lab. +// name - the name of the virtual network. +// virtualNetwork - a virtual network. +func (client VirtualNetworksClient) Update(ctx context.Context, resourceGroupName string, labName string, name string, virtualNetwork VirtualNetworkFragment) (result VirtualNetwork, err error) { + if tracing.IsEnabled() { + ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworksClient.Update") + defer func() { + sc := -1 + if result.Response.Response != nil { + sc = result.Response.Response.StatusCode + } + tracing.EndSpan(ctx, sc, err) + }() + } + req, err := client.UpdatePreparer(ctx, resourceGroupName, labName, name, virtualNetwork) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "dtl.VirtualNetworksClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client VirtualNetworksClient) UpdatePreparer(ctx context.Context, resourceGroupName string, labName string, name string, virtualNetwork VirtualNetworkFragment) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "labName": autorest.Encode("path", labName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2018-09-15" + 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.DevTestLab/labs/{labName}/virtualnetworks/{name}", pathParameters), + autorest.WithJSON(virtualNetwork), + 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 VirtualNetworksClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client VirtualNetworksClient) UpdateResponder(resp *http.Response) (result VirtualNetwork, 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/modules.txt b/vendor/modules.txt index 94445f862..93ee550f8 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -18,6 +18,7 @@ github.com/Azure/azure-sdk-for-go/profiles/latest/compute/mgmt/compute/computeap github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-03-01/compute github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-03-01/compute/computeapi +github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2018-02-14/keyvault github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-01-01/network github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions diff --git a/website/source/partials/builder/azure/dtl/_ArtifactParameter-not-required.html.md b/website/source/partials/builder/azure/dtl/_ArtifactParameter-not-required.html.md new file mode 100644 index 000000000..854a41597 --- /dev/null +++ b/website/source/partials/builder/azure/dtl/_ArtifactParameter-not-required.html.md @@ -0,0 +1,5 @@ + + +- `name` (string) - Name +- `value` (string) - Value +- `type` (string) - Type \ No newline at end of file diff --git a/website/source/partials/builder/azure/dtl/_Config-not-required.html.md b/website/source/partials/builder/azure/dtl/_Config-not-required.html.md new file mode 100644 index 000000000..90d88d6a3 --- /dev/null +++ b/website/source/partials/builder/azure/dtl/_Config-not-required.html.md @@ -0,0 +1,158 @@ + + +- `capture_name_prefix` (string) - Capture + +- `capture_container_name` (string) - Capture Container Name +- `shared_image_gallery` (SharedImageGallery) - Use a [Shared Gallery + image](https://azure.microsoft.com/en-us/blog/announcing-the-public-preview-of-shared-image-gallery/) + as the source for this build. *VHD targets are incompatible with this + build type* - the target must be a *Managed Image*. + + "shared_image_gallery": { + "subscription": "00000000-0000-0000-0000-00000000000", + "resource_group": "ResourceGroup", + "gallery_name": "GalleryName", + "image_name": "ImageName", + "image_version": "1.0.0" + } + "managed_image_name": "TargetImageName", + "managed_image_resource_group_name": "TargetResourceGroup" + +- `shared_image_gallery_destination` (SharedImageGalleryDestination) - The name of the Shared Image Gallery under which the managed image will be published as Shared Gallery Image version. + + Following is an example. + + + + "shared_image_gallery_destination": { + "resource_group": "ResourceGroup", + "gallery_name": "GalleryName", + "image_name": "ImageName", + "image_version": "1.0.0", + "replication_regions": ["regionA", "regionB", "regionC"] + } + "managed_image_name": "TargetImageName", + "managed_image_resource_group_name": "TargetResourceGroup" + +- `shared_image_gallery_timeout` (duration string | ex: "1h5m2s") - How long to wait for an image to be published to the shared image + gallery before timing out. If your Packer build is failing on the + Publishing to Shared Image Gallery step with the error `Original Error: + context deadline exceeded`, but the image is present when you check your + Azure dashboard, then you probably need to increase this timeout from + its default of "60m" (valid time units include `s` for seconds, `m` for + minutes, and `h` for hours.) + +- `image_publisher` (string) - PublisherName for your base image. See + [documentation](https://azure.microsoft.com/en-us/documentation/articles/resource-groups-vm-searching/) + for details. + + CLI example `az vm image list-publishers --location westus` + +- `image_offer` (string) - Offer for your base image. See + [documentation](https://azure.microsoft.com/en-us/documentation/articles/resource-groups-vm-searching/) + for details. + + CLI example + `az vm image list-offers --location westus --publisher Canonical` + +- `image_sku` (string) - SKU for your base image. See + [documentation](https://azure.microsoft.com/en-us/documentation/articles/resource-groups-vm-searching/) + for details. + + CLI example + `az vm image list-skus --location westus --publisher Canonical --offer UbuntuServer` + +- `image_version` (string) - Specify a specific version of an OS to boot from. + Defaults to `latest`. There may be a difference in versions available + across regions due to image synchronization latency. To ensure a consistent + version across regions set this value to one that is available in all + regions where you are deploying. + + CLI example + `az vm image list --location westus --publisher Canonical --offer UbuntuServer --sku 16.04.0-LTS --all` + +- `image_url` (string) - Specify a custom VHD to use. If this value is set, do + not set image_publisher, image_offer, image_sku, or image_version. + +- `custom_managed_image_resource_group_name` (string) - Specify the source managed image's resource group used to use. If this + value is set, do not set image\_publisher, image\_offer, image\_sku, or + image\_version. If this value is set, the value + `custom_managed_image_name` must also be set. See + [documentation](https://docs.microsoft.com/en-us/azure/storage/storage-managed-disks-overview#images) + to learn more about managed images. + +- `custom_managed_image_name` (string) - Specify the source managed image's name to use. If this value is set, do + not set image\_publisher, image\_offer, image\_sku, or image\_version. + If this value is set, the value + `custom_managed_image_resource_group_name` must also be set. See + [documentation](https://docs.microsoft.com/en-us/azure/storage/storage-managed-disks-overview#images) + to learn more about managed images. + +- `location` (string) - Location +- `vm_size` (string) - Size of the VM used for building. This can be changed when you deploy a + VM from your VHD. See + [pricing](https://azure.microsoft.com/en-us/pricing/details/virtual-machines/) + information. Defaults to `Standard_A1`. + + CLI example `az vm list-sizes --location westus` + +- `managed_image_resource_group_name` (string) - Specify the managed image resource group name where the result of the + Packer build will be saved. The resource group must already exist. If + this value is set, the value managed_image_name must also be set. See + documentation to learn more about managed images. + +- `managed_image_name` (string) - Specify the managed image name where the result of the Packer build will + be saved. The image name must not exist ahead of time, and will not be + overwritten. If this value is set, the value + managed_image_resource_group_name must also be set. See documentation to + learn more about managed images. + +- `managed_image_storage_account_type` (string) - Specify the storage account + type for a managed image. Valid values are Standard_LRS and Premium_LRS. + The default is Standard_LRS. + +- `azure_tags` (map[string]\*string) - the user can define up to 15 + tags. Tag names cannot exceed 512 characters, and tag values cannot exceed + 256 characters. Tags are applied to every resource deployed by a Packer + build, i.e. Resource Group, VM, NIC, VNET, Public IP, KeyVault, etc. + +- `plan_id` (string) - Used for creating images from Marketplace images. Please refer to + [Deploy an image with Marketplace + terms](https://aka.ms/azuremarketplaceapideployment) for more details. + Not all Marketplace images support programmatic deployment, and support + is controlled by the image publisher. + Plan_id is a string with unique identifier for the plan associated with images. + Ex plan_id="1-12ab" + +- `polling_duration_timeout` (duration string | ex: "1h5m2s") - The default PollingDuration for azure is 15mins, this property will override + that value. See [Azure DefaultPollingDuration](https://godoc.org/github.com/Azure/go-autorest/autorest#pkg-constants) + If your Packer build is failing on the + ARM deployment step with the error `Original Error: + context deadline exceeded`, then you probably need to increase this timeout from + its default of "15m" (valid time units include `s` for seconds, `m` for + minutes, and `h` for hours.) + +- `os_type` (string) - If either Linux or Windows is specified Packer will + automatically configure authentication credentials for the provisioned + machine. For Linux this configures an SSH authorized key. For Windows + this configures a WinRM certificate. + +- `os_disk_size_gb` (int32) - Specify the size of the OS disk in GB + (gigabytes). Values of zero or less than zero are ignored. + +- `disk_additional_size` ([]int32) - For Managed build the final artifacts are included in the managed image. + The additional disk will have the same storage account type as the OS + disk, as specified with the `managed_image_storage_account_type` + setting. + +- `disk_caching_type` (string) - Specify the disk caching type. Valid values + are None, ReadOnly, and ReadWrite. The default value is ReadWrite. + +- `storage_type` (string) - DTL values + +- `lab_virtual_network_name` (string) - Lab Virtual Network Name +- `lab_name` (string) - Lab Name +- `lab_subnet_name` (string) - Lab Subnet Name +- `lab_resource_group_name` (string) - Lab Resource Group Name +- `dtl_artifacts` ([]DtlArtifact) - Dtl Artifacts +- `vm_name` (string) - VM Name \ No newline at end of file diff --git a/website/source/partials/builder/azure/dtl/_DtlArtifact-not-required.html.md b/website/source/partials/builder/azure/dtl/_DtlArtifact-not-required.html.md new file mode 100644 index 000000000..6b4a8ce7f --- /dev/null +++ b/website/source/partials/builder/azure/dtl/_DtlArtifact-not-required.html.md @@ -0,0 +1,6 @@ + + +- `artifact_name` (string) - Artifact Name +- `repository_name` (string) - Repository Name +- `artifact_id` (string) - Artifact Id +- `parameters` ([]ArtifactParameter) - Parameters \ No newline at end of file diff --git a/website/source/partials/builder/azure/dtl/_SharedImageGallery-not-required.html.md b/website/source/partials/builder/azure/dtl/_SharedImageGallery-not-required.html.md new file mode 100644 index 000000000..906249d49 --- /dev/null +++ b/website/source/partials/builder/azure/dtl/_SharedImageGallery-not-required.html.md @@ -0,0 +1,7 @@ + + +- `subscription` (string) - Subscription +- `resource_group` (string) - Resource Group +- `gallery_name` (string) - Gallery Name +- `image_name` (string) - Image Name +- `image_version` (string) - Image Version \ No newline at end of file diff --git a/website/source/partials/builder/azure/dtl/_SharedImageGalleryDestination-not-required.html.md b/website/source/partials/builder/azure/dtl/_SharedImageGalleryDestination-not-required.html.md new file mode 100644 index 000000000..8760879db --- /dev/null +++ b/website/source/partials/builder/azure/dtl/_SharedImageGalleryDestination-not-required.html.md @@ -0,0 +1,7 @@ + + +- `resource_group` (string) - Sig Destination Resource Group +- `gallery_name` (string) - Sig Destination Gallery Name +- `image_name` (string) - Sig Destination Image Name +- `image_version` (string) - Sig Destination Image Version +- `replication_regions` ([]string) - Sig Destination Replication Regions \ No newline at end of file