Esempio n. 1
0
        public void TriggerBackup(string backupInstanceName)
        {
            //JToken requestData = mockJson["Entries"][7]["RequestBody"];
            string requestData        = "{\r\n  \"backupRuleOptions\": {\r\n    \"ruleName\": \"BackupHourly\",\r\n    \"triggerOption\": {\r\n      \"retentionTagOverride\": \"Default\"\r\n    }\r\n  }\r\n}";
            TriggerBackupRequest body = SafeJsonConvert.DeserializeObject <TriggerBackupRequest>(requestData.ToString(), BackupClient.DeserializationSettings);
            var response = BackupClient.BackupInstances.AdhocBackup(VaultName, ResourceGroup, backupInstanceName, body.BackupRuleOptions);

            Assert.NotNull(response);
            Assert.Equal("/subscriptions/62b829ee-7936-40c9-a1c9-47a93f9f3965/resourceGroups/mayaggarDiskRG/providers/Microsoft.DataProtection/backupVaults/DiskbackupVault2/backupJobs/610fe9cb-4196-4508-ab4b-4dbcfdc44b57", response.JobId);
        }
Esempio n. 2
0
        public string BackupProtectedItem(string rsVaultRgName, string rsVaultName, string containerUri, string protectedItemUri)
        {
            string fabricName = CommonTestHelper.GetSetting(TestConstants.ProviderTypeAzureIaasVM);

            TriggerBackupRequest backupRequest = new TriggerBackupRequest();

            backupRequest.Item = new BackupRequestResource();
            IaaSVMBackupRequest iaasVmBackupRequest = new IaaSVMBackupRequest();

            iaasVmBackupRequest.RecoveryPointExpiryTimeInUTC = DateTime.UtcNow.AddDays(2);
            backupRequest.Item.Properties = iaasVmBackupRequest;

            var response = Client.Backups.TriggerBackup(rsVaultRgName, rsVaultName, CommonTestHelper.GetCustomRequestHeaders(),
                                                        fabricName, containerUri, protectedItemUri, backupRequest);

            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);
        }
Esempio n. 3
0
        /// <summary>
        /// Triggers backup on the specified item
        /// </summary>
        /// <param name="containerName">Name of the container which this item belongs to</param>
        /// <param name="itemName">Name of the item</param>
        /// <returns>Job created by this operation</returns>
        public BaseRecoveryServicesJobResponse TriggerBackup(
            string containerName,
            string itemName,
            DateTime?expiryDateTimeUtc)
        {
            TriggerBackupRequest triggerBackupRequest = new TriggerBackupRequest();

            triggerBackupRequest.Item = new BackupRequestResource();
            IaaSVMBackupRequest iaasVmBackupRequest = new IaaSVMBackupRequest();

            iaasVmBackupRequest.RecoveryPointExpiryTimeInUTC = expiryDateTimeUtc;
            triggerBackupRequest.Item.Properties             = iaasVmBackupRequest;

            return(BmsAdapter.Client.Backups.TriggerBackupAsync(
                       BmsAdapter.GetResourceGroupName(),
                       BmsAdapter.GetResourceName(),
                       BmsAdapter.GetCustomRequestHeaders(),
                       ServiceClientAdapter.AzureFabricName,
                       containerName,
                       itemName,
                       triggerBackupRequest,
                       BmsAdapter.CmdletCancellationToken).Result);
        }
 /// <summary>
 /// The Trigger Backup Operation starts an operation in the service
 /// which triggers the backup of the specified item in the specified
 /// container in your Recovery Services Vault. 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='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.RecoveryServices.Backup.IBackupOperations.
 /// </param>
 /// <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'>
 /// Required. 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 which has to be backed up.
 /// </param>
 /// <param name='request'>
 /// Optional. Backup request for the backup item.
 /// </param>
 /// <returns>
 /// Base recovery job response for all the asynchronous operations.
 /// </returns>
 public static BaseRecoveryServicesJobResponse TriggerBackup(this IBackupOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName, string containerName, string protectedItemName, TriggerBackupRequest request)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((IBackupOperations)s).TriggerBackupAsync(resourceGroupName, resourceName, customRequestHeaders, fabricName, containerName, protectedItemName, request);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
 /// <summary>
 /// The Trigger Backup Operation starts an operation in the service
 /// which triggers the backup of the specified item in the specified
 /// container in your Recovery Services Vault. 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='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.RecoveryServices.Backup.IBackupOperations.
 /// </param>
 /// <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'>
 /// Required. 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 which has to be backed up.
 /// </param>
 /// <param name='request'>
 /// Optional. Backup request for the backup item.
 /// </param>
 /// <returns>
 /// Base recovery job response for all the asynchronous operations.
 /// </returns>
 public static Task <BaseRecoveryServicesJobResponse> TriggerBackupAsync(this IBackupOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName, string containerName, string protectedItemName, TriggerBackupRequest request)
 {
     return(operations.TriggerBackupAsync(resourceGroupName, resourceName, customRequestHeaders, fabricName, containerName, protectedItemName, request, CancellationToken.None));
 }
Esempio n. 6
0
        /// <summary>
        /// The Trigger Backup Operation starts an operation in the service
        /// which triggers the backup of the specified item in the specified
        /// container in your Recovery Services Vault. 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'>
        /// Required. 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 which has to be backed up.
        /// </param>
        /// <param name='request'>
        /// Optional. Backup 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> TriggerBackupAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName, string containerName, string protectedItemName, TriggerBackupRequest request, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceName == null)
            {
                throw new ArgumentNullException("resourceName");
            }
            if (customRequestHeaders == null)
            {
                throw new ArgumentNullException("customRequestHeaders");
            }
            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("request", request);
                TracingAdapter.Enter(invocationId, this, "TriggerBackupAsync", 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 + "/backup";
            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 IaaSVMBackupRequest)
                        {
                            propertiesValue["objectType"] = "IaasVMBackupRequest";
                            IaaSVMBackupRequest derived = ((IaaSVMBackupRequest)request.Item.Properties);

                            if (derived.RecoveryPointExpiryTimeInUTC != null)
                            {
                                propertiesValue["recoveryPointExpiryTimeInUTC"] = derived.RecoveryPointExpiryTimeInUTC.Value;
                            }
                        }
                    }
                }

                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();
                }
            }
        }