private void AzureToAzureReplication(EnableProtectionInput input) { var providerSettings = new A2AEnableProtectionInput() { FabricObjectId = this.AzureVmId, RecoveryContainerId = this.ProtectionContainerMapping.TargetProtectionContainerId, VmDisks = new List <A2AVmDiskInputDetails>(), RecoveryResourceGroupId = this.RecoveryResourceGroupId, RecoveryCloudServiceId = this.RecoveryCloudServiceId, RecoveryAvailabilitySetId = this.RecoveryAvailabilitySetId }; // If azureVmDisk Details are null add disk to protect // TODO:: item for other parameterset when customer can pass AzureVmId targetStorageAccount and RecoveryStorageAccount. // will add support when compute dependency is added in common library. foreach (ASRAzuretoAzureDiskReplicationConfig disk in this.AzureToAzureDiskReplicationConfiguration) { providerSettings.VmDisks.Add(new A2AVmDiskInputDetails { DiskUri = disk.VhdUri, RecoveryAzureStorageAccountId = disk.RecoveryAzureStorageAccountId, PrimaryStagingAzureStorageAccountId = disk.LogStorageAccountId, }); } input.Properties.ProviderSpecificDetails = providerSettings; }
/// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteCmdlet() { switch (this.ParameterSetName) { case ASRParameterSets.ByPEObject: this.targetNameOrId = this.ProtectionEntity.FriendlyName; break; } this.ConfirmAction( this.Force.IsPresent || 0 != string.CompareOrdinal(this.Protection, Constants.DisableProtection), string.Format(Properties.Resources.DisableProtectionWarning, this.targetNameOrId), string.Format(Properties.Resources.DisableProtectionWhatIfMessage, this.Protection), this.targetNameOrId, () => { try { // ADD SOME VALIDATIONS if (this.Protection == Constants.EnableProtection) { EnableProtectionInput input = new EnableProtectionInput(); this.response = RecoveryServicesClient.EnableProtection( this.ProtectionEntity.ProtectionContainerId, this.ProtectionEntity.Name, input); } else { DisableProtectionInput input = new DisableProtectionInput(); this.response = RecoveryServicesClient.DisableProtection( this.ProtectionEntity.ProtectionContainerId, this.ProtectionEntity.Name, input); } jobResponse = RecoveryServicesClient .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); WriteObject(new ASRJob(jobResponse.Job)); if (this.WaitForCompletion.IsPresent) { this.WaitForJobCompletion(this.jobResponse.Job.Name); } } catch (Exception exception) { this.HandleException(exception); } }); }
/// <summary> /// Sets protection on Protection entity. /// </summary> /// <param name="protectionContainerId">Protection Container ID</param> /// <param name="virtualMachineId">Virtual Machine ID</param> /// <param name="input">Enable protection input.</param> /// <returns>Job response</returns> public JobResponse EnableProtection( string protectionContainerId, string virtualMachineId, EnableProtectionInput input) { return(this.GetSiteRecoveryClient().ProtectionEntity.EnableProtection( protectionContainerId, virtualMachineId, input, this.GetRequestHeaders())); }
/// <summary> /// Sets protection on Protection entity. /// </summary> /// <param name="protectionContainerId">Protection Container ID</param> /// <param name="protectionEntityId">Virtual Machine ID or Replication group Id</param> /// <param name="input">Enable protection input.</param> /// <returns>Job response</returns> public LongRunningOperationResponse EnableProtection( string protectionContainerId, string protectionEntityId, EnableProtectionInput input) { return(this.GetSiteRecoveryClient().ProtectionEntity.EnableProtection( protectionContainerId, protectionEntityId, input, this.GetRequestHeaders())); }
/// <summary> /// Creates Replicated Protected Item. /// </summary> /// <param name="protectionContainerName">Protection Container ID</param> /// <param name="replicationProtectedItemName">Virtual Machine ID or Replication group Id</param> /// <param name="input">Enable protection input.</param> /// <returns>Job response</returns> public LongRunningOperationResponse EnableProtection(string fabricName, string protectionContainerName, string replicationProtectedItemName, EnableProtectionInput input) { return(this.GetSiteRecoveryClient().ReplicationProtectedItem.BeginEnableProtection( fabricName, protectionContainerName, replicationProtectedItemName, input, this.GetRequestHeaders())); }
/// <summary> /// Creates Replicated Protected Item. /// </summary> /// <param name="protectionContainerName">Protection Container ID</param> /// <param name="replicationProtectedItemName">Virtual Machine ID or Replication group Id</param> /// <param name="input">Enable protection input.</param> /// <returns>Job response</returns> public PSSiteRecoveryLongRunningOperation EnableProtection( string fabricName, string protectionContainerName, string replicationProtectedItemName, EnableProtectionInput input) { var op = this.GetSiteRecoveryClient() .ReplicationProtectedItems.BeginCreateWithHttpMessagesAsync( fabricName, protectionContainerName, replicationProtectedItemName, input, this.GetRequestHeaders(true)) .GetAwaiter() .GetResult(); var result = Mapper.Map <PSSiteRecoveryLongRunningOperation>(op); return(result); }
private void VMwareToAzureReplication(EnableProtectionInput input) { var providerSettings = new InMageAzureV2EnableProtectionInput { ProcessServerId = this.ProcessServer.Id, MasterTargetId = this.ProcessServer.Id, // Assumption: PS and MT are same. RunAsAccountId = this.Account.AccountId, StorageAccountId = this.RecoveryAzureStorageAccountId, TargetAzureNetworkId = this.RecoveryAzureNetworkId, TargetAzureSubnetId = this.RecoveryAzureSubnetName, LogStorageAccountId = this.LogStorageAccountId, MultiVmGroupName = this.ReplicationGroupName, DiskType = this.DiskType, MultiVmGroupId = this.ReplicationGroupName, TargetAzureVmName = string.IsNullOrEmpty(this.RecoveryVmName) ? this.ProtectableItem.FriendlyName : this.RecoveryVmName, EnableRdpOnTargetOption = Constants.NeverEnableRDPOnTargetOption }; if (this.IsParameterBound(c => c.InMageAzureV2DiskInput)) { List <InMageAzureV2DiskInputDetails> inmageAzureV2DiskInput = InMageAzureV2DiskInput.Select( p => new InMageAzureV2DiskInputDetails() { DiskId = p.DiskId, DiskType = p.DiskType, LogStorageAccountId = p.LogStorageAccountId }).ToList(); providerSettings.DisksToInclude = inmageAzureV2DiskInput; } providerSettings.TargetAzureV2ResourceGroupId = this.RecoveryResourceGroupId; // Check if the Replication Group Name is valid. if (this.ReplicationGroupName != null) { // Get all the Protected Items in the Protection Container. var fabricName = Utilities.GetValueFromArmId( this.ProtectableItem.ID, ARMResourceTypeConstants.ReplicationFabrics); var protectionContainerName = Utilities.GetValueFromArmId( this.ProtectableItem.ID, ARMResourceTypeConstants.ReplicationProtectionContainers); var listReplicationProtectedItems = this.RecoveryServicesClient .GetAzureSiteRecoveryReplicationProtectedItem( fabricName, protectionContainerName); // Loop over all the Protected Items and find if the Multi VM Group already exists. var flag = false; foreach (var rpi in listReplicationProtectedItems) // Check if the Replication Protected Item is an InMageAzureV2 Instance. { if (rpi.Properties.ProviderSpecificDetails is InMageAzureV2ReplicationDetails) { // Get the InMageAzureV2 specific details. var providerSpecificDetails = (InMageAzureV2ReplicationDetails)rpi.Properties .ProviderSpecificDetails; // Compare the Multi VM Group Name. if (string.Compare( this.ReplicationGroupName, providerSpecificDetails.MultiVmGroupName, StringComparison.OrdinalIgnoreCase) == 0) { // Multi VM Group found. // Set the values in the InMageAzureV2 Provider specific input. providerSettings.MultiVmGroupName = providerSpecificDetails.MultiVmGroupName; providerSettings.MultiVmGroupId = providerSpecificDetails.MultiVmGroupId; flag = true; break; } } } // Check if the Multi VM Group was found or is to be created now. if (flag == false) { // Multi VM Group was not found. // Create a new Multi VM Group and Set the values in the // InMageAzureV2 Provider specific input. providerSettings.MultiVmGroupName = this.ReplicationGroupName; providerSettings.MultiVmGroupId = Guid.NewGuid().ToString(); } } // Set the InMageAzureV2 Provider specific input in the Enable Protection Input. input.Properties.ProviderSpecificDetails = providerSettings; }
/// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); if (this.ShouldProcess(this.Name, VerbsCommon.New)) { var policy = this.RecoveryServicesClient.GetAzureSiteRecoveryPolicy( Utilities.GetValueFromArmId( this.ProtectionContainerMapping.PolicyId, ARMResourceTypeConstants.ReplicationPolicies)); var policyInstanceType = policy.Properties.ProviderSpecificDetails; var enableProtectionProviderSpecificInput = new EnableProtectionProviderSpecificInput(); var inputProperties = new EnableProtectionInputProperties { PolicyId = this.ProtectionContainerMapping.PolicyId, // A2A there is no ProtectableItem ProtectableItemId = this.ProtectableItem == null ? null : this.ProtectableItem.ID, ProviderSpecificDetails = enableProtectionProviderSpecificInput }; var input = new EnableProtectionInput { Properties = inputProperties }; switch (this.ParameterSetName) { case ASRParameterSets.EnterpriseToEnterprise: if (!(policyInstanceType is HyperVReplicaPolicyDetails) && !(policyInstanceType is HyperVReplicaBluePolicyDetails)) { throw new PSArgumentException( string.Format( Resources.ContainerMappingParameterSetMismatch, this.ProtectionContainerMapping.Name, policyInstanceType)); } break; case ASRParameterSets.EnterpriseToAzure: case ASRParameterSets.HyperVSiteToAzure: if (!(policyInstanceType is HyperVReplicaAzurePolicyDetails)) { throw new PSArgumentException( string.Format( Resources.ContainerMappingParameterSetMismatch, this.ProtectionContainerMapping.Name, policyInstanceType)); } EnterpriseAndHyperVToAzure(input); break; case VMwareToAzureWithDiskType: case VMwareToAzureParameterSet: if (!(policyInstanceType is InMageAzureV2PolicyDetails)) { throw new PSArgumentException( string.Format( Resources.ContainerMappingParameterSetMismatch, this.ProtectionContainerMapping.Name, policyInstanceType)); } VMwareToAzureReplication(input); break; case ASRParameterSets.AzureToAzureWithoutDiskDetails: case ASRParameterSets.AzureToAzure: if (!(policyInstanceType is A2APolicyDetails)) { throw new PSArgumentException( string.Format( Properties.Resources.ContainerMappingParameterSetMismatch, this.ProtectionContainerMapping.Name, policyInstanceType)); } AzureToAzureReplication(input); break; default: break; } this.response = this.RecoveryServicesClient.EnableProtection( Utilities.GetValueFromArmId( this.ProtectionContainerMapping.ID, ARMResourceTypeConstants.ReplicationFabrics), Utilities.GetValueFromArmId( this.ProtectionContainerMapping.ID, ARMResourceTypeConstants.ReplicationProtectionContainers), this.Name, input); this.jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient.GetJobIdFromReponseLocation(this.response.Location)); this.WriteObject(new ASRJob(this.jobResponse)); if (this.WaitForCompletion.IsPresent) { this.WaitForJobCompletion(this.jobResponse.Name); this.jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient .GetJobIdFromReponseLocation(this.response.Location)); this.WriteObject(new ASRJob(this.jobResponse)); } } }
/// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); this.targetNameOrId = this.ProtectionEntity.FriendlyName; this.ConfirmAction( this.Force.IsPresent || 0 != string.CompareOrdinal(this.Protection, Constants.DisableProtection), string.Format(Properties.Resources.DisableProtectionWarning, this.targetNameOrId), string.Format(Properties.Resources.DisableProtectionWhatIfMessage, this.Protection), this.targetNameOrId, () => { if (this.Protection == Constants.EnableProtection) { if (string.Compare(this.ParameterSetName, ASRParameterSets.DisableDR, StringComparison.OrdinalIgnoreCase) == 0) { throw new PSArgumentException(Properties.Resources.PassingPolicyMandatoryForEnablingDR); } EnableProtectionProviderSpecificInput enableProtectionProviderSpecificInput = new EnableProtectionProviderSpecificInput(); EnableProtectionInputProperties inputProperties = new EnableProtectionInputProperties() { PolicyId = this.Policy.ID, ProtectableItemId = this.ProtectionEntity.ID, ProviderSpecificDetails = enableProtectionProviderSpecificInput }; EnableProtectionInput input = new EnableProtectionInput() { Properties = inputProperties }; // Process if block only if policy is not null, policy is created for E2A or B2A and parameter set is for enable DR of E2A or B2A if (this.Policy != null && 0 == string.Compare(this.Policy.ReplicationProvider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase) && (0 == string.Compare(this.ParameterSetName, ASRParameterSets.EnterpriseToAzure, StringComparison.OrdinalIgnoreCase) || 0 == string.Compare(this.ParameterSetName, ASRParameterSets.HyperVSiteToAzure, StringComparison.OrdinalIgnoreCase))) { HyperVReplicaAzureEnableProtectionInput providerSettings = new HyperVReplicaAzureEnableProtectionInput(); providerSettings.HvHostVmId = this.ProtectionEntity.FabricObjectId; providerSettings.VmName = this.ProtectionEntity.FriendlyName; // Id disk details are missing in input PE object, get the latest PE. if (string.IsNullOrEmpty(this.ProtectionEntity.OS)) { // Just checked for OS to see whether the disk details got filled up or not ProtectableItemResponse protectableItemResponse = RecoveryServicesClient.GetAzureSiteRecoveryProtectableItem( Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationFabrics), this.ProtectionEntity.ProtectionContainerId, this.ProtectionEntity.Name); this.ProtectionEntity = new ASRProtectionEntity(protectableItemResponse.ProtectableItem); } if (string.IsNullOrWhiteSpace(this.OS)) { providerSettings.OSType = ((string.Compare(this.ProtectionEntity.OS, Constants.OSWindows) == 0) || (string.Compare(this.ProtectionEntity.OS, Constants.OSLinux) == 0)) ? this.ProtectionEntity.OS : Constants.OSWindows; } else { providerSettings.OSType = this.OS; } if (string.IsNullOrWhiteSpace(this.OSDiskName)) { providerSettings.VhdId = this.ProtectionEntity.OSDiskId; } else { foreach (var disk in this.ProtectionEntity.Disks) { if (0 == string.Compare(disk.Name, this.OSDiskName, true)) { providerSettings.VhdId = disk.Id; break; } } } if (RecoveryAzureStorageAccountId != null) { providerSettings.TargetStorageAccountId = RecoveryAzureStorageAccountId; } input.Properties.ProviderSpecificDetails = providerSettings; } else if (this.Policy != null && 0 == string.Compare(this.Policy.ReplicationProvider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase) && 0 == string.Compare(this.ParameterSetName, ASRParameterSets.EnterpriseToEnterprise, StringComparison.OrdinalIgnoreCase)) { throw new PSArgumentException(Properties.Resources.PassingStorageMandatoryForEnablingDRInAzureScenarios); } this.response = RecoveryServicesClient.EnableProtection( Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationFabrics), Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationProtectionContainers), this.ProtectionEntity.Name, input); } else { // fetch the latest PE object ProtectableItemResponse protectableItemResponse = RecoveryServicesClient.GetAzureSiteRecoveryProtectableItem(Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationFabrics), this.ProtectionEntity.ProtectionContainerId, this.ProtectionEntity.Name); ProtectableItem protectableItem = protectableItemResponse.ProtectableItem; if (!this.Force.IsPresent) { DisableProtectionInput input = new DisableProtectionInput(); input.Properties = new DisableProtectionInputProperties() { ProviderSettings = new DisableProtectionProviderSpecificInput() }; this.response = RecoveryServicesClient.DisableProtection( Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationFabrics), Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationProtectionContainers), Utilities.GetValueFromArmId(protectableItem.Properties.ReplicationProtectedItemId, ARMResourceTypeConstants.ReplicationProtectedItems), input); } else { this.response = RecoveryServicesClient.PurgeProtection( Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationFabrics), Utilities.GetValueFromArmId(this.ProtectionEntity.ID, ARMResourceTypeConstants.ReplicationProtectionContainers), Utilities.GetValueFromArmId(protectableItem.Properties.ReplicationProtectedItemId, ARMResourceTypeConstants.ReplicationProtectedItems) ); } } jobResponse = RecoveryServicesClient .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); WriteObject(new ASRJob(jobResponse.Job)); if (this.WaitForCompletion.IsPresent) { this.WaitForJobCompletion(this.jobResponse.Job.Name); jobResponse = RecoveryServicesClient .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); WriteObject(new ASRJob(jobResponse.Job)); } }); }
/// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); if (this.ShouldProcess( this.Name, VerbsCommon.New)) { var policy = this.RecoveryServicesClient.GetAzureSiteRecoveryPolicy( Utilities.GetValueFromArmId( this.ProtectionContainerMapping.PolicyId, ARMResourceTypeConstants.ReplicationPolicies)); var policyInstanceType = policy.Properties.ProviderSpecificDetails; switch (this.ParameterSetName) { case ASRParameterSets.EnterpriseToEnterprise: if (!(policyInstanceType is HyperVReplicaPolicyDetails) && !(policyInstanceType is HyperVReplicaBluePolicyDetails)) { throw new PSArgumentException( string.Format( Resources.ContainerMappingParameterSetMismatch, this.ProtectionContainerMapping.Name, policyInstanceType)); } break; case ASRParameterSets.EnterpriseToAzure: case ASRParameterSets.HyperVSiteToAzure: if (!(policyInstanceType is HyperVReplicaAzurePolicyDetails)) { throw new PSArgumentException( string.Format( Resources.ContainerMappingParameterSetMismatch, this.ProtectionContainerMapping.Name, policyInstanceType)); } break; default: break; } var enableProtectionProviderSpecificInput = new EnableProtectionProviderSpecificInput(); var inputProperties = new EnableProtectionInputProperties { PolicyId = this.ProtectionContainerMapping.PolicyId, ProtectableItemId = this.ProtectableItem.ID, ProviderSpecificDetails = enableProtectionProviderSpecificInput }; var input = new EnableProtectionInput { Properties = inputProperties }; // E2A and B2A. if ((0 == string.Compare( this.ParameterSetName, ASRParameterSets.EnterpriseToAzure, StringComparison.OrdinalIgnoreCase)) || (0 == string.Compare( this.ParameterSetName, ASRParameterSets.HyperVSiteToAzure, StringComparison.OrdinalIgnoreCase))) { var providerSettings = new HyperVReplicaAzureEnableProtectionInput(); providerSettings.HvHostVmId = this.ProtectableItem.FabricObjectId; providerSettings.VmName = this.ProtectableItem.FriendlyName; providerSettings.TargetAzureVmName = this.ProtectableItem.FriendlyName; // Id disk details are missing in input PE object, get the latest PE. if (string.IsNullOrEmpty(this.ProtectableItem.OS)) { // Just checked for OS to see whether the disk details got filled up or not var protectableItemResponse = this.RecoveryServicesClient .GetAzureSiteRecoveryProtectableItem( Utilities.GetValueFromArmId( this.ProtectableItem.ID, ARMResourceTypeConstants.ReplicationFabrics), this.ProtectableItem.ProtectionContainerId, this.ProtectableItem.Name); this.ProtectableItem = new ASRProtectableItem(protectableItemResponse); } if (string.IsNullOrWhiteSpace(this.OS)) { providerSettings.OsType = (string.Compare( this.ProtectableItem.OS, Constants.OSWindows, StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare( this.ProtectableItem.OS, Constants.OSLinux) == 0) ? this.ProtectableItem.OS : Constants.OSWindows; } else { providerSettings.OsType = this.OS; } if (string.IsNullOrWhiteSpace(this.OSDiskName)) { providerSettings.VhdId = this.ProtectableItem.OSDiskId; } else { foreach (var disk in this.ProtectableItem.Disks) { if (0 == string.Compare( disk.Name, this.OSDiskName, true)) { providerSettings.VhdId = disk.Id; break; } } } if (this.RecoveryAzureStorageAccountId != null) { providerSettings.TargetStorageAccountId = this.RecoveryAzureStorageAccountId; } var deploymentType = Utilities.GetValueFromArmId( this.RecoveryAzureStorageAccountId, ARMResourceTypeConstants.Providers); if (deploymentType.ToLower() .Contains(Constants.Classic.ToLower())) { providerSettings.TargetAzureV1ResourceGroupId = this.RecoveryResourceGroupId; providerSettings.TargetAzureV2ResourceGroupId = null; } else { providerSettings.TargetAzureV1ResourceGroupId = null; providerSettings.TargetAzureV2ResourceGroupId = this.RecoveryResourceGroupId; } input.Properties.ProviderSpecificDetails = providerSettings; } this.response = this.RecoveryServicesClient.EnableProtection( Utilities.GetValueFromArmId( this.ProtectableItem.ID, ARMResourceTypeConstants.ReplicationFabrics), Utilities.GetValueFromArmId( this.ProtectableItem.ID, ARMResourceTypeConstants.ReplicationProtectionContainers), this.Name, input); this.jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient.GetJobIdFromReponseLocation(this.response.Location)); this.WriteObject(new ASRJob(this.jobResponse)); if (this.WaitForCompletion.IsPresent) { this.WaitForJobCompletion(this.jobResponse.Name); this.jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient .GetJobIdFromReponseLocation(this.response.Location)); this.WriteObject(new ASRJob(this.jobResponse)); } } }
public void EndToEndB2ASingleVM() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetSiteRecoveryClient(CustomHttpHandler); bool createPolicy = true; bool pairClouds = true; bool enableDR = true; bool pfo = true; bool commit = true; bool tfo = true; bool pfoReverse = true; bool commitReverse = true; bool reprotect = true; bool disableDR = true; bool unpair = true; bool removePolicy = true; // Process Variables string fabricName = string.Empty; string recCldName = "Microsoft Azure"; string priCldName = string.Empty; string policyName = "Hydra-EndToEndB2ASingleVM-" + (new Random()).Next(); string mappingName = "Mapping-EndToEndB2ASingleVM-" + (new Random()).Next(); string enableDRName = string.Empty; string protectedItemName = "PE" + (new Random()).Next(); // Data Variables Fabric selectedFabric = null; ProtectionContainer primaryCloud = null; Policy selectedPolicy = null; ProtectableItem protectableItem = null; ReplicationProtectedItem protectedItem = null; // Fetch HyperV if (string.IsNullOrEmpty(fabricName)) { var fabrics = client.Fabrics.List(RequestHeaders); foreach (var fabric in fabrics.Fabrics) { if (fabric.Properties.CustomDetails.InstanceType.Contains("HyperV")) { selectedFabric = fabric; fabricName = selectedFabric.Name; } } } else { selectedFabric = client.Fabrics.Get(fabricName, RequestHeaders).Fabric; } // Fetch Cloud primaryCloud = client.ProtectionContainer.List(selectedFabric.Name, RequestHeaders).ProtectionContainers[0]; priCldName = primaryCloud.Name; if (createPolicy) { HyperVReplicaAzurePolicyInput hvrAPolicy = new HyperVReplicaAzurePolicyInput() { ApplicationConsistentSnapshotFrequencyInHours = 0, Encryption = "Disable", OnlineIrStartTime = null, RecoveryPointHistoryDuration = 0, ReplicationInterval = 30, StorageAccounts = new List <string>() { "/subscriptions/19b823e2-d1f3-4805-93d7-401c5d8230d5/resourceGroups/Default-Storage-WestUS/providers/Microsoft.ClassicStorage/storageAccounts/bvtmapped2storacc" } }; CreatePolicyInputProperties createInputProp = new CreatePolicyInputProperties() { ProviderSpecificInput = hvrAPolicy }; CreatePolicyInput policyInput = new CreatePolicyInput() { Properties = createInputProp }; selectedPolicy = (client.Policies.Create(policyName, policyInput, RequestHeaders) as CreatePolicyOperationResponse).Policy; } else { selectedPolicy = client.Policies.Get(policyName, RequestHeaders).Policy; } if (pairClouds) { CreateProtectionContainerMappingInputProperties pairingProps = new CreateProtectionContainerMappingInputProperties() { PolicyId = selectedPolicy.Id, TargetProtectionContainerId = recCldName, ProviderSpecificInput = new ReplicationProviderContainerMappingInput() }; CreateProtectionContainerMappingInput pairingInput = new CreateProtectionContainerMappingInput() { Properties = pairingProps }; var pairingResponse = client.ProtectionContainerMapping.ConfigureProtection( selectedFabric.Name, primaryCloud.Name, mappingName, pairingInput, RequestHeaders); } if (enableDR) { if (string.IsNullOrEmpty(enableDRName)) { protectableItem = client.ProtectableItem.List(selectedFabric.Name, primaryCloud.Name, "Unprotected", RequestHeaders).ProtectableItems[0]; enableDRName = protectableItem.Name; } else { protectableItem = client.ProtectableItem.Get(selectedFabric.Name, primaryCloud.Name, enableDRName, RequestHeaders).ProtectableItem; } HyperVReplicaAzureEnableProtectionInput hvrAEnableDRInput = new HyperVReplicaAzureEnableProtectionInput() { HvHostVmId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).SourceItemId, OSType = "Windows", VhdId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).DiskDetailsList[0].VhdId, VmName = protectableItem.Properties.FriendlyName, TargetStorageAccountId = "/subscriptions/19b823e2-d1f3-4805-93d7-401c5d8230d5/resourceGroups/Default-Storage-WestUS/providers/Microsoft.ClassicStorage/storageAccounts/bvtmapped2storacc", }; EnableProtectionInputProperties enableDRProp = new EnableProtectionInputProperties() { PolicyId = selectedPolicy.Id, ProtectableItemId = protectableItem.Id, ProviderSpecificDetails = hvrAEnableDRInput }; EnableProtectionInput enableDRInput = new EnableProtectionInput() { Properties = enableDRProp }; DateTime enablStartTime = DateTime.UtcNow; protectedItem = ( client.ReplicationProtectedItem.EnableProtection( selectedFabric.Name, primaryCloud.Name, protectedItemName, enableDRInput, RequestHeaders) as ReplicationProtectedItemOperationResponse).ReplicationProtectedItem; MonitoringHelper.MonitorJobs(MonitoringHelper.AzureIrJobName, enablStartTime, client, RequestHeaders); } if (pfo || commit || tfo || pfoReverse || commitReverse || reprotect || disableDR) { protectableItem = client.ProtectableItem.Get(selectedFabric.Name, primaryCloud.Name, enableDRName, RequestHeaders).ProtectableItem; protectedItem = client.ReplicationProtectedItem.Get(selectedFabric.Name, primaryCloud.Name, protectedItemName, RequestHeaders).ReplicationProtectedItem; // Create Input for Operations ///////////////////////////// PFO ///////////////////////////////////// HyperVReplicaAzureFailoverProviderInput hvrAFOInput = new HyperVReplicaAzureFailoverProviderInput() { VaultLocation = "West US", }; PlannedFailoverInputProperties plannedFailoverProp = new PlannedFailoverInputProperties() { FailoverDirection = "", ProviderSpecificDetails = hvrAFOInput }; PlannedFailoverInput plannedFailoverInput = new PlannedFailoverInput() { Properties = plannedFailoverProp }; HyperVReplicaAzureFailbackProviderInput hvrAFBInput = new HyperVReplicaAzureFailbackProviderInput() { RecoveryVmCreationOption = "NoAction", DataSyncOption = "ForSyncronization" }; PlannedFailoverInputProperties plannedFailbackProp = new PlannedFailoverInputProperties() { FailoverDirection = "", ProviderSpecificDetails = hvrAFBInput }; PlannedFailoverInput plannedFailbackInput = new PlannedFailoverInput() { Properties = plannedFailbackProp }; ////////////////////////////// Reprotect ////////////////////////////////////// HyperVReplicaAzureReprotectInput hvrARRInput = new HyperVReplicaAzureReprotectInput() { HvHostVmId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).SourceItemId, OSType = "Windows", VHDId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).DiskDetailsList[0].VhdId, VmName = protectableItem.Properties.FriendlyName, StorageAccountId = "/subscriptions/19b823e2-d1f3-4805-93d7-401c5d8230d5/resourceGroups/Default-Storage-WestUS/providers/Microsoft.ClassicStorage/storageAccounts/bvtmapped2storacc", }; ReverseReplicationInputProperties rrProp = new ReverseReplicationInputProperties() { FailoverDirection = "", ProviderSpecificDetails = hvrARRInput }; ReverseReplicationInput rrInput = new ReverseReplicationInput() { Properties = rrProp }; ////////////////////////////////// UFO ///////////////////////////////////////// UnplannedFailoverInputProperties ufoProp = new UnplannedFailoverInputProperties() { ProviderSpecificDetails = hvrAFOInput, SourceSiteOperations = "NotRequired" }; UnplannedFailoverInput ufoInput = new UnplannedFailoverInput() { Properties = ufoProp }; /////////////////////////////////// TFO ///////////////////////////////////////////// TestFailoverInputProperties tfoProp = new TestFailoverInputProperties() { ProviderSpecificDetails = hvrAFOInput }; TestFailoverInput tfoInput = new TestFailoverInput() { Properties = tfoProp }; ////////////////////////////////////////////////////////////////////////////////////////// if (pfo) { var plannedfailover = client.ReplicationProtectedItem.PlannedFailover(selectedFabric.Name, primaryCloud.Name, protectedItem.Name, plannedFailoverInput, RequestHeaders); } if (commit) { var commitFailover = client.ReplicationProtectedItem.CommitFailover(selectedFabric.Name, primaryCloud.Name, protectedItem.Name, RequestHeaders); } if (pfoReverse) { //var unplannedFailoverReverse = client.ReplicationProtectedItem.UnplannedFailover(selectedFabric.Name, priCld, replicationProtectedItems.ReplicationProtectedItems[0].Name, ufoInput, RequestHeaders); var plannedFailoverReverse = client.ReplicationProtectedItem.PlannedFailover(selectedFabric.Name, primaryCloud.Name, protectedItem.Name, plannedFailbackInput, RequestHeaders); } if (commitReverse) { var commitFailoverReverse = client.ReplicationProtectedItem.CommitFailover(selectedFabric.Name, primaryCloud.Name, protectedItem.Name, RequestHeaders); } if (reprotect) { var reprotectStartTime = DateTime.UtcNow; var rrReverseOp = client.ReplicationProtectedItem.Reprotect(selectedFabric.Name, primaryCloud.Name, protectedItem.Name, rrInput, RequestHeaders); MonitoringHelper.MonitorJobs(MonitoringHelper.AzureIrJobName, reprotectStartTime, client, RequestHeaders); } if (tfo) { DateTime startTFO = DateTime.UtcNow; var tfoOp = client.ReplicationProtectedItem.TestFailover(selectedFabric.Name, primaryCloud.Name, protectedItem.Name, tfoInput, RequestHeaders); var jobs = MonitoringHelper.GetJobId(MonitoringHelper.TestFailoverJobName, startTFO, client, RequestHeaders); ResumeJobParamsProperties resProp = new ResumeJobParamsProperties() { Comments = "Res TFO" }; ResumeJobParams resParam = new ResumeJobParams() { Properties = resProp }; var resJob = client.Jobs.Resume(jobs.Name, resParam, RequestHeaders); } if (disableDR) { var disableDROperation = client.ReplicationProtectedItem.DisableProtection(selectedFabric.Name, primaryCloud.Name, protectedItem.Name, new DisableProtectionInput(), RequestHeaders); } if (unpair) { var unpairClouds = client.ProtectionContainerMapping.UnconfigureProtection( selectedFabric.Name, primaryCloud.Name, mappingName, new RemoveProtectionContainerMappingInput(), RequestHeaders); } } if (removePolicy) { var policyDeletion = client.Policies.Delete(selectedPolicy.Name, RequestHeaders); } } }
/// <summary> /// Enable Protection for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='input'> /// Optional. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse EnableProtection(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, EnableProtectionInput input, CustomRequestHeaders customRequestHeaders) { return(Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).EnableProtectionAsync(protectionContainerId, protectionEntityId, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult()); }
/// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteCmdlet() { this.targetNameOrId = this.ProtectionEntity.FriendlyName; this.ConfirmAction( this.Force.IsPresent || 0 != string.CompareOrdinal(this.Protection, Constants.DisableProtection), string.Format(Properties.Resources.DisableProtectionWarning, this.targetNameOrId), string.Format(Properties.Resources.DisableProtectionWhatIfMessage, this.Protection), this.targetNameOrId, () => { try { if (this.Protection == Constants.EnableProtection) { EnableProtectionInput input = new EnableProtectionInput(); // Considering no PP input for E2E, if needed, change below logic // for E2E, consider the profile created PS & a profile created in service if (this.ProtectionProfile != null && 0 == string.Compare( this.ProtectionProfile.ReplicationProvider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase)) { input.ProtectionProfileId = this.ProtectionProfile.Name; AzureEnableProtectionInput providerSettings = new AzureEnableProtectionInput(); providerSettings.HvHostVmId = this.ProtectionEntity.FabricObjectId; providerSettings.VmName = this.ProtectionEntity.FriendlyName; // Id disk details are missing in input PE object, get the latest PE. // As get PE by name is failing before protection, get all & filter. // Once after we fix get pe by name, change the logic to use the same. if (string.IsNullOrEmpty(this.ProtectionEntity.OS)) { // Just checked for OS to see whether the disk details got filled up or not ProtectionEntityListResponse protectionEntityListResponse = RecoveryServicesClient.GetAzureSiteRecoveryProtectionEntity( this.ProtectionEntity.ProtectionContainerId); foreach (ProtectionEntity pe in protectionEntityListResponse.ProtectionEntities) { if (0 == string.Compare(this.ProtectionEntity.FriendlyName, pe.Properties.FriendlyName, true)) { this.ProtectionEntity = new ASRProtectionEntity(pe); break; } } } providerSettings.OSType = this.ProtectionEntity.OS; if (string.IsNullOrWhiteSpace(this.OSDiskName)) { providerSettings.VHDId = this.ProtectionEntity.OSDiskId; } else { foreach (var disk in this.ProtectionEntity.Disks) { if (0 == string.Compare(disk.Name, this.OSDiskName, true)) { providerSettings.VHDId = disk.Id; break; } } } input.ProviderSettings = providerSettings; } this.response = RecoveryServicesClient.EnableProtection( this.ProtectionEntity.ProtectionContainerId, this.ProtectionEntity.Name, input); } else { DisableProtectionInput input = new DisableProtectionInput(); this.response = RecoveryServicesClient.DisableProtection( this.ProtectionEntity.ProtectionContainerId, this.ProtectionEntity.Name, input); } jobResponse = RecoveryServicesClient .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); WriteObject(new ASRJob(jobResponse.Job)); if (this.WaitForCompletion.IsPresent) { this.WaitForJobCompletion(this.jobResponse.Job.Name); } } catch (Exception exception) { this.HandleException(exception); } }); }
/// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteCmdlet() { switch (this.ParameterSetName) { case ASRParameterSets.ByPEObject: this.Id = this.ProtectionEntity.ID; this.ProtectionContainerId = this.ProtectionEntity.ProtectionContainerId; this.targetNameOrId = this.ProtectionEntity.Name; this.alreadyEnabled = this.ProtectionEntity.Protected; break; case ASRParameterSets.ByIDs: this.targetNameOrId = this.Id; ProtectionEntityResponse protectionEntityResponse = RecoveryServicesClient.GetAzureSiteRecoveryProtectionEntity( this.ProtectionContainerId, this.Id); this.alreadyEnabled = protectionEntityResponse.ProtectionEntity.Protected; this.targetNameOrId = protectionEntityResponse.ProtectionEntity.Name; break; } if (this.alreadyEnabled && this.Protection.Equals(Constants.EnableProtection, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException( string.Format( Properties.Resources.ProtectionEntityAlreadyEnabled, this.targetNameOrId)); } else if (!this.alreadyEnabled && this.Protection.Equals(Constants.DisableProtection, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException( Properties.Resources.ProtectionEntityAlreadyDisabled, this.targetNameOrId); } this.ConfirmAction( this.Force.IsPresent || 0 != string.CompareOrdinal(this.Protection, Constants.DisableProtection), string.Format(Properties.Resources.DisableProtectionWarning, this.targetNameOrId), string.Format(Properties.Resources.DisableProtectionWhatIfMessage, this.Protection), this.targetNameOrId, () => { try { if (this.Protection == Constants.EnableProtection) { string profileId = string.Empty; var input = new EnableProtectionInput(); if (this.ProtectionEntity == null) { var pe = RecoveryServicesClient.GetAzureSiteRecoveryProtectionEntity( this.ProtectionContainerId, this.Id); this.ProtectionEntity = new ASRProtectionEntity(pe.ProtectionEntity); } // Get the replciation provider from profile object otherwise assume its E2E. // Let the call go without profileId set. string replicationProvider = null; if (this.ProtectionProfile != null) { profileId = this.ProtectionProfile.ID; replicationProvider = this.ProtectionProfile.ReplicationProvider; } else { string pcId = this.ProtectionContainerId ?? this.ProtectionEntity.ProtectionContainerId; var pc = RecoveryServicesClient.GetAzureSiteRecoveryProtectionContainer( pcId); // PC will have all profiles associated with same replciation providers only. replicationProvider = pc.ProtectionContainer.AvailableProtectionProfiles.Count < 1 ? null : pc.ProtectionContainer.AvailableProtectionProfiles[0].ReplicationProvider; if (replicationProvider != Constants.HyperVReplica) { throw new Exception("Please provide the protection profile object. It can be chosen from available protection profiles of the protection container."); } } if (this.ParameterSetName == ASRParameterSets.ByIDs) { this.ValidateUsageById(replicationProvider, "Id"); } if (replicationProvider == Constants.HyperVReplicaAzure) { input.ProtectionProfileId = this.ProtectionProfile.ID; AzureEnableProtectionInput azureInput = new AzureEnableProtectionInput(); azureInput.HvHostVmId = this.ProtectionEntity.FabricObjectId; azureInput.VmName = this.ProtectionEntity.Name; azureInput.OSType = this.OS; if (string.IsNullOrWhiteSpace(this.OS)) { azureInput.OSType = this.ProtectionEntity.OS; } if (string.IsNullOrWhiteSpace(this.OSDiskName)) { azureInput.VHDId = this.ProtectionEntity.OSDiskId; } else { foreach (var disk in this.ProtectionEntity.Disks) { if (disk.Name == this.OSDiskName) { azureInput.VHDId = disk.Id; break; } } } input.ReplicationProviderInput = DataContractUtils.Serialize <AzureEnableProtectionInput>(azureInput); } else if (string.IsNullOrWhiteSpace(profileId)) { input = null; } else { input.ReplicationProviderInput = string.Empty; input.ProtectionProfileId = profileId; } this.jobResponse = RecoveryServicesClient.EnableProtection( this.ProtectionContainerId, this.Id, input); } else { this.jobResponse = RecoveryServicesClient.DisbleProtection( this.ProtectionContainerId, this.Id); } this.WriteJob(this.jobResponse.Job); if (this.WaitForCompletion.IsPresent) { this.WaitForJobCompletion(this.jobResponse.Job.ID); } } catch (Exception exception) { this.HandleException(exception); } }); }
public void EnableProtectionTest() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetSiteRecoveryClient(CustomHttpHandler); var requestHeaders = RequestHeaders; requestHeaders.AgentAuthenticationHeader = GenerateAgentAuthenticationHeader(requestHeaders.ClientRequestId); var responsePC = client.ProtectionContainer.List(RequestHeaders); JobResponse response = new JobResponse(); bool desiredPEFound = false; foreach (var pc in responsePC.ProtectionContainers) { if (pc.Role == "Primary") { var responsePEs = client.ProtectionEntity.List(pc.ID, RequestHeaders); response = null; foreach (var pe in responsePEs.ProtectionEntities) { if (pe.Protected == false) { AzureVmDiskDetails diskDetails; DataContractUtils.Deserialize <AzureVmDiskDetails>( pe.ReplicationProviderSettings, out diskDetails); EnableProtectionInput input = new EnableProtectionInput(); int index = 0; input.ProtectionProfileId = pc.AvailableProtectionProfiles[index].ID; AzureEnableProtectionInput azureInput = new AzureEnableProtectionInput(); azureInput.HvHostVmId = pe.FabricObjectId; azureInput.VmName = pe.Name; azureInput.VHDId = diskDetails.VHDId; azureInput.OSType = diskDetails.OsType; if (string.IsNullOrWhiteSpace(azureInput.OSType)) { azureInput.OSType = "Windows"; } input.ReplicationProviderInput = DataContractUtils.Serialize <AzureEnableProtectionInput>(azureInput); response = client.ProtectionEntity.EnableProtection( pe.ProtectionContainerId, pe.ID, input, requestHeaders); desiredPEFound = true; break; } } if (desiredPEFound) { break; } } } Assert.NotNull(response.Job); Assert.NotNull(response.Job.ID); Assert.True(response.Job.Errors.Count < 1, "Errors found while doing Enable protection operation"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } }
/// <summary> /// Helper method for E2A and H2A scenario. /// </summary> private void EnterpriseAndHyperVToAzure(EnableProtectionInput input) { var providerSettings = new HyperVReplicaAzureEnableProtectionInput(); providerSettings.HvHostVmId = this.ProtectableItem.FabricObjectId; providerSettings.VmName = this.ProtectableItem.FriendlyName; providerSettings.TargetAzureVmName = string.IsNullOrEmpty(this.RecoveryVmName) ? this.ProtectableItem.FriendlyName : this.RecoveryVmName; if (!string.IsNullOrEmpty(this.RecoveryAzureNetworkId)) { providerSettings.TargetAzureNetworkId = this.RecoveryAzureNetworkId; } if (!string.IsNullOrEmpty(this.RecoveryAzureSubnetName)) { providerSettings.TargetAzureSubnetId = this.RecoveryAzureSubnetName; } if (!string.IsNullOrEmpty(this.LogStorageAccountId)) { providerSettings.LogStorageAccountId = this.LogStorageAccountId; } // Id disk details are missing in input PE object, get the latest PE. if (string.IsNullOrEmpty(this.ProtectableItem.OS)) { // Just checked for OS to see whether the disk details got filled up or not var protectableItemResponse = this.RecoveryServicesClient .GetAzureSiteRecoveryProtectableItem( Utilities.GetValueFromArmId( this.ProtectableItem.ID, ARMResourceTypeConstants.ReplicationFabrics), this.ProtectableItem.ProtectionContainerId, this.ProtectableItem.Name); this.ProtectableItem = new ASRProtectableItem(protectableItemResponse); } if (string.IsNullOrWhiteSpace(this.OS)) { providerSettings.OsType = (string.Compare( this.ProtectableItem.OS, Constants.OSWindows, StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare( this.ProtectableItem.OS, Constants.OSLinux) == 0) ? this.ProtectableItem.OS : Constants.OSWindows; } else { providerSettings.OsType = this.OS; } if (string.IsNullOrWhiteSpace(this.OSDiskName)) { providerSettings.VhdId = this.ProtectableItem.OSDiskId; } else { foreach (var disk in this.ProtectableItem.Disks) { if (0 == string.Compare(disk.Name, this.OSDiskName, true)) { providerSettings.VhdId = disk.Id; break; } } } if (this.RecoveryAzureStorageAccountId != null) { providerSettings.TargetStorageAccountId = this.RecoveryAzureStorageAccountId; } var deploymentType = Utilities.GetValueFromArmId( this.RecoveryAzureStorageAccountId, ARMResourceTypeConstants.Providers); if (deploymentType.ToLower() .Contains(Constants.Classic.ToLower())) { providerSettings.TargetAzureV1ResourceGroupId = this.RecoveryResourceGroupId; providerSettings.TargetAzureV2ResourceGroupId = null; } else { providerSettings.TargetAzureV1ResourceGroupId = null; providerSettings.TargetAzureV2ResourceGroupId = this.RecoveryResourceGroupId; } input.Properties.ProviderSpecificDetails = providerSettings; }
/// <summary> /// Helper method for Azure to Azure replication scenario. /// </summary> private void AzureToAzureReplication(EnableProtectionInput input) { var providerSettings = new A2AEnableProtectionInput() { FabricObjectId = this.AzureVmId, RecoveryContainerId = this.ProtectionContainerMapping.TargetProtectionContainerId, VmDisks = new List <A2AVmDiskInputDetails>(), VmManagedDisks = new List <A2AVmManagedDiskInputDetails>(), RecoveryResourceGroupId = this.RecoveryResourceGroupId, RecoveryCloudServiceId = this.RecoveryCloudServiceId, RecoveryAvailabilitySetId = this.RecoveryAvailabilitySetId, RecoveryBootDiagStorageAccountId = this.RecoveryBootDiagStorageAccountId, RecoveryAzureNetworkId = this.RecoveryAzureNetworkId, RecoverySubnetName = this.RecoveryAzureSubnetName, RecoveryAvailabilityZone = this.RecoveryAvailabilityZone }; if (!string.IsNullOrEmpty(this.ReplicationGroupName)) { providerSettings.MultiVmGroupName = this.ReplicationGroupName; } if (!string.IsNullOrEmpty(this.RecoveryCloudServiceId)) { providerSettings.RecoveryResourceGroupId = null; } if (this.AzureToAzureDiskReplicationConfiguration == null) { if (this.AzureVmId.ToLower().Contains(ARMResourceTypeConstants.Compute.ToLower())) { var vmName = Utilities.GetValueFromArmId(this.AzureVmId, ARMResourceTypeConstants.VirtualMachine); var vmRg = Utilities.GetValueFromArmId(this.AzureVmId, ARMResourceTypeConstants.ResourceGroups); var subscriptionId = Utilities.GetValueFromArmId(this.AzureVmId, ARMResourceTypeConstants.Subscriptions); var tempSubscriptionId = this.ComputeManagementClient.GetComputeManagementClient.SubscriptionId; this.ComputeManagementClient.GetComputeManagementClient.SubscriptionId = subscriptionId; var virtualMachine = this.ComputeManagementClient.GetComputeManagementClient. VirtualMachines.GetWithHttpMessagesAsync(vmRg, vmName).GetAwaiter().GetResult().Body; this.ComputeManagementClient.GetComputeManagementClient.SubscriptionId = tempSubscriptionId; if (virtualMachine == null) { throw new Exception("Azure Vm not found"); } // if managed disk if (virtualMachine.StorageProfile.OsDisk.ManagedDisk != null) { if (this.RecoveryAzureStorageAccountId != null) { throw new Exception("Recovery Storage account is not required for managed disk vm to protect"); } var osDisk = virtualMachine.StorageProfile.OsDisk; providerSettings.VmManagedDisks.Add(new A2AVmManagedDiskInputDetails { DiskId = osDisk.ManagedDisk.Id, RecoveryResourceGroupId = this.RecoveryResourceGroupId, PrimaryStagingAzureStorageAccountId = this.LogStorageAccountId, RecoveryReplicaDiskAccountType = osDisk.ManagedDisk.StorageAccountType, RecoveryTargetDiskAccountType = osDisk.ManagedDisk.StorageAccountType }); if (virtualMachine.StorageProfile.DataDisks != null) { foreach (var dataDisk in virtualMachine.StorageProfile.DataDisks) { providerSettings.VmManagedDisks.Add(new A2AVmManagedDiskInputDetails { DiskId = dataDisk.ManagedDisk.Id, RecoveryResourceGroupId = this.RecoveryResourceGroupId, PrimaryStagingAzureStorageAccountId = LogStorageAccountId, RecoveryReplicaDiskAccountType = dataDisk.ManagedDisk.StorageAccountType, RecoveryTargetDiskAccountType = dataDisk.ManagedDisk.StorageAccountType }); } } } else { if (this.RecoveryAzureStorageAccountId == null) { throw new Exception("Recovery Storage account is required for non-managed disk vm to protect"); } var osDisk = virtualMachine.StorageProfile.OsDisk; providerSettings.VmDisks.Add(new A2AVmDiskInputDetails { DiskUri = osDisk.Vhd.Uri, RecoveryAzureStorageAccountId = this.RecoveryAzureStorageAccountId, PrimaryStagingAzureStorageAccountId = LogStorageAccountId }); if (virtualMachine.StorageProfile.DataDisks != null) { foreach (var dataDisk in virtualMachine.StorageProfile.DataDisks) { providerSettings.VmDisks.Add(new A2AVmDiskInputDetails { DiskUri = dataDisk.Vhd.Uri, RecoveryAzureStorageAccountId = this.RecoveryAzureStorageAccountId, PrimaryStagingAzureStorageAccountId = LogStorageAccountId }); } } } } else { throw new Exception("Pass Disk details for Classic VMs"); } } else { foreach (ASRAzuretoAzureDiskReplicationConfig disk in this.AzureToAzureDiskReplicationConfiguration) { if (disk.IsManagedDisk) { providerSettings.VmManagedDisks.Add(new A2AVmManagedDiskInputDetails { DiskId = disk.DiskId, RecoveryResourceGroupId = disk.RecoveryResourceGroupId, PrimaryStagingAzureStorageAccountId = disk.LogStorageAccountId, RecoveryReplicaDiskAccountType = disk.RecoveryReplicaDiskAccountType, RecoveryTargetDiskAccountType = disk.RecoveryTargetDiskAccountType, DiskEncryptionInfo = Utilities.A2AEncryptionDetails( disk.DiskEncryptionSecretUrl, disk.DiskEncryptionVaultId, disk.KeyEncryptionKeyUrl, disk.KeyEncryptionVaultId) }); } else { providerSettings.VmDisks.Add(new A2AVmDiskInputDetails { DiskUri = disk.VhdUri, RecoveryAzureStorageAccountId = disk.RecoveryAzureStorageAccountId, PrimaryStagingAzureStorageAccountId = disk.LogStorageAccountId, }); } } } providerSettings.DiskEncryptionInfo = Utilities.A2AEncryptionDetails( this.DiskEncryptionSecretUrl, this.DiskEncryptionVaultId, this.KeyEncryptionKeyUrl, this.KeyEncryptionVaultId); input.Properties.ProviderSpecificDetails = providerSettings; }
public static ReplicationProtectedItemOperationResponse EnableDR( this SiteRecoveryManagementClient client, Fabric primaryFabric, ProtectionContainer protectionContainer, Policy policy, ProtectableItem protectableItem, string armResourceName) { if (policy.Properties.ProviderSpecificDetails.InstanceType == "HyperVReplicaAzure") { string vhdId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails) .DiskDetailsList[0].VhdId; DiskDetails osDisk = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).DiskDetailsList .FirstOrDefault(item => item.VhdType == "OperatingSystem"); if (osDisk != null) { vhdId = osDisk.VhdId; } HyperVReplicaAzureEnableProtectionInput hvrAEnableDRInput = new HyperVReplicaAzureEnableProtectionInput() { HvHostVmId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).SourceItemId, OSType = "Windows", VhdId = vhdId, VmName = protectableItem.Properties.FriendlyName, TargetStorageAccountId = (policy.Properties.ProviderSpecificDetails as HyperVReplicaAzurePolicyDetails) .ActiveStorageAccountId, }; EnableProtectionInputProperties enableDRProp = new EnableProtectionInputProperties() { PolicyId = policy.Id, ProtectableItemId = protectableItem.Id, ProviderSpecificDetails = hvrAEnableDRInput }; EnableProtectionInput enableDRInput = new EnableProtectionInput() { Properties = enableDRProp }; return(client.ReplicationProtectedItem.EnableProtection( primaryFabric.Name, protectionContainer.Name, armResourceName, enableDRInput, GetRequestHeaders()) as ReplicationProtectedItemOperationResponse); } else if (policy.Properties.ProviderSpecificDetails.InstanceType == "HyperVReplica2012" || policy.Properties.ProviderSpecificDetails.InstanceType == "HyperVReplica2012R2") { var enableDRProp = new EnableProtectionInputProperties() { PolicyId = policy.Id, ProtectableItemId = protectableItem.Id, ProviderSpecificDetails = new EnableProtectionProviderSpecificInput() }; EnableProtectionInput enableInput = new EnableProtectionInput() { Properties = enableDRProp }; return(client.ReplicationProtectedItem.EnableProtection( primaryFabric.Name, protectionContainer.Name, armResourceName, enableInput, GetRequestHeaders()) as ReplicationProtectedItemOperationResponse); } else { throw new NotImplementedException(); } }
/// <summary> /// Enable Protection for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='input'> /// Optional. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task <JobResponse> EnableProtectionAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, EnableProtectionInput input, CustomRequestHeaders customRequestHeaders) { return(operations.EnableProtectionAsync(protectionContainerId, protectionEntityId, input, customRequestHeaders, CancellationToken.None)); }
public void EndToEndE2ESingleVM() { using (UndoContext context = UndoContext.Current) { context.Start(); var client = GetSiteRecoveryClient(CustomHttpHandler); bool pairClouds = true; bool enableDR = true; bool pfo = true; bool commit = true; bool tfo = true; bool pfoReverse = true; bool commitReverse = true; bool rr = true; bool rrReverse = true; bool disableDR = true; bool unpair = true; bool removePolicy = true; var fabrics = client.Fabrics.List(RequestHeaders); Fabric selectedFabric = null; foreach (var fabric in fabrics.Fabrics) { if (fabric.Properties.CustomDetails.InstanceType.Contains("VMM")) { selectedFabric = fabric; } } string priCld = string.Empty; string recCldGuid = string.Empty; string recCld = string.Empty; string policyName = "Hydra-EndToEndE2ESingleVM-" + (new Random()).Next(); string mappingName = "Mapping-EndToEndE2ESingleVM-" + (new Random()).Next(); string replicationProtectedItemName = "PE" + (new Random()).Next(); string enableDRVmName = string.Empty; Policy currentPolicy = null; var policies = client.Policies.List(RequestHeaders); if (string.IsNullOrEmpty(recCldGuid)) { var containers = client.ProtectionContainer.List(selectedFabric.Name, RequestHeaders); foreach (var container in containers.ProtectionContainers) { if (container.Properties.PairingStatus.Equals("NotPaired", StringComparison.InvariantCultureIgnoreCase)) { if (string.IsNullOrEmpty(priCld)) { priCld = container.Name; } else if (string.IsNullOrEmpty(recCld) && priCld != container.Name) { recCld = container.Id; recCldGuid = container.Name; } } } } else { recCld = client.ProtectionContainer.Get(selectedFabric.Name, recCldGuid, RequestHeaders).ProtectionContainer.Id; } if (pairClouds) { HyperVReplica2012R2PolicyInput hvrProfileInput = new HyperVReplica2012R2PolicyInput() { ApplicationConsistentSnapshotFrequencyInHours = 0, AllowedAuthenticationType = 1, Compression = "Enable", InitialReplicationMethod = "OverNetwork", OnlineReplicationStartTime = null, RecoveryPoints = 0, ReplicaDeletion = "Required", ReplicationPort = 8083, ReplicationFrequencyInSeconds = 300 }; CreatePolicyInputProperties policyCreationProp = new CreatePolicyInputProperties() { ProviderSpecificInput = hvrProfileInput }; CreatePolicyInput policyCreationInput = new CreatePolicyInput() { Properties = policyCreationProp }; var policyCreateResp = client.Policies.Create(policyName, policyCreationInput, RequestHeaders); currentPolicy = client.Policies.Get(policyName, RequestHeaders).Policy; CreateProtectionContainerMappingInputProperties pairingProps = new CreateProtectionContainerMappingInputProperties() { PolicyId = currentPolicy.Id, TargetProtectionContainerId = recCld, ProviderSpecificInput = new ReplicationProviderContainerMappingInput() }; CreateProtectionContainerMappingInput pairingInput = new CreateProtectionContainerMappingInput() { Properties = pairingProps }; var pairingResponse = client.ProtectionContainerMapping.ConfigureProtection( selectedFabric.Name, priCld, mappingName, pairingInput, RequestHeaders); // Adding SP1 Profile too HyperVReplica2012PolicyInput hvrsp1ProfileInput = new HyperVReplica2012PolicyInput() { ApplicationConsistentSnapshotFrequencyInHours = 0, AllowedAuthenticationType = 1, Compression = "Enable", InitialReplicationMethod = "OverNetwork", OnlineReplicationStartTime = null, RecoveryPoints = 0, ReplicaDeletion = "Required", ReplicationPort = 8083 }; CreatePolicyInputProperties policySp1CreationProp = new CreatePolicyInputProperties() { ProviderSpecificInput = hvrsp1ProfileInput }; CreatePolicyInput policySp1CreationInput = new CreatePolicyInput() { Properties = policySp1CreationProp }; var policySp1CreateResp = client.Policies.Create(policyName + "SP1", policySp1CreationInput, RequestHeaders); var currentSp1Policy = client.Policies.Get(policyName + "SP1", RequestHeaders).Policy; CreateProtectionContainerMappingInputProperties pairingSp1Props = new CreateProtectionContainerMappingInputProperties() { PolicyId = currentSp1Policy.Id, TargetProtectionContainerId = recCld, ProviderSpecificInput = new ReplicationProviderContainerMappingInput() }; CreateProtectionContainerMappingInput pairingSp1Input = new CreateProtectionContainerMappingInput() { Properties = pairingSp1Props }; var pairingSp1Response = client.ProtectionContainerMapping.ConfigureProtection( selectedFabric.Name, priCld, mappingName + "sp1", pairingSp1Input, RequestHeaders); } else { currentPolicy = client.Policies.Get(policyName, RequestHeaders).Policy; } if (enableDR) { EnableProtectionInputProperties enableDRProp = new EnableProtectionInputProperties(); if (string.IsNullOrEmpty(enableDRVmName)) { var protectableItems = client.ProtectableItem.List(selectedFabric.Name, priCld, "Unprotected", RequestHeaders); enableDRProp = new EnableProtectionInputProperties() { PolicyId = currentPolicy.Id, ProtectableItemId = protectableItems.ProtectableItems[0].Id, ProviderSpecificDetails = new EnableProtectionProviderSpecificInput() }; } else { var item = client.ProtectableItem.Get(selectedFabric.Name, priCld, enableDRVmName, RequestHeaders); enableDRProp = new EnableProtectionInputProperties() { PolicyId = currentPolicy.Id, ProtectableItemId = item.ProtectableItem.Id, ProviderSpecificDetails = new EnableProtectionProviderSpecificInput() }; } EnableProtectionInput enableInput = new EnableProtectionInput() { Properties = enableDRProp }; var enableDRStartTime = DateTime.Now; var enableDRresp = client.ReplicationProtectedItem.EnableProtection( selectedFabric.Name, priCld, replicationProtectedItemName, enableInput, RequestHeaders); MonitoringHelper.MonitorJobs(MonitoringHelper.SecondaryIrJobName, enableDRStartTime, client, RequestHeaders); } ///////////////////////////// PFO //////////////////////////////// PlannedFailoverInputProperties plannedFailoverProp = new PlannedFailoverInputProperties() { ProviderSpecificDetails = new ProviderSpecificFailoverInput() }; PlannedFailoverInput plannedFailoverInput = new PlannedFailoverInput() { Properties = plannedFailoverProp }; ////////////////////////////// RR //////////////////////////////// ReverseReplicationInputProperties rrProp = new ReverseReplicationInputProperties() { ProviderSpecificDetails = new ReverseReplicationProviderSpecificInput() }; ReverseReplicationInput rrInput = new ReverseReplicationInput() { Properties = rrProp }; ////////////////////////////////// UFO ///////////////////////////// UnplannedFailoverInputProperties ufoProp = new UnplannedFailoverInputProperties() { ProviderSpecificDetails = new ProviderSpecificFailoverInput(), SourceSiteOperations = "NotRequired" }; UnplannedFailoverInput ufoInput = new UnplannedFailoverInput() { Properties = ufoProp }; /////////////////////////////////// TFO ////////////////////////////// TestFailoverInputProperties tfoProp = new TestFailoverInputProperties() { ProviderSpecificDetails = new ProviderSpecificFailoverInput() }; TestFailoverInput tfoInput = new TestFailoverInput() { Properties = tfoProp }; ///////////////////////////////////// if (pfo) { var protectedItem = client.ReplicationProtectedItem.Get( selectedFabric.Name, priCld, replicationProtectedItemName, RequestHeaders); var plannedfailover = client.ReplicationProtectedItem.PlannedFailover(selectedFabric.Name, priCld, replicationProtectedItemName, plannedFailoverInput, RequestHeaders); //var unplannedFailoverReverse = client.ReplicationProtectedItem.UnplannedFailover( // selectedFabric.Name, // priCld, // replicationProtectedItemName, // ufoInput, // RequestHeaders); } if (commit) { var commitFailover = client.ReplicationProtectedItem.CommitFailover(selectedFabric.Name, priCld, replicationProtectedItemName, RequestHeaders); } if (rr) { var rrOp = client.ReplicationProtectedItem.Reprotect(selectedFabric.Name, priCld, replicationProtectedItemName, rrInput, RequestHeaders); } if (pfoReverse) { //var unplannedFailoverReverse = client.ReplicationProtectedItem.UnplannedFailover( // selectedFabric.Name, priCld, replicationProtectedItemName, ufoInput, RequestHeaders); var plannedFailoverReverse = client.ReplicationProtectedItem.PlannedFailover(selectedFabric.Name, priCld, replicationProtectedItemName, plannedFailoverInput, RequestHeaders); } if (commitReverse) { var commitFailoverReverse = client.ReplicationProtectedItem.CommitFailover(selectedFabric.Name, priCld, replicationProtectedItemName, RequestHeaders); } if (rrReverse) { DateTime rrPostUfoStartTime = DateTime.UtcNow; var rrReverseOp = client.ReplicationProtectedItem.Reprotect(selectedFabric.Name, priCld, replicationProtectedItemName, rrInput, RequestHeaders); /*while (true) * { * Thread.Sleep(5000 * 60); * Job ufoJob = MonitoringHelper.GetJobId( * MonitoringHelper.ReverseReplicationJobName, * rrPostUfoStartTime, * client, * RequestHeaders); * * if (ufoJob.Properties.StateDescription.Equals( * "WaitingForFinalizeProtection", * StringComparison.InvariantCultureIgnoreCase)) * { * break; * } * } * * MonitoringHelper.MonitorJobs(MonitoringHelper.PrimaryIrJobName, rrPostUfoStartTime, client, RequestHeaders); * MonitoringHelper.MonitorJobs(MonitoringHelper.SecondaryIrJobName, rrPostUfoStartTime, client, RequestHeaders);*/ } if (tfo) { DateTime startTFO = DateTime.UtcNow; var tfoOp = client.ReplicationProtectedItem.TestFailover(selectedFabric.Name, priCld, replicationProtectedItemName, tfoInput, RequestHeaders); var jobs = MonitoringHelper.GetJobId(MonitoringHelper.TestFailoverJobName, startTFO, client, RequestHeaders); ResumeJobParamsProperties resProp = new ResumeJobParamsProperties() { Comments = "Res TFO" }; ResumeJobParams resParam = new ResumeJobParams() { Properties = resProp }; var resJob = client.Jobs.Resume(jobs.Name, resParam, RequestHeaders); } if (disableDR) { var disableDROperation = client.ReplicationProtectedItem.DisableProtection(selectedFabric.Name, priCld, replicationProtectedItemName, new DisableProtectionInput(), RequestHeaders); } if (unpair) { var unpaiClouds = client.ProtectionContainerMapping.UnconfigureProtection( selectedFabric.Name, priCld, mappingName, new RemoveProtectionContainerMappingInput(), RequestHeaders); } if (removePolicy) { var policyDeletion = client.Policies.Delete(currentPolicy.Name, RequestHeaders); } } }