Example #1
0
        /// <summary>
        /// Restores the disk based on the recovery point and other input parameters
        /// </summary>
        /// <param name="rp">Recovery point to restore the disk to</param>
        /// <param name="storageAccountId">ID of the storage account where to restore the disk</param>
        /// <param name="storageAccountLocation">Location of the storage account where to restore the disk</param>
        /// <param name="storageAccountType">Type of the storage account where to restore the disk</param>
        /// <returns>Job created by this operation</returns>
        public RestAzureNS.AzureOperationResponse RestoreDisk(
            AzureVmRecoveryPoint rp,
            string storageAccountId,
            string storageAccountLocation,
            string storageAccountType,
            bool osaOption)
        {
            var useOsa = ShouldUseOsa(rp, osaOption);

            string resourceGroupName = BmsAdapter.GetResourceGroupName();
            string resourceName      = BmsAdapter.GetResourceName();
            string vaultLocation     = BmsAdapter.GetResourceLocation();
            Dictionary <UriEnums, string> uriDict = HelperUtils.ParseUri(rp.Id);
            string containerUri     = HelperUtils.GetContainerUri(uriDict, rp.Id);
            string protectedItemUri = HelperUtils.GetProtectedItemUri(uriDict, rp.Id);
            string recoveryPointId  = rp.RecoveryPointId;

            //validtion block
            if (storageAccountLocation != vaultLocation)
            {
                throw new Exception(Resources.RestoreDiskIncorrectRegion);
            }

            string vmType = containerUri.Split(';')[1].Equals("iaasvmcontainer", StringComparison.OrdinalIgnoreCase)
                ? "Classic" : "Compute";
            string strType = storageAccountType.Equals("Microsoft.ClassicStorage/StorageAccounts",
                                                       StringComparison.OrdinalIgnoreCase) ? "Classic" : "Compute";

            if (vmType != strType)
            {
                throw new Exception(string.Format(Resources.RestoreDiskStorageTypeError, vmType));
            }

            IaasVMRestoreRequest restoreRequest = new IaasVMRestoreRequest()
            {
                CreateNewCloudService = false,
                RecoveryPointId       = recoveryPointId,
                RecoveryType          = RecoveryType.RestoreDisks,
                Region                       = vaultLocation,
                StorageAccountId             = storageAccountId,
                SourceResourceId             = rp.SourceResourceId,
                OriginalStorageAccountOption = useOsa,
            };

            RestoreRequestResource triggerRestoreRequest = new RestoreRequestResource();

            triggerRestoreRequest.Properties = restoreRequest;

            var response = BmsAdapter.Client.Restores.TriggerWithHttpMessagesAsync(
                resourceName,
                resourceGroupName,
                AzureFabricName,
                containerUri,
                protectedItemUri,
                recoveryPointId,
                triggerRestoreRequest,
                cancellationToken: BmsAdapter.CmdletCancellationToken).Result;

            return(response);
        }
Example #2
0
        public BaseRecoveryServicesJobResponse RestoreDisk(AzureVmRecoveryPoint rp, string storageAccountId,
                                                           string storageAccountLocation, string storageAccountType)
        {
            string resourceGroupName = BmsAdapter.GetResourceGroupName();
            string resourceName      = BmsAdapter.GetResourceName();
            string vaultLocation     = BmsAdapter.GetResourceLocation();
            string containerName     = rp.ContainerName;
            string protectedItemName = rp.ItemName;
            string recoveryPointId   = rp.RecoveryPointId;

            //validtion block
            if (storageAccountLocation != vaultLocation)
            {
                throw new Exception(Resources.RestoreDiskIncorrectRegion);
            }
            string vmType = containerName.Split(';')[1].Equals("iaasvmcontainer", StringComparison.OrdinalIgnoreCase)
                ? "Classic" : "Compute";
            string strType = storageAccountType.Equals("Microsoft.ClassicStorage/StorageAccounts",
                                                       StringComparison.OrdinalIgnoreCase) ? "Classic" : "Compute";

            if (vmType != strType)
            {
                throw new Exception(String.Format(Resources.RestoreDiskStorageTypeError, vmType));
            }

            IaasVMRestoreRequest restoreRequest = new IaasVMRestoreRequest()
            {
                AffinityGroup = String.Empty,
                CloudServiceOrResourceGroup = String.Empty,
                CreateNewCloudService       = false,
                RecoveryPointId             = recoveryPointId,
                RecoveryType       = RecoveryType.RestoreDisks,
                Region             = vaultLocation,
                StorageAccountId   = storageAccountId,
                SubnetId           = string.Empty,
                VirtualMachineName = string.Empty,
                VirtualNetworkId   = string.Empty,
            };

            TriggerRestoreRequest triggerRestoreRequest = new TriggerRestoreRequest();

            triggerRestoreRequest.Item            = new RestoreRequestResource();
            triggerRestoreRequest.Item.Properties = new RestoreRequest();
            triggerRestoreRequest.Item.Properties = restoreRequest;

            var response = BmsAdapter.Client.Restores.TriggerRestoreAsync(
                resourceGroupName,
                resourceName,
                BmsAdapter.GetCustomRequestHeaders(),
                AzureFabricName,
                containerName,
                protectedItemName,
                recoveryPointId,
                triggerRestoreRequest,
                BmsAdapter.CmdletCancellationToken).Result;

            return(response);
        }
Example #3
0
        public string RestoreProtectedItem(string rsVaultRgName, string rsVaultName, string containerUri, string protectedItemUri, string sourceResourceId, string storageAccountId, RecoveryPointResource recoveryPointResource)
        {
            string fabricName = CommonTestHelper.GetSetting(TestConstants.ProviderTypeAzureIaasVM);

            RecoveryPoint recoveryPoint = (RecoveryPoint)recoveryPointResource.Properties;

            TriggerRestoreRequest restoreRequest = new TriggerRestoreRequest();

            restoreRequest.Item = new RestoreRequestResource();
            IaasVMRestoreRequest iaasVmRestoreRequest = new IaasVMRestoreRequest();

            if (recoveryPoint.KeyAndSecret != null &&
                recoveryPoint.KeyAndSecret.BekDetails != null &&
                recoveryPoint.KeyAndSecret.KekDetails != null)
            {
                iaasVmRestoreRequest.EncryptionDetails = new EncryptionDetails();
                iaasVmRestoreRequest.EncryptionDetails.EncryptionEnabled = true;
                iaasVmRestoreRequest.EncryptionDetails.KekUrl            = recoveryPoint.KeyAndSecret.KekDetails.KeyUrl;
                iaasVmRestoreRequest.EncryptionDetails.KekVaultId        = recoveryPoint.KeyAndSecret.KekDetails.KeyVaultId;
                iaasVmRestoreRequest.EncryptionDetails.SecretKeyUrl      = recoveryPoint.KeyAndSecret.BekDetails.SecretUrl;
                iaasVmRestoreRequest.EncryptionDetails.SecretKeyVaultId  = recoveryPoint.KeyAndSecret.BekDetails.SecretVaultId;
            }
            iaasVmRestoreRequest.RecoveryPointId  = recoveryPointResource.Name;
            iaasVmRestoreRequest.RecoveryType     = RecoveryType.RestoreDisks.ToString();
            iaasVmRestoreRequest.SourceResourceId = sourceResourceId;
            iaasVmRestoreRequest.StorageAccountId = storageAccountId;
            restoreRequest.Item.Properties        = iaasVmRestoreRequest;

            var response = Client.Restores.TriggerRestore(rsVaultRgName, rsVaultName, CommonTestHelper.GetCustomRequestHeaders(),
                                                          fabricName, containerUri, protectedItemUri, recoveryPointResource.Name, restoreRequest);

            Assert.NotNull(response);
            Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
            Assert.NotNull(response.Location);
            Assert.NotNull(response.AzureAsyncOperation);
            Assert.NotNull(response.RetryAfter);

            var operationResponse = Client.ProtectedItems.GetProtectedItemOperationResultByURLAsync(response.Location, CommonTestHelper.GetCustomRequestHeaders());

            while (operationResponse.Result.StatusCode == HttpStatusCode.Accepted)
            {
                if (HttpMockServer.Mode == HttpRecorderMode.Record)
                {
                    System.Threading.Thread.Sleep(5 * 1000);
                }
                operationResponse = Client.ProtectedItems.GetProtectedItemOperationResultByURLAsync(response.Location, CommonTestHelper.GetCustomRequestHeaders());
            }

            var operationStatusResponse = Client.GetOperationStatusByURLAsync(response.AzureAsyncOperation, CommonTestHelper.GetCustomRequestHeaders());
            var operationJobResponse    = (OperationStatusJobExtendedInfo)operationStatusResponse.Result.OperationStatus.Properties;

            Assert.NotNull(operationJobResponse.JobId);

            return(operationJobResponse.JobId);
        }
Example #4
0
        public void RestoreDiskTest()
        {
            using (UndoContext context = UndoContext.Current)
            {
                context.Start();

                string resourceNamespace   = ConfigurationManager.AppSettings["ResourceNamespace"];
                string vaultLocation       = ConfigurationManager.AppSettings["vaultLocation"];
                string fabricName          = ConfigurationManager.AppSettings["AzureBackupFabricName"];
                string containerUniqueName = ConfigurationManager.AppSettings["RsVaultIaasVMContainerUniqueNameRestore"];
                string containeType        = ConfigurationManager.AppSettings["IaaSVMContainerType"];
                string itemUniqueName      = ConfigurationManager.AppSettings["RsVaultIaasVMItemUniqueNameRestore"];
                string itemType            = ConfigurationManager.AppSettings["IaaSVMItemType"];
                string recoveryPointId     = ConfigurationManager.AppSettings["RecoveryPointName"];
                string storageAccountId    = ConfigurationManager.AppSettings["StorageAccountId"];
                string sourceResourceId    = ConfigurationManager.AppSettings["SourceVmIdForRestore"];

                var client = GetServiceClient <RecoveryServicesBackupManagementClient>(resourceNamespace);

                string resourceGroupName = ConfigurationManager.AppSettings["RsVaultRgNameRestore"];
                string resourceName      = ConfigurationManager.AppSettings["RsVaultNameRestore"];
                string containerUri      = containeType + ";" + containerUniqueName;
                string itemUri           = itemType + ";" + itemUniqueName;

                IaasVMRestoreRequest restoreRequest = new IaasVMRestoreRequest()
                {
                    AffinityGroup         = String.Empty,
                    CreateNewCloudService = false,
                    RecoveryPointId       = recoveryPointId,
                    RecoveryType          = RecoveryType.RestoreDisks,
                    Region                 = vaultLocation,
                    StorageAccountId       = storageAccountId,
                    SubnetId               = string.Empty,
                    VirtualNetworkId       = string.Empty,
                    SourceResourceId       = sourceResourceId,
                    TargetDomainNameId     = string.Empty,
                    TargetResourceGroupId  = string.Empty,
                    TargetVirtualMachineId = string.Empty,
                };

                TriggerRestoreRequest triggerRestoreRequest = new TriggerRestoreRequest();
                triggerRestoreRequest.Item            = new RestoreRequestResource();
                triggerRestoreRequest.Item.Properties = new RestoreRequest();
                triggerRestoreRequest.Item.Properties = restoreRequest;

                var response = client.Restores.TriggerRestore(resourceGroupName, resourceName, CommonTestHelper.GetCustomRequestHeaders(),
                                                              fabricName, containerUri, itemUri, recoveryPointId, triggerRestoreRequest);

                Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
                Assert.True(!string.IsNullOrEmpty(response.Location), "Location cant be null");
            }
        }
Example #5
0
        /// <summary>
        /// The Trigger Restore Operation starts an operation in the service
        /// which triggers the restore of the specified item in the specified
        /// container in your Recovery Services Vault based on the specified
        /// recovery point ID. This is an asynchronous operation. To determine
        /// whether the backend service has finished processing the request,
        /// call Get Protected Item Operation Result API.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. Resource group name of your recovery services vault.
        /// </param>
        /// <param name='resourceName'>
        /// Required. Name of your recovery services vault.
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Optional. Request header parameters.
        /// </param>
        /// <param name='fabricName'>
        /// Optional. Fabric name of the protected item.
        /// </param>
        /// <param name='containerName'>
        /// Optional. Name of the container where the protected item belongs to.
        /// </param>
        /// <param name='protectedItemName'>
        /// Optional. Name of the protected item whose recovery points are to
        /// be fetched.
        /// </param>
        /// <param name='recoveryPointId'>
        /// Optional. ID of the recovery point whose details are to be fetched.
        /// </param>
        /// <param name='request'>
        /// Optional. Restore request for the backup item.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Base recovery job response for all the asynchronous operations.
        /// </returns>
        public async Task <BaseRecoveryServicesJobResponse> TriggerRestoreAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName, string containerName, string protectedItemName, string recoveryPointId, TriggerRestoreRequest request, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceName == null)
            {
                throw new ArgumentNullException("resourceName");
            }
            if (request != null)
            {
                if (request.Item != null)
                {
                    if (request.Item.Properties == null)
                    {
                        throw new ArgumentNullException("request.Item.Properties");
                    }
                }
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("resourceName", resourceName);
                tracingParameters.Add("customRequestHeaders", customRequestHeaders);
                tracingParameters.Add("fabricName", fabricName);
                tracingParameters.Add("containerName", containerName);
                tracingParameters.Add("protectedItemName", protectedItemName);
                tracingParameters.Add("recoveryPointId", recoveryPointId);
                tracingParameters.Add("request", request);
                TracingAdapter.Enter(invocationId, this, "TriggerRestoreAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            if (this.Client.ResourceNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            }
            url = url + "/";
            url = url + "vaults";
            url = url + "/";
            url = url + Uri.EscapeDataString(resourceName);
            url = url + "/backupFabrics/";
            if (fabricName != null)
            {
                url = url + Uri.EscapeDataString(fabricName);
            }
            url = url + "/protectionContainers/";
            if (containerName != null)
            {
                url = url + Uri.EscapeDataString(containerName);
            }
            url = url + "/protectedItems/";
            if (protectedItemName != null)
            {
                url = url + Uri.EscapeDataString(protectedItemName);
            }
            url = url + "/recoveryPoints/";
            if (recoveryPointId != null)
            {
                url = url + Uri.EscapeDataString(recoveryPointId);
            }
            url = url + "/restore";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=2016-05-01");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Post;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture);
                httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string requestContent = null;
                JToken requestDoc     = null;

                if (request != null)
                {
                    if (request.Item != null)
                    {
                        JObject itemValue = new JObject();
                        requestDoc = itemValue;

                        JObject propertiesValue = new JObject();
                        itemValue["properties"] = propertiesValue;
                        if (request.Item.Properties is IaasVMRestoreRequest)
                        {
                            propertiesValue["objectType"] = "IaasVMRestoreRequest";
                            IaasVMRestoreRequest derived = ((IaasVMRestoreRequest)request.Item.Properties);

                            if (derived.RecoveryPointId != null)
                            {
                                propertiesValue["recoveryPointId"] = derived.RecoveryPointId;
                            }

                            if (derived.RecoveryType != null)
                            {
                                propertiesValue["recoveryType"] = derived.RecoveryType;
                            }

                            if (derived.StorageAccountId != null)
                            {
                                propertiesValue["storageAccountId"] = derived.StorageAccountId;
                            }

                            propertiesValue["createNewCloudService"] = derived.CreateNewCloudService;

                            if (derived.VirtualNetworkId != null)
                            {
                                propertiesValue["virtualNetworkId"] = derived.VirtualNetworkId;
                            }

                            if (derived.Region != null)
                            {
                                propertiesValue["region"] = derived.Region;
                            }

                            if (derived.AffinityGroup != null)
                            {
                                propertiesValue["affinityGroup"] = derived.AffinityGroup;
                            }

                            if (derived.SubnetId != null)
                            {
                                propertiesValue["subnetId"] = derived.SubnetId;
                            }

                            if (derived.SourceResourceId != null)
                            {
                                propertiesValue["sourceResourceId"] = derived.SourceResourceId;
                            }

                            if (derived.TargetVirtualMachineId != null)
                            {
                                propertiesValue["targetVirtualMachineId"] = derived.TargetVirtualMachineId;
                            }

                            if (derived.TargetResourceGroupId != null)
                            {
                                propertiesValue["targetResourceGroupId"] = derived.TargetResourceGroupId;
                            }

                            if (derived.TargetDomainNameId != null)
                            {
                                propertiesValue["targetDomainNameId"] = derived.TargetDomainNameId;
                            }
                        }
                    }
                }

                requestContent      = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    BaseRecoveryServicesJobResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new BaseRecoveryServicesJobResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken locationValue = responseDoc["location"];
                            if (locationValue != null && locationValue.Type != JTokenType.Null)
                            {
                                string locationInstance = ((string)locationValue);
                                result.Location = locationInstance;
                            }

                            JToken azureAsyncOperationValue = responseDoc["azureAsyncOperation"];
                            if (azureAsyncOperationValue != null && azureAsyncOperationValue.Type != JTokenType.Null)
                            {
                                string azureAsyncOperationInstance = ((string)azureAsyncOperationValue);
                                result.AzureAsyncOperation = azureAsyncOperationInstance;
                            }

                            JToken retryAfterValue = responseDoc["retryAfter"];
                            if (retryAfterValue != null && retryAfterValue.Type != JTokenType.Null)
                            {
                                string retryAfterInstance = ((string)retryAfterValue);
                                result.RetryAfter = retryAfterInstance;
                            }

                            JToken statusValue = responseDoc["Status"];
                            if (statusValue != null && statusValue.Type != JTokenType.Null)
                            {
                                OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)statusValue), true));
                                result.Status = statusInstance;
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
                    {
                        result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
                    }
                    if (httpResponse.Headers.Contains("Location"))
                    {
                        result.Location = httpResponse.Headers.GetValues("Location").FirstOrDefault();
                    }
                    if (httpResponse.Headers.Contains("Retry-After"))
                    {
                        result.RetryAfter = httpResponse.Headers.GetValues("Retry-After").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }