Example #1
0
        /// <summary>
        /// Creates policy given the provider data
        /// </summary>
        /// <returns>Created policy object as returned by the service</returns>
        public ProtectionPolicyResource CreatePolicy()
        {
            string vaultName         = (string)ProviderData[VaultParams.VaultName];
            string resourceGroupName = (string)ProviderData[VaultParams.ResourceGroupName];
            string policyName        = (string)ProviderData[PolicyParams.PolicyName];

            CmdletModel.WorkloadType workloadType =
                (CmdletModel.WorkloadType)ProviderData[PolicyParams.WorkloadType];
            RetentionPolicyBase retentionPolicy =
                ProviderData.ContainsKey(PolicyParams.RetentionPolicy) ?
                (RetentionPolicyBase)ProviderData[PolicyParams.RetentionPolicy] :
                null;

            ValidateAzureSqlWorkloadType(workloadType);

            // validate RetentionPolicy
            ValidateAzureSqlRetentionPolicy(retentionPolicy);
            Logger.Instance.WriteDebug("Validation of Retention policy is successful");

            // construct Hydra policy request
            ProtectionPolicyResource protectionPolicyResource = new ProtectionPolicyResource()
            {
                Properties = new AzureSqlProtectionPolicy()
                {
                    RetentionPolicy = PolicyHelpers.GetServiceClientSimpleRetentionPolicy(
                        (CmdletModel.SimpleRetentionPolicy)retentionPolicy)
                }
            };

            return(ServiceClientAdapter.CreateOrUpdateProtectionPolicy(
                       policyName,
                       protectionPolicyResource,
                       vaultName: vaultName,
                       resourceGroupName: resourceGroupName).Body);
        }
Example #2
0
        CreateOrUpdateProtectionPolicy(
            string policyName,
            ProtectionPolicyResource request,
            string vaultName            = null,
            string resourceGroupName    = null,
            string auxiliaryAccessToken = "",
            bool isMUAProtected         = false)
        {
            Dictionary <string, List <string> > customHeaders = new Dictionary <string, List <string> >();
            string operationRequest = null;

            if (isMUAProtected)
            {
                List <ResourceGuardProxyBaseResource> resourceGuardMapping = ListResourceGuardMapping(vaultName, resourceGroupName);

                if (resourceGuardMapping != null && resourceGuardMapping.Count != 0)
                {
                    foreach (ResourceGuardOperationDetail operationDetail in resourceGuardMapping[0].Properties.ResourceGuardOperationDetails)
                    {
                        if (operationDetail.VaultCriticalOperation == "Microsoft.RecoveryServices/vaults/backupPolicies/write")
                        {
                            operationRequest = operationDetail.DefaultResourceRequest;
                        }
                    }

                    if (operationRequest != null)
                    {
                        request.Properties.ResourceGuardOperationRequests = new List <string>();
                        request.Properties.ResourceGuardOperationRequests.Add(operationRequest);
                    }
                }
            }

            if (auxiliaryAccessToken != null && auxiliaryAccessToken != "")
            {
                if (operationRequest != null)
                {
                    customHeaders.Add("x-ms-authorization-auxiliary", new List <string> {
                        "Bearer " + auxiliaryAccessToken
                    });
                }
                else if (!isMUAProtected)
                {
                    throw new ArgumentException(String.Format(Resources.PolicyUpdateNotCritical));
                }
                else
                {
                    throw new ArgumentException(String.Format(Resources.UnexpectedParameterToken, "ModifyPolicy"));
                }
            }

            return(BmsAdapter.Client.ProtectionPolicies.CreateOrUpdateWithHttpMessagesAsync(
                       vaultName ?? BmsAdapter.GetResourceName(),
                       resourceGroupName ?? BmsAdapter.GetResourceGroupName(),
                       policyName,
                       request,
                       customHeaders,
                       cancellationToken: BmsAdapter.CmdletCancellationToken).Result);
        }
Example #3
0
 CreateOrUpdateProtectionPolicy(string policyName, ProtectionPolicyResource request)
 {
     return(BmsAdapter.Client.ProtectionPolicies.CreateOrUpdateWithHttpMessagesAsync(
                BmsAdapter.GetResourceName(),
                BmsAdapter.GetResourceGroupName(),
                policyName,
                request,
                cancellationToken: BmsAdapter.CmdletCancellationToken).Result);
 }
        public ProtectionPolicyResource GetPolicyWithRetries(string policyName)
        {
            ProtectionPolicyResource policy = null;

            RetryActionWithTimeout(
                () => policy = BackupClient.ProtectionPolicies.Get(VaultName, ResourceGroup, policyName),
                () => policy != null,
                TimeSpan.FromMinutes(5),
                ResourceNotSyncedRetryLogic);

            return(policy);
        }
Example #5
0
        /// <summary>
        /// Creates policy given the provider data
        /// </summary>
        /// <returns>Created policy object as returned by the service</returns>
        public ProtectionPolicyResource CreatePolicy()
        {
            string policyName = (string)ProviderData[PolicyParams.PolicyName];

            CmdletModel.WorkloadType workloadType =
                (CmdletModel.WorkloadType)ProviderData[PolicyParams.WorkloadType];
            RetentionPolicyBase retentionPolicy =
                ProviderData.ContainsKey(PolicyParams.RetentionPolicy) ?
                (RetentionPolicyBase)ProviderData[PolicyParams.RetentionPolicy] :
                null;
            SchedulePolicyBase schedulePolicy =
                ProviderData.ContainsKey(PolicyParams.SchedulePolicy) ?
                (SchedulePolicyBase)ProviderData[PolicyParams.SchedulePolicy] :
                null;

            // do validations
            ValidateAzureVMWorkloadType(workloadType);
            ValidateAzureVMSchedulePolicy(schedulePolicy);
            Logger.Instance.WriteDebug("Validation of Schedule policy is successful");

            // validate RetentionPolicy
            ValidateAzureVMRetentionPolicy(retentionPolicy);
            Logger.Instance.WriteDebug("Validation of Retention policy is successful");

            // update the retention times from backupSchedule to retentionPolicy after converting to UTC
            CopyScheduleTimeToRetentionTimes((CmdletModel.LongTermRetentionPolicy)retentionPolicy,
                                             (CmdletModel.SimpleSchedulePolicy)schedulePolicy);
            Logger.Instance.WriteDebug("Copy of RetentionTime from with SchedulePolicy to RetentionPolicy is successful");

            // Now validate both RetentionPolicy and SchedulePolicy together
            PolicyHelpers.ValidateLongTermRetentionPolicyWithSimpleRetentionPolicy(
                (CmdletModel.LongTermRetentionPolicy)retentionPolicy,
                (CmdletModel.SimpleSchedulePolicy)schedulePolicy);
            Logger.Instance.WriteDebug("Validation of Retention policy with Schedule policy is successful");

            // construct Service Client policy request
            ProtectionPolicyResource serviceClientRequest = new ProtectionPolicyResource()
            {
                Properties = new AzureIaaSVMProtectionPolicy()
                {
                    RetentionPolicy = PolicyHelpers.GetServiceClientLongTermRetentionPolicy(
                        (CmdletModel.LongTermRetentionPolicy)retentionPolicy),
                    SchedulePolicy = PolicyHelpers.GetServiceClientSimpleSchedulePolicy(
                        (CmdletModel.SimpleSchedulePolicy)schedulePolicy)
                }
            };

            return(ServiceClientAdapter.CreateOrUpdateProtectionPolicy(
                       policyName,
                       serviceClientRequest).Body);
        }
Example #6
0
        public void ListDefaultPolicy()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
                using (var testHelper = new TestHelper()
                {
                    VaultName = PoliciesTestVault, ResourceGroup = PoliciesTestVaultRg
                })
                {
                    testHelper.Initialize(context);
                    List <ProtectionPolicyResource> policies = testHelper.ListAllPoliciesWithRetries();
                    Assert.Contains(policies, policy => policy.Name.ToLower().Equals("defaultpolicy"));

                    ProtectionPolicyResource defaultPolicy = testHelper.GetPolicyWithRetries("defaultpolicy");

                    Assert.NotNull(defaultPolicy);
                    Assert.Equal("defaultpolicy", defaultPolicy.Name.ToLower());
                }
        }
Example #7
0
        /// <summary>
        /// Fetches policies by name
        /// </summary>
        /// <param name="policyName">Name of the policy to be fetched</param>
        /// <param name="serviceClientAdapter">Service client adapter with which to make calls</param>
        /// <param name="vaultName"></param>
        /// <param name="resourceGroupName"></param>
        /// <returns></returns>
        public static ProtectionPolicyResource GetProtectionPolicyByName(
            string policyName,
            ServiceClientAdapter serviceClientAdapter,
            string vaultName         = null,
            string resourceGroupName = null)
        {
            ProtectionPolicyResource response = null;

            try
            {
                response = serviceClientAdapter.GetProtectionPolicy(
                    policyName,
                    vaultName: vaultName,
                    resourceGroupName: resourceGroupName);
                Logger.Instance.WriteDebug("Successfully fetched policy from service: " + policyName);
            }
            catch (AggregateException exception)
            {
                // if http response is NotFound - then ignore and return NULL response
                if (exception.InnerException != null && exception.InnerException is CloudException)
                {
                    var cloudEx = exception.InnerException as CloudException;
                    if (cloudEx.Response != null)
                    {
                        if (cloudEx.Response.StatusCode != SystemNet.HttpStatusCode.NotFound)
                        {
                            Logger.Instance.WriteDebug("CloudException Response statusCode: " +
                                                       cloudEx.Response.StatusCode);
                            throw;
                        }
                    }
                    else
                    {
                        throw;
                    }
                }
                else
                {
                    throw;
                }
            }

            return(response);
        }
Example #8
0
        /// <summary>
        /// Modifies policy using the provider data
        /// </summary>
        /// <returns>Modified policy object as returned by the service</returns>
        public RestAzureNS.AzureOperationResponse <ProtectionPolicyResource> ModifyPolicy()
        {
            string vaultName                    = (string)ProviderData[VaultParams.VaultName];
            string resourceGroupName            = (string)ProviderData[VaultParams.ResourceGroupName];
            RetentionPolicyBase retentionPolicy =
                ProviderData.ContainsKey(PolicyParams.RetentionPolicy) ?
                (RetentionPolicyBase)ProviderData[PolicyParams.RetentionPolicy] :
                null;

            PolicyBase policy =
                ProviderData.ContainsKey(PolicyParams.ProtectionPolicy) ?
                (PolicyBase)ProviderData[PolicyParams.ProtectionPolicy] :
                null;

            // RetentionPolicy
            if (retentionPolicy == null)
            {
                throw new ArgumentException(Resources.RetentionPolicyEmptyInAzureSql);
            }
            else
            {
                ValidateAzureSqlRetentionPolicy(retentionPolicy);
                ((AzureSqlPolicy)policy).RetentionPolicy = retentionPolicy;
                Logger.Instance.WriteDebug("Validation of Retention policy is successful");
            }

            CmdletModel.SimpleRetentionPolicy sqlRetentionPolicy =
                (CmdletModel.SimpleRetentionPolicy)((AzureSqlPolicy)policy).RetentionPolicy;
            ProtectionPolicyResource protectionPolicyResource = new ProtectionPolicyResource()
            {
                Properties = new AzureSqlProtectionPolicy()
                {
                    RetentionPolicy =
                        PolicyHelpers.GetServiceClientSimpleRetentionPolicy(sqlRetentionPolicy)
                }
            };

            return(ServiceClientAdapter.CreateOrUpdateProtectionPolicy(
                       policy.Name,
                       protectionPolicyResource,
                       vaultName: vaultName,
                       resourceGroupName: resourceGroupName));
        }
        public string EnableProtection(string containerName, string protectedItemName, string policyName)
        {
            ProtectionPolicyResource policy = GetPolicyWithRetries(policyName);

            BackupClient.ProtectionContainers.Refresh(VaultName, ResourceGroup, FabricName);

            ODataQuery <BMSPOQueryObject> query = new ODataQuery <BMSPOQueryObject>(po => po.BackupManagementType == BackupManagementType.AzureIaasVM);

            IPage <WorkloadProtectableItemResource> protectableItems = BackupClient.BackupProtectableItems.List(VaultName, ResourceGroup, odataQuery: query);

            var desiredProtectedItem = (AzureIaaSComputeVMProtectableItem)protectableItems.First(
                protectableItem => containerName.ToLower().Contains(protectableItem.Name.ToLower())
                ).Properties;

            Assert.NotNull(desiredProtectedItem);

            var item = new ProtectedItemResource()
            {
                Properties = new AzureIaaSComputeVMProtectedItem()
                {
                    PolicyId         = policy.Id,
                    SourceResourceId = desiredProtectedItem.VirtualMachineId,
                }
            };

            var response = BackupClient.ProtectedItems.CreateOrUpdateWithHttpMessagesAsync(
                VaultName, ResourceGroup, FabricName, containerName, protectedItemName, item).Result;

            ValidateOperationResponse(response);

            var jobResponse = GetOperationResponse <ProtectedItemResource, OperationStatusJobExtendedInfo>(
                containerName, protectedItemName, response,
                operationId => BackupClient.ProtectedItemOperationResults.GetWithHttpMessagesAsync(
                    VaultName, ResourceGroup, FabricName, containerName, protectedItemName, operationId).Result,
                operationId => BackupClient.ProtectedItemOperationStatuses.GetWithHttpMessagesAsync(
                    VaultName, ResourceGroup, FabricName, containerName, protectedItemName, operationId).Result);

            Assert.NotNull(jobResponse.JobId);

            return(jobResponse.JobId);
        }
Example #10
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId);
                string vaultName         = resourceIdentifier.ResourceName;
                string resourceGroupName = resourceIdentifier.ResourceGroupName;

                WriteDebug(string.Format("Input params - Policy: {0}" +
                                         "RetentionPolicy:{1}, SchedulePolicy:{2}",
                                         Policy == null ? "NULL" : Policy.ToString(),
                                         RetentionPolicy == null ? "NULL" : RetentionPolicy.ToString(),
                                         SchedulePolicy == null ? "NULL" : SchedulePolicy.ToString()));

                // Validate policy name
                PolicyCmdletHelpers.ValidateProtectionPolicyName(Policy.Name);

                // Validate if policy already exists
                ProtectionPolicyResource servicePolicy = PolicyCmdletHelpers.GetProtectionPolicyByName(
                    Policy.Name,
                    ServiceClientAdapter,
                    vaultName: vaultName,
                    resourceGroupName: resourceGroupName);
                if (servicePolicy == null)
                {
                    throw new ArgumentException(string.Format(Resources.PolicyNotFoundException,
                                                              Policy.Name));
                }

                PsBackupProviderManager providerManager = new PsBackupProviderManager(
                    new Dictionary <System.Enum, object>()
                {
                    { VaultParams.VaultName, vaultName },
                    { VaultParams.ResourceGroupName, resourceGroupName },
                    { PolicyParams.ProtectionPolicy, Policy },
                    { PolicyParams.RetentionPolicy, RetentionPolicy },
                    { PolicyParams.SchedulePolicy, SchedulePolicy },
                }, ServiceClientAdapter);

                IPsBackupProvider psBackupProvider = providerManager.GetProviderInstance(
                    Policy.WorkloadType, Policy.BackupManagementType);
                AzureOperationResponse <ProtectionPolicyResource> policyResponse =
                    psBackupProvider.ModifyPolicy();
                WriteDebug("ModifyPolicy http response from service: " +
                           policyResponse.Response.StatusCode.ToString());

                if (policyResponse.Response.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    // Track OperationStatus URL for operation completion

                    string policyName = Policy.Name;

                    ServiceClientModel.OperationStatus operationStatus =
                        TrackingHelpers.GetOperationStatus(
                            policyResponse,
                            operationId =>
                            ServiceClientAdapter.GetProtectionPolicyOperationStatus(
                                policyName,
                                operationId,
                                vaultName: vaultName,
                                resourceGroupName: resourceGroupName));

                    WriteDebug("Final operation status: " + operationStatus.Status);

                    if (operationStatus.Properties != null &&
                        ((OperationStatusJobsExtendedInfo)operationStatus.Properties)
                        .JobIds != null)
                    {
                        // get list of jobIds and return jobResponses
                        WriteObject(GetJobObject(
                                        ((OperationStatusJobsExtendedInfo)operationStatus.Properties).JobIds,
                                        vaultName: vaultName,
                                        resourceGroupName: resourceGroupName));
                    }

                    if (operationStatus.Status == OperationStatusValues.Failed)
                    {
                        // if operation failed, then trace error and throw exception
                        if (operationStatus.Error != null)
                        {
                            WriteDebug(string.Format(
                                           "OperationStatus Error: {0} " +
                                           "OperationStatus Code: {1}",
                                           operationStatus.Error.Message,
                                           operationStatus.Error.Code));
                        }
                    }
                }
                else
                {
                    // ServiceClient will return OK if NO datasources are associated with this policy
                    WriteDebug("No datasources are associated with Policy, http response code: " +
                               policyResponse.Response.StatusCode.ToString());
                }
            }, ShouldProcess(Policy.Name, VerbsCommon.Set));
        }
        private RestAzureNS.AzureOperationResponse <ProtectionPolicyResource> CreateorModifyPolicy()
        {
            string vaultName         = (string)ProviderData[VaultParams.VaultName];
            string resourceGroupName = (string)ProviderData[VaultParams.ResourceGroupName];
            string policyName        = ProviderData.ContainsKey(PolicyParams.PolicyName) ?
                                       (string)ProviderData[PolicyParams.PolicyName] : null;
            RetentionPolicyBase retentionPolicy =
                ProviderData.ContainsKey(PolicyParams.RetentionPolicy) ?
                (RetentionPolicyBase)ProviderData[PolicyParams.RetentionPolicy] :
                null;
            SchedulePolicyBase schedulePolicy =
                ProviderData.ContainsKey(PolicyParams.SchedulePolicy) ?
                (SchedulePolicyBase)ProviderData[PolicyParams.SchedulePolicy] :
                null;
            PolicyBase policy =
                ProviderData.ContainsKey(PolicyParams.ProtectionPolicy) ?
                (PolicyBase)ProviderData[PolicyParams.ProtectionPolicy] :
                null;
            bool fixForInconsistentItems = ProviderData.ContainsKey(PolicyParams.FixForInconsistentItems) ?
                                           (bool)ProviderData[PolicyParams.FixForInconsistentItems] : false;
            ProtectionPolicyResource serviceClientRequest = new ProtectionPolicyResource();

            if (policy != null)
            {
                // do validations
                ValidateAzureWorkloadProtectionPolicy(policy);
                Logger.Instance.WriteDebug("Validation of Protection Policy is successful");

                // RetentionPolicy and SchedulePolicy both should not be empty
                if (retentionPolicy == null && schedulePolicy == null)
                {
                    if (fixForInconsistentItems == false)
                    {
                        throw new ArgumentException(Resources.BothRetentionAndSchedulePoliciesEmpty);
                    }
                    AzureVmWorkloadProtectionPolicy azureVmWorkloadModifyPolicy = new AzureVmWorkloadProtectionPolicy();
                    azureVmWorkloadModifyPolicy.Settings = new Settings("UTC",
                                                                        ((AzureVmWorkloadPolicy)policy).IsCompression,
                                                                        ((AzureVmWorkloadPolicy)policy).IsCompression);
                    azureVmWorkloadModifyPolicy.WorkLoadType         = ConversionUtils.GetServiceClientWorkloadType(policy.WorkloadType.ToString());
                    azureVmWorkloadModifyPolicy.SubProtectionPolicy  = new List <SubProtectionPolicy>();
                    azureVmWorkloadModifyPolicy.SubProtectionPolicy  = PolicyHelpers.GetServiceClientSubProtectionPolicy((AzureVmWorkloadPolicy)policy);
                    azureVmWorkloadModifyPolicy.MakePolicyConsistent = true;
                    serviceClientRequest.Properties = azureVmWorkloadModifyPolicy;
                }
                else
                {
                    // validate RetentionPolicy and SchedulePolicy
                    if (schedulePolicy != null)
                    {
                        AzureWorkloadProviderHelper.ValidateSQLSchedulePolicy(schedulePolicy);
                        AzureWorkloadProviderHelper.GetUpdatedSchedulePolicy(policy, (SQLSchedulePolicy)schedulePolicy);
                        Logger.Instance.WriteDebug("Validation of Schedule policy is successful");
                    }
                    if (retentionPolicy != null)
                    {
                        AzureWorkloadProviderHelper.ValidateSQLRetentionPolicy(retentionPolicy);
                        AzureWorkloadProviderHelper.GetUpdatedRetentionPolicy(policy, (SQLRetentionPolicy)retentionPolicy);
                        Logger.Instance.WriteDebug("Validation of Retention policy is successful");
                    }

                    // copy the backupSchedule time to retentionPolicy after converting to UTC
                    AzureWorkloadProviderHelper.CopyScheduleTimeToRetentionTimes(
                        (CmdletModel.LongTermRetentionPolicy)((AzureVmWorkloadPolicy)policy).FullBackupRetentionPolicy,
                        (CmdletModel.SimpleSchedulePolicy)((AzureVmWorkloadPolicy)policy).FullBackupSchedulePolicy);
                    Logger.Instance.WriteDebug("Copy of RetentionTime from with SchedulePolicy to RetentionPolicy is successful");

                    // Now validate both RetentionPolicy and SchedulePolicy matches or not
                    PolicyHelpers.ValidateLongTermRetentionPolicyWithSimpleRetentionPolicy(
                        (CmdletModel.LongTermRetentionPolicy)((AzureVmWorkloadPolicy)policy).FullBackupRetentionPolicy,
                        (CmdletModel.SimpleSchedulePolicy)((AzureVmWorkloadPolicy)policy).FullBackupSchedulePolicy);
                    Logger.Instance.WriteDebug("Validation of Retention policy with Schedule policy is successful");

                    // construct Service Client policy request
                    AzureVmWorkloadProtectionPolicy azureVmWorkloadProtectionPolicy = new AzureVmWorkloadProtectionPolicy();
                    azureVmWorkloadProtectionPolicy.Settings = new Settings("UTC",
                                                                            ((AzureVmWorkloadPolicy)policy).IsCompression,
                                                                            ((AzureVmWorkloadPolicy)policy).IsCompression);
                    azureVmWorkloadProtectionPolicy.WorkLoadType        = ConversionUtils.GetServiceClientWorkloadType(policy.WorkloadType.ToString());
                    azureVmWorkloadProtectionPolicy.SubProtectionPolicy = new List <SubProtectionPolicy>();
                    azureVmWorkloadProtectionPolicy.SubProtectionPolicy = PolicyHelpers.GetServiceClientSubProtectionPolicy((AzureVmWorkloadPolicy)policy);
                    serviceClientRequest.Properties = azureVmWorkloadProtectionPolicy;
                }
            }
            else
            {
                CmdletModel.WorkloadType workloadType =
                    (CmdletModel.WorkloadType)ProviderData[PolicyParams.WorkloadType];

                // do validations
                ValidateAzureWorkloadWorkloadType(workloadType);
                AzureWorkloadProviderHelper.ValidateSQLSchedulePolicy(schedulePolicy);
                Logger.Instance.WriteDebug("Validation of Schedule policy is successful");

                // validate RetentionPolicy
                AzureWorkloadProviderHelper.ValidateSQLRetentionPolicy(retentionPolicy);
                Logger.Instance.WriteDebug("Validation of Retention policy is successful");

                // update the retention times from backupSchedule to retentionPolicy after converting to UTC
                AzureWorkloadProviderHelper.CopyScheduleTimeToRetentionTimes(((SQLRetentionPolicy)retentionPolicy).FullBackupRetentionPolicy,
                                                                             ((SQLSchedulePolicy)schedulePolicy).FullBackupSchedulePolicy);
                Logger.Instance.WriteDebug("Copy of RetentionTime from with SchedulePolicy to RetentionPolicy is successful");

                // Now validate both RetentionPolicy and SchedulePolicy together
                PolicyHelpers.ValidateLongTermRetentionPolicyWithSimpleRetentionPolicy(
                    (SQLRetentionPolicy)retentionPolicy,
                    (SQLSchedulePolicy)schedulePolicy);
                Logger.Instance.WriteDebug("Validation of Retention policy with Schedule policy is successful");

                // construct Service Client policy request
                AzureVmWorkloadProtectionPolicy azureVmWorkloadProtectionPolicy = new AzureVmWorkloadProtectionPolicy();
                azureVmWorkloadProtectionPolicy.Settings = new Settings("UTC",
                                                                        ((SQLSchedulePolicy)schedulePolicy).IsCompression,
                                                                        ((SQLSchedulePolicy)schedulePolicy).IsCompression);
                azureVmWorkloadProtectionPolicy.WorkLoadType        = ConversionUtils.GetServiceClientWorkloadType(workloadType.ToString());
                azureVmWorkloadProtectionPolicy.SubProtectionPolicy = new List <SubProtectionPolicy>();
                azureVmWorkloadProtectionPolicy.SubProtectionPolicy = PolicyHelpers.GetServiceClientSubProtectionPolicy(
                    (SQLRetentionPolicy)retentionPolicy,
                    (SQLSchedulePolicy)schedulePolicy);
                serviceClientRequest.Properties = azureVmWorkloadProtectionPolicy;
            }

            return(ServiceClientAdapter.CreateOrUpdateProtectionPolicy(
                       policyName = policyName ?? policy.Name,
                       serviceClientRequest,
                       vaultName: vaultName,
                       resourceGroupName: resourceGroupName));
        }
Example #12
0
        private RestAzureNS.AzureOperationResponse <ProtectionPolicyResource> CreateorModifyPolicy()
        {
            string vaultName         = (string)ProviderData[VaultParams.VaultName];
            string resourceGroupName = (string)ProviderData[VaultParams.ResourceGroupName];
            string policyName        = ProviderData.ContainsKey(PolicyParams.PolicyName) ?
                                       (string)ProviderData[PolicyParams.PolicyName] : null;
            RetentionPolicyBase retentionPolicy =
                ProviderData.ContainsKey(PolicyParams.RetentionPolicy) ?
                (RetentionPolicyBase)ProviderData[PolicyParams.RetentionPolicy] :
                null;
            SchedulePolicyBase schedulePolicy =
                ProviderData.ContainsKey(PolicyParams.SchedulePolicy) ?
                (SchedulePolicyBase)ProviderData[PolicyParams.SchedulePolicy] :
                null;
            PolicyBase policy =
                ProviderData.ContainsKey(PolicyParams.ProtectionPolicy) ?
                (PolicyBase)ProviderData[PolicyParams.ProtectionPolicy] :
                null;
            ProtectionPolicyResource serviceClientRequest = new ProtectionPolicyResource();

            if (policy != null)
            {
                // do validations
                ValidateAzureFileProtectionPolicy(policy);
                Logger.Instance.WriteDebug("Validation of Protection Policy is successful");

                // RetentionPolicy and SchedulePolicy both should not be empty
                if (retentionPolicy == null && schedulePolicy == null)
                {
                    throw new ArgumentException(Resources.BothRetentionAndSchedulePoliciesEmpty);
                }

                // validate RetentionPolicy and SchedulePolicy
                if (schedulePolicy != null)
                {
                    AzureWorkloadProviderHelper.ValidateSimpleSchedulePolicy(schedulePolicy);
                    ((AzureFileSharePolicy)policy).SchedulePolicy = schedulePolicy;
                    Logger.Instance.WriteDebug("Validation of Schedule policy is successful");
                }
                if (retentionPolicy != null)
                {
                    AzureWorkloadProviderHelper.ValidateLongTermRetentionPolicy(retentionPolicy);
                    ((AzureFileSharePolicy)policy).RetentionPolicy = retentionPolicy;
                    Logger.Instance.WriteDebug("Validation of Retention policy is successful");
                }

                // copy the backupSchedule time to retentionPolicy after converting to UTC
                AzureWorkloadProviderHelper.CopyScheduleTimeToRetentionTimes(
                    (CmdletModel.LongTermRetentionPolicy)((AzureFileSharePolicy)policy).RetentionPolicy,
                    (CmdletModel.SimpleSchedulePolicy)((AzureFileSharePolicy)policy).SchedulePolicy);
                Logger.Instance.WriteDebug("Copy of RetentionTime from with SchedulePolicy to RetentionPolicy is successful");

                // Now validate both RetentionPolicy and SchedulePolicy matches or not
                PolicyHelpers.ValidateLongTermRetentionPolicyWithSimpleRetentionPolicy(
                    (CmdletModel.LongTermRetentionPolicy)((AzureFileSharePolicy)policy).RetentionPolicy,
                    (CmdletModel.SimpleSchedulePolicy)((AzureFileSharePolicy)policy).SchedulePolicy);
                Logger.Instance.WriteDebug("Validation of Retention policy with Schedule policy is successful");

                // construct Service Client policy request
                AzureFileShareProtectionPolicy azureFileShareProtectionPolicy = new AzureFileShareProtectionPolicy();
                azureFileShareProtectionPolicy.RetentionPolicy = PolicyHelpers.GetServiceClientLongTermRetentionPolicy(
                    (CmdletModel.LongTermRetentionPolicy)((AzureFileSharePolicy)policy).RetentionPolicy);
                azureFileShareProtectionPolicy.SchedulePolicy = PolicyHelpers.GetServiceClientSimpleSchedulePolicy(
                    (CmdletModel.SimpleSchedulePolicy)((AzureFileSharePolicy)policy).SchedulePolicy);
                azureFileShareProtectionPolicy.TimeZone     = DateTimeKind.Utc.ToString().ToUpper();
                azureFileShareProtectionPolicy.WorkLoadType = ConversionUtils.GetServiceClientWorkloadType(policy.WorkloadType.ToString());
                serviceClientRequest.Properties             = azureFileShareProtectionPolicy;
            }
            else
            {
                CmdletModel.WorkloadType workloadType =
                    (CmdletModel.WorkloadType)ProviderData[PolicyParams.WorkloadType];

                // do validations
                ValidateAzureFilesWorkloadType(workloadType);
                AzureWorkloadProviderHelper.ValidateSimpleSchedulePolicy(schedulePolicy);
                Logger.Instance.WriteDebug("Validation of Schedule policy is successful");

                // validate RetentionPolicy
                AzureWorkloadProviderHelper.ValidateLongTermRetentionPolicy(retentionPolicy);
                Logger.Instance.WriteDebug("Validation of Retention policy is successful");

                // update the retention times from backupSchedule to retentionPolicy after converting to UTC
                AzureWorkloadProviderHelper.CopyScheduleTimeToRetentionTimes((CmdletModel.LongTermRetentionPolicy)retentionPolicy,
                                                                             (CmdletModel.SimpleSchedulePolicy)schedulePolicy);
                Logger.Instance.WriteDebug("Copy of RetentionTime from with SchedulePolicy to RetentionPolicy is successful");

                // Now validate both RetentionPolicy and SchedulePolicy together
                PolicyHelpers.ValidateLongTermRetentionPolicyWithSimpleRetentionPolicy(
                    (CmdletModel.LongTermRetentionPolicy)retentionPolicy,
                    (CmdletModel.SimpleSchedulePolicy)schedulePolicy);
                Logger.Instance.WriteDebug("Validation of Retention policy with Schedule policy is successful");

                // construct Service Client policy request
                AzureFileShareProtectionPolicy azureFileShareProtectionPolicy = new AzureFileShareProtectionPolicy();
                azureFileShareProtectionPolicy.RetentionPolicy = PolicyHelpers.GetServiceClientLongTermRetentionPolicy(
                    (CmdletModel.LongTermRetentionPolicy)retentionPolicy);
                azureFileShareProtectionPolicy.RetentionPolicy = PolicyHelpers.GetServiceClientLongTermRetentionPolicy(
                    (CmdletModel.LongTermRetentionPolicy)retentionPolicy);
                azureFileShareProtectionPolicy.SchedulePolicy = PolicyHelpers.GetServiceClientSimpleSchedulePolicy(
                    (CmdletModel.SimpleSchedulePolicy)schedulePolicy);
                azureFileShareProtectionPolicy.TimeZone     = DateTimeKind.Utc.ToString().ToUpper();
                azureFileShareProtectionPolicy.WorkLoadType = ConversionUtils.GetServiceClientWorkloadType(workloadType.ToString());
                serviceClientRequest.Properties             = azureFileShareProtectionPolicy;
            }

            return(ServiceClientAdapter.CreateOrUpdateProtectionPolicy(
                       policyName = policyName ?? policy.Name,
                       serviceClientRequest,
                       vaultName: vaultName,
                       resourceGroupName: resourceGroupName));
        }
 /// <summary>
 /// Creates or modifies a backup policy. This is an asynchronous operation.
 /// Status of the operation can be fetched
 /// using GetPolicyOperationResult API.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='vaultName'>
 /// The name of the recovery services vault.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group where the recovery services vault is
 /// present.
 /// </param>
 /// <param name='policyName'>
 /// Backup policy to be created.
 /// </param>
 /// <param name='parameters'>
 /// resource backup policy
 /// </param>
 public static ProtectionPolicyResource CreateOrUpdate(this IProtectionPoliciesOperations operations, string vaultName, string resourceGroupName, string policyName, ProtectionPolicyResource parameters)
 {
     return(operations.CreateOrUpdateAsync(vaultName, resourceGroupName, policyName, parameters).GetAwaiter().GetResult());
 }
 /// <summary>
 /// Creates or modifies a backup policy. This is an asynchronous operation.
 /// Status of the operation can be fetched
 /// using GetPolicyOperationResult API.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='vaultName'>
 /// The name of the recovery services vault.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group where the recovery services vault is
 /// present.
 /// </param>
 /// <param name='policyName'>
 /// Backup policy to be created.
 /// </param>
 /// <param name='parameters'>
 /// resource backup policy
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <ProtectionPolicyResource> CreateOrUpdateAsync(this IProtectionPoliciesOperations operations, string vaultName, string resourceGroupName, string policyName, ProtectionPolicyResource parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(vaultName, resourceGroupName, policyName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Example #15
0
        /// <summary>
        /// Creates or modifies a backup policy. This is an asynchronous operation.
        /// Status of the operation can be fetched
        /// using GetPolicyOperationResult API.
        /// </summary>
        /// <param name='vaultName'>
        /// The name of the recovery services vault.
        /// </param>
        /// <param name='resourceGroupName'>
        /// The name of the resource group where the recovery services vault is
        /// present.
        /// </param>
        /// <param name='policyName'>
        /// Backup policy to be created.
        /// </param>
        /// <param name='parameters'>
        /// resource backup policy
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <ProtectionPolicyResource> > CreateOrUpdateWithHttpMessagesAsync(string vaultName, string resourceGroupName, string policyName, ProtectionPolicyResource parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (vaultName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
            }
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (policyName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "policyName");
            }
            if (parameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
            }
            string apiVersion = "2016-12-01";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("vaultName", vaultName);
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("policyName", policyName);
                tracingParameters.Add("parameters", parameters);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupPolicies/{policyName}").ToString();

            _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{policyName}", System.Uri.EscapeDataString(policyName));
            List <string> _queryParameters = new List <string>();

            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PUT");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (parameters != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 202)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex      = new CloudException(_errorBody.Message);
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <ProtectionPolicyResource>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <ProtectionPolicyResource>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Example #16
0
        /// <summary>
        /// Modifies policy using the provider data
        /// </summary>
        /// <returns>Modified policy object as returned by the service</returns>
        public RestAzureNS.AzureOperationResponse <ProtectionPolicyResource> ModifyPolicy()
        {
            RetentionPolicyBase retentionPolicy =
                ProviderData.ContainsKey(PolicyParams.RetentionPolicy) ?
                (RetentionPolicyBase)ProviderData[PolicyParams.RetentionPolicy] :
                null;
            SchedulePolicyBase schedulePolicy =
                ProviderData.ContainsKey(PolicyParams.SchedulePolicy) ?
                (SchedulePolicyBase)ProviderData[PolicyParams.SchedulePolicy] :
                null;

            PolicyBase policy =
                ProviderData.ContainsKey(PolicyParams.ProtectionPolicy) ?
                (PolicyBase)ProviderData[PolicyParams.ProtectionPolicy] :
                null;

            // do validations
            ValidateAzureVMProtectionPolicy(policy);
            Logger.Instance.WriteDebug("Validation of Protection Policy is successful");

            // RetentionPolicy and SchedulePolicy both should not be empty
            if (retentionPolicy == null && schedulePolicy == null)
            {
                throw new ArgumentException(Resources.BothRetentionAndSchedulePoliciesEmpty);
            }

            // validate RetentionPolicy and SchedulePolicy
            if (schedulePolicy != null)
            {
                ValidateAzureVMSchedulePolicy(schedulePolicy);
                ((AzureVmPolicy)policy).SchedulePolicy = schedulePolicy;
                Logger.Instance.WriteDebug("Validation of Schedule policy is successful");
            }
            if (retentionPolicy != null)
            {
                ValidateAzureVMRetentionPolicy(retentionPolicy);
                ((AzureVmPolicy)policy).RetentionPolicy = retentionPolicy;
                Logger.Instance.WriteDebug("Validation of Retention policy is successful");
            }

            // copy the backupSchedule time to retentionPolicy after converting to UTC
            CopyScheduleTimeToRetentionTimes(
                (CmdletModel.LongTermRetentionPolicy)((AzureVmPolicy)policy).RetentionPolicy,
                (CmdletModel.SimpleSchedulePolicy)((AzureVmPolicy)policy).SchedulePolicy);
            Logger.Instance.WriteDebug("Copy of RetentionTime from with SchedulePolicy to RetentionPolicy is successful");

            // Now validate both RetentionPolicy and SchedulePolicy matches or not
            PolicyHelpers.ValidateLongTermRetentionPolicyWithSimpleRetentionPolicy(
                (CmdletModel.LongTermRetentionPolicy)((AzureVmPolicy)policy).RetentionPolicy,
                (CmdletModel.SimpleSchedulePolicy)((AzureVmPolicy)policy).SchedulePolicy);
            Logger.Instance.WriteDebug("Validation of Retention policy with Schedule policy is successful");

            // construct Service Client policy request
            ProtectionPolicyResource serviceClientRequest = new ProtectionPolicyResource()
            {
                Properties = new AzureIaaSVMProtectionPolicy()
                {
                    RetentionPolicy = PolicyHelpers.GetServiceClientLongTermRetentionPolicy(
                        (CmdletModel.LongTermRetentionPolicy)((AzureVmPolicy)policy).RetentionPolicy),
                    SchedulePolicy = PolicyHelpers.GetServiceClientSimpleSchedulePolicy(
                        (CmdletModel.SimpleSchedulePolicy)((AzureVmPolicy)policy).SchedulePolicy)
                }
            };

            return(ServiceClientAdapter.CreateOrUpdateProtectionPolicy(policy.Name,
                                                                       serviceClientRequest));
        }