private static void AdjustRetryAfter(LongRunningOperationResponse longrunningResponse, int longRunningOperationInitialTimeout)
 {
     if (longRunningOperationInitialTimeout >= 0)
     {
         longrunningResponse.RetryAfter = longRunningOperationInitialTimeout;
     }
 }
Exemple #2
0
        /// <summary>
        /// Starts PE Test failover.
        /// </summary>
        private void StartPETestFailover()
        {
            TestFailoverInputProperties testFailoverInputProperties = new TestFailoverInputProperties()
            {
                FailoverDirection       = this.Direction,
                NetworkId               = this.networkId,
                NetworkType             = this.networkType,
                ProviderSpecificDetails = new ProviderSpecificFailoverInput()
            };

            TestFailoverInput input = new TestFailoverInput()
            {
                Properties = testFailoverInputProperties
            };

            // fetch the latest PE object
            ProtectableItemResponse protectableItemResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryProtectableItem(this.fabricName,
                                                                           this.ProtectionEntity.ProtectionContainerId, this.ProtectionEntity.Name);

            ReplicationProtectedItemResponse replicationProtectedItemResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryReplicationProtectedItem(this.fabricName,
                                                                                    this.ProtectionEntity.ProtectionContainerId, Utilities.GetValueFromArmId(protectableItemResponse.ProtectableItem.Properties.ReplicationProtectedItemId, ARMResourceTypeConstants.ReplicationProtectedItems));

            PolicyResponse policyResponse = RecoveryServicesClient.GetAzureSiteRecoveryPolicy(Utilities.GetValueFromArmId(replicationProtectedItemResponse.ReplicationProtectedItem.Properties.PolicyID, ARMResourceTypeConstants.ReplicationPolicies));

            this.ProtectionEntity = new ASRProtectionEntity(protectableItemResponse.ProtectableItem, replicationProtectedItemResponse.ReplicationProtectedItem);

            if (0 == string.Compare(
                    this.ProtectionEntity.ReplicationProvider,
                    Constants.HyperVReplicaAzure,
                    StringComparison.OrdinalIgnoreCase))
            {
                if (this.Direction == Constants.PrimaryToRecovery)
                {
                    HyperVReplicaAzureFailoverProviderInput failoverInput = new HyperVReplicaAzureFailoverProviderInput()
                    {
                        PrimaryKekCertificatePfx   = null,
                        SecondaryKekCertificatePfx = null,
                        VaultLocation = this.GetCurrentValutLocation()
                    };
                    input.Properties.ProviderSpecificDetails = failoverInput;
                }
                else
                {
                    new ArgumentException(Properties.Resources.UnsupportedDirectionForTFO);// Throw Unsupported Direction Exception
                }
            }

            LongRunningOperationResponse response =
                RecoveryServicesClient.StartAzureSiteRecoveryTestFailover(
                    this.fabricName,
                    this.protectionContainerName,
                    Utilities.GetValueFromArmId(replicationProtectedItemResponse.ReplicationProtectedItem.Id, ARMResourceTypeConstants.ReplicationProtectedItems),
                    input);

            JobResponse jobResponse =
                RecoveryServicesClient
                .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location));

            WriteObject(new ASRJob(jobResponse.Job));
        }
Exemple #3
0
        /// <summary>
        /// The Get Operation Status operation returns the status of the
        /// specified operation. After calling an asynchronous operation, you
        /// can call Get Operation Status to determine whether the operation
        /// has succeeded, failed, or is still in progress.
        /// </summary>
        /// <param name='operationStatusLink'>
        /// Required. Location value returned by the Begin operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response for long running operations.
        /// </returns>
        public async Task <LongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
        {
            // Validate
            if (operationStatusLink == null)
            {
                throw new ArgumentNullException("operationStatusLink");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("operationStatusLink", operationStatusLink);
                Tracing.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters);
            }

            // Construct URL
            string url = operationStatusLink;

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

                // Set Headers
                httpRequest.Headers.Add("x-ms-version", "2014-12-01-preview");

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

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

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent && statusCode != HttpStatusCode.NotFound && statusCode != HttpStatusCode.Conflict && statusCode != HttpStatusCode.PreconditionFailed)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    LongRunningOperationResponse result = null;
                    result            = new LongRunningOperationResponse();
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }
                    if (statusCode == HttpStatusCode.PreconditionFailed)
                    {
                        result.Status = OperationStatus.Failed;
                    }
                    if (statusCode == HttpStatusCode.NotFound)
                    {
                        result.Status = OperationStatus.Failed;
                    }
                    if (statusCode == HttpStatusCode.Conflict)
                    {
                        result.Status = OperationStatus.Failed;
                    }
                    if (statusCode == HttpStatusCode.NoContent)
                    {
                        result.Status = OperationStatus.Succeeded;
                    }
                    if (statusCode == HttpStatusCode.OK)
                    {
                        result.Status = OperationStatus.Succeeded;
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// ProcessRecord of the command.
        /// </summary>
        public override void ExecuteSiteRecoveryCmdlet()
        {
            base.ExecuteSiteRecoveryCmdlet();

            ReplicationProtectedItemResponse replicationProtectedItemResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryReplicationProtectedItem(Utilities.GetValueFromArmId(this.ReplicationProtectedItem.ID, ARMResourceTypeConstants.ReplicationFabrics),
                                                                                    Utilities.GetValueFromArmId(this.ReplicationProtectedItem.ID, ARMResourceTypeConstants.ReplicationProtectionContainers),
                                                                                    ReplicationProtectedItem.Name);

            string provider =
                replicationProtectedItemResponse.ReplicationProtectedItem.Properties.ProviderSpecificDetails.InstanceType;

            // Check for Replication Provider type HyperVReplicaAzure/InMageAzureV2
            if (0 != string.Compare(provider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase) &&
                0 != string.Compare(provider, Constants.InMageAzureV2, StringComparison.OrdinalIgnoreCase))
            {
                this.WriteWarning(Properties.Resources.UnsupportedReplicationProvidedForUpdateVmProperties.ToString());
                return;
            }

            // Check for at least one option
            if (string.IsNullOrEmpty(this.Name) &&
                string.IsNullOrEmpty(this.Size) &&
                string.IsNullOrEmpty(this.PrimaryNic) &&
                string.IsNullOrEmpty(this.RecoveryNetworkId) &&
                string.IsNullOrEmpty(this.LicenseType))
            {
                this.WriteWarning(Properties.Resources.ArgumentsMissingForUpdateVmProperties.ToString());
                return;
            }

            // Both primary & recovery inputs should be present
            if (string.IsNullOrEmpty(this.PrimaryNic) ^
                string.IsNullOrEmpty(this.RecoveryNetworkId))
            {
                this.WriteWarning(Properties.Resources.NetworkArgumentsMissingForUpdateVmProperties.ToString());
                return;
            }

            string vmName = this.Name;
            string vmSize = this.Size;
            string vmRecoveryNetworkId = this.RecoveryNetworkId;
            string licenseType         = this.LicenseType;
            List <VMNicInputDetails> vMNicInputDetailsList = new List <VMNicInputDetails>();
            VMNicDetails             vMNicDetailsToBeUpdated;

            if (0 == string.Compare(provider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase))
            {
                HyperVReplicaAzureReplicationDetails providerSpecificDetails =
                    (HyperVReplicaAzureReplicationDetails)replicationProtectedItemResponse.ReplicationProtectedItem.Properties.ProviderSpecificDetails;

                if (string.IsNullOrEmpty(this.Name))
                {
                    vmName = providerSpecificDetails.RecoveryAzureVMName;
                }

                if (string.IsNullOrEmpty(this.Size))
                {
                    vmSize = providerSpecificDetails.RecoveryAzureVMSize;
                }

                if (string.IsNullOrEmpty(this.RecoveryNetworkId))
                {
                    vmRecoveryNetworkId = providerSpecificDetails.SelectedRecoveryAzureNetworkId;
                }

                if (string.IsNullOrEmpty(this.LicenseType))
                {
                    licenseType = providerSpecificDetails.LicenseType;
                }

                if (!string.IsNullOrEmpty(this.PrimaryNic))
                {
                    if (providerSpecificDetails.VMNics != null)
                    {
                        vMNicDetailsToBeUpdated = providerSpecificDetails.VMNics.SingleOrDefault(
                            n => string.Compare(n.NicId, this.PrimaryNic, StringComparison.OrdinalIgnoreCase) == 0);
                        if (vMNicDetailsToBeUpdated != null)
                        {
                            VMNicInputDetails vMNicInputDetails = new VMNicInputDetails();

                            vMNicInputDetails.NicId = this.PrimaryNic;
                            vMNicInputDetails.RecoveryVMSubnetName      = this.RecoveryNicSubnetName;
                            vMNicInputDetails.ReplicaNicStaticIPAddress = this.RecoveryNicStaticIPAddress;
                            vMNicInputDetails.SelectionType             =
                                string.IsNullOrEmpty(this.NicSelectionType) ? Constants.SelectedByUser : this.NicSelectionType;
                            vMNicInputDetailsList.Add(vMNicInputDetails);

                            IEnumerable <VMNicDetails> vMNicDetailsListRemaining = providerSpecificDetails.VMNics.Where(
                                n => string.Compare(n.NicId, this.PrimaryNic, StringComparison.OrdinalIgnoreCase) != 0);
                            foreach (VMNicDetails nDetails in vMNicDetailsListRemaining)
                            {
                                vMNicInputDetails = new VMNicInputDetails();

                                vMNicInputDetails.NicId = nDetails.NicId;
                                vMNicInputDetails.RecoveryVMSubnetName      = nDetails.RecoveryVMSubnetName;
                                vMNicInputDetails.ReplicaNicStaticIPAddress = nDetails.ReplicaNicStaticIPAddress;
                                vMNicInputDetails.SelectionType             = nDetails.SelectionType;
                                vMNicInputDetailsList.Add(vMNicInputDetails);
                            }
                        }
                        else
                        {
                            throw new PSInvalidOperationException(Properties.Resources.NicNotFoundInVMForUpdateVmProperties);
                        }
                    }
                }
                else
                {
                    VMNicInputDetails vMNicInputDetails;
                    foreach (VMNicDetails nDetails in providerSpecificDetails.VMNics)
                    {
                        vMNicInputDetails = new VMNicInputDetails();

                        vMNicInputDetails.NicId = nDetails.NicId;
                        vMNicInputDetails.RecoveryVMSubnetName      = nDetails.RecoveryVMSubnetName;
                        vMNicInputDetails.ReplicaNicStaticIPAddress = nDetails.ReplicaNicStaticIPAddress;
                        vMNicInputDetails.SelectionType             = nDetails.SelectionType;
                        vMNicInputDetailsList.Add(vMNicInputDetails);
                    }
                }
            }
            else if (0 == string.Compare(provider, Constants.InMageAzureV2, StringComparison.OrdinalIgnoreCase))
            {
                InMageAzureV2ProviderSpecificSettings providerSpecificDetails =
                    (InMageAzureV2ProviderSpecificSettings)replicationProtectedItemResponse.ReplicationProtectedItem.Properties.ProviderSpecificDetails;

                if (string.IsNullOrEmpty(this.Name))
                {
                    vmName = providerSpecificDetails.RecoveryAzureVMName;
                }

                if (string.IsNullOrEmpty(this.Size))
                {
                    vmSize = providerSpecificDetails.RecoveryAzureVMSize;
                }

                if (string.IsNullOrEmpty(this.RecoveryNetworkId))
                {
                    vmRecoveryNetworkId = providerSpecificDetails.SelectedRecoveryAzureNetworkId;
                }

                if (string.IsNullOrEmpty(this.LicenseType))
                {
                    licenseType = providerSpecificDetails.LicenseType;
                }

                if (!string.IsNullOrEmpty(this.PrimaryNic))
                {
                    if (providerSpecificDetails.VMNics != null)
                    {
                        vMNicDetailsToBeUpdated = providerSpecificDetails.VMNics.SingleOrDefault(
                            n => string.Compare(n.NicId, this.PrimaryNic, StringComparison.OrdinalIgnoreCase) == 0);
                        if (vMNicDetailsToBeUpdated != null)
                        {
                            VMNicInputDetails vMNicInputDetails = new VMNicInputDetails();

                            vMNicInputDetails.NicId = this.PrimaryNic;
                            vMNicInputDetails.RecoveryVMSubnetName      = this.RecoveryNicSubnetName;
                            vMNicInputDetails.ReplicaNicStaticIPAddress = this.RecoveryNicStaticIPAddress;
                            vMNicInputDetails.SelectionType             = string.IsNullOrEmpty(this.NicSelectionType) ? Constants.SelectedByUser : this.NicSelectionType;
                            vMNicInputDetailsList.Add(vMNicInputDetails);

                            IEnumerable <VMNicDetails> vMNicDetailsListRemaining = providerSpecificDetails.VMNics.Where(
                                n => string.Compare(n.NicId, this.PrimaryNic, StringComparison.OrdinalIgnoreCase) != 0);
                            foreach (VMNicDetails nDetails in vMNicDetailsListRemaining)
                            {
                                vMNicInputDetails = new VMNicInputDetails();

                                vMNicInputDetails.NicId = nDetails.NicId;
                                vMNicInputDetails.RecoveryVMSubnetName      = nDetails.RecoveryVMSubnetName;
                                vMNicInputDetails.ReplicaNicStaticIPAddress = nDetails.ReplicaNicStaticIPAddress;
                                vMNicInputDetails.SelectionType             = nDetails.SelectionType;
                                vMNicInputDetailsList.Add(vMNicInputDetails);
                            }
                        }
                        else
                        {
                            throw new PSInvalidOperationException(Properties.Resources.NicNotFoundInVMForUpdateVmProperties);
                        }
                    }
                }
                else
                {
                    VMNicInputDetails vMNicInputDetails;
                    foreach (VMNicDetails nDetails in providerSpecificDetails.VMNics)
                    {
                        vMNicInputDetails = new VMNicInputDetails();

                        vMNicInputDetails.NicId = nDetails.NicId;
                        vMNicInputDetails.RecoveryVMSubnetName      = nDetails.RecoveryVMSubnetName;
                        vMNicInputDetails.ReplicaNicStaticIPAddress = nDetails.ReplicaNicStaticIPAddress;
                        vMNicInputDetails.SelectionType             = nDetails.SelectionType;
                        vMNicInputDetailsList.Add(vMNicInputDetails);
                    }
                }
            }

            UpdateReplicationProtectedItemInputProperties updateReplicationProtectedItemInputProperties =
                new UpdateReplicationProtectedItemInputProperties()
            {
                RecoveryAzureVMName            = vmName,
                RecoveryAzureVMSize            = vmSize,
                SelectedRecoveryAzureNetworkId = vmRecoveryNetworkId,
                VmNics      = vMNicInputDetailsList,
                LicenseType = licenseType
            };

            UpdateReplicationProtectedItemInput input = new UpdateReplicationProtectedItemInput()
            {
                Properties = updateReplicationProtectedItemInputProperties
            };

            LongRunningOperationResponse response = RecoveryServicesClient.UpdateVmProperties(
                Utilities.GetValueFromArmId(this.ReplicationProtectedItem.ID, ARMResourceTypeConstants.ReplicationFabrics),
                Utilities.GetValueFromArmId(this.ReplicationProtectedItem.ID, ARMResourceTypeConstants.ReplicationProtectionContainers),
                ReplicationProtectedItem.Name,
                input);

            JobResponse jobResponse =
                RecoveryServicesClient
                .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location));

            WriteObject(new ASRJob(jobResponse.Job));
        }
        /// <summary>
        /// ProcessRecord of the command.
        /// </summary>
        public override void ExecuteSiteRecoveryCmdlet()
        {
            base.ExecuteSiteRecoveryCmdlet();

            var policy = RecoveryServicesClient.GetAzureSiteRecoveryPolicy(
                Utilities.GetValueFromArmId(this.ProtectionContainerMapping.PolicyId, ARMResourceTypeConstants.Policies)).Policy;
            var policyInstanceType = policy.Properties.ProviderSpecificDetails.InstanceType;

            switch (this.ParameterSetName)
            {
            case ASRParameterSets.EnterpriseToEnterprise:
                if (policyInstanceType != Constants.HyperVReplica2012 &&
                    policyInstanceType != Constants.HyperVReplica2012R2)
                {
                    throw new PSArgumentException(
                              string.Format(
                                  Properties.Resources.ContainerMappingParameterSetMismatch,
                                  this.ProtectionContainerMapping.Name,
                                  policyInstanceType));
                }
                break;

            case ASRParameterSets.EnterpriseToAzure:
            case ASRParameterSets.HyperVSiteToAzure:
                if (policyInstanceType != Constants.HyperVReplicaAzure)
                {
                    throw new PSArgumentException(
                              string.Format(
                                  Properties.Resources.ContainerMappingParameterSetMismatch,
                                  this.ProtectionContainerMapping.Name,
                                  policyInstanceType));
                }
                break;

            default:
                break;
            }

            EnableProtectionProviderSpecificInput enableProtectionProviderSpecificInput = new EnableProtectionProviderSpecificInput();
            EnableProtectionInputProperties       inputProperties = new EnableProtectionInputProperties()
            {
                PolicyId                = this.ProtectionContainerMapping.PolicyId,
                ProtectableItemId       = this.ProtectableItem.ID,
                ProviderSpecificDetails = enableProtectionProviderSpecificInput
            };

            EnableProtectionInput 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))
            {
                HyperVReplicaAzureEnableProtectionInput providerSettings = new HyperVReplicaAzureEnableProtectionInput();
                providerSettings.HvHostVmId = this.ProtectableItem.FabricObjectId;
                providerSettings.VmName     = 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
                    ProtectableItemResponse protectableItemResponse =
                        RecoveryServicesClient.GetAzureSiteRecoveryProtectableItem(
                            Utilities.GetValueFromArmId(this.ProtectableItem.ID, ARMResourceTypeConstants.ReplicationFabrics),
                            this.ProtectableItem.ProtectionContainerId,
                            this.ProtectableItem.Name);

                    this.ProtectableItem = new ASRProtectableItem(protectableItemResponse.ProtectableItem);
                }

                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 (RecoveryAzureStorageAccountId != null)
                {
                    providerSettings.TargetStorageAccountId = RecoveryAzureStorageAccountId;
                }

                input.Properties.ProviderSpecificDetails = providerSettings;
            }

            this.response =
                RecoveryServicesClient.EnableProtection(
                    Utilities.GetValueFromArmId(this.ProtectableItem.ID, ARMResourceTypeConstants.ReplicationFabrics),
                    Utilities.GetValueFromArmId(this.ProtectableItem.ID, ARMResourceTypeConstants.ReplicationProtectionContainers),
                    Name,
                    input);

            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>
        /// Creates an E2E Policy object
        /// </summary>
        private void EnterpriseToEnterprisePolicyObject()
        {
            if (string.Compare(this.ReplicationProvider, Constants.HyperVReplica2012, StringComparison.OrdinalIgnoreCase) != 0 && string.Compare(this.ReplicationProvider, Constants.HyperVReplica2012R2, StringComparison.OrdinalIgnoreCase) != 0)
            {
                throw new InvalidOperationException(
                          string.Format(
                              Properties.Resources.IncorrectReplicationProvider,
                              this.ReplicationProvider));
            }

            PSRecoveryServicesClient.ValidateReplicationStartTime(this.ReplicationStartTime);

            ushort replicationFrequencyInSeconds =
                PSRecoveryServicesClient.ConvertReplicationFrequencyToUshort(this.ReplicationFrequencyInSeconds);

            CreatePolicyInputProperties createPolicyInputProperties = new CreatePolicyInputProperties();

            if (string.Compare(this.ReplicationProvider, Constants.HyperVReplica2012, StringComparison.OrdinalIgnoreCase) == 0)
            {
                createPolicyInputProperties.ProviderSpecificInput = new HyperVReplica2012PolicyInput()
                {
                    AllowedAuthenticationType =
                        (ushort)((string.Compare(this.Authentication, Constants.AuthenticationTypeKerberos, StringComparison.OrdinalIgnoreCase) == 0) ? 1 : 2),
                    ApplicationConsistentSnapshotFrequencyInHours = this.ApplicationConsistentSnapshotFrequencyInHours,
                    Compression = this.CompressionEnabled == true ? "Enable" : "Disable",
                    InitialReplicationMethod =
                        (string.Compare(this.ReplicationMethod, Constants.OnlineReplicationMethod, StringComparison.OrdinalIgnoreCase) == 0) ? "OverNetwork" : "Offline",
                    OnlineReplicationStartTime = this.ReplicationStartTime,
                    RecoveryPoints             = this.RecoveryPoints,
                    ReplicaDeletion            = this.AllowReplicaDeletion == true ? "Required" : "NotRequired",
                    ReplicationPort            = this.ReplicationPort
                };
            }
            else
            {
                createPolicyInputProperties.ProviderSpecificInput = new HyperVReplica2012R2PolicyInput()
                {
                    AllowedAuthenticationType =
                        (ushort)((string.Compare(this.Authentication, Constants.AuthenticationTypeKerberos, StringComparison.OrdinalIgnoreCase) == 0) ? 1 : 2),
                    ApplicationConsistentSnapshotFrequencyInHours = this.ApplicationConsistentSnapshotFrequencyInHours,
                    Compression = this.CompressionEnabled == true ? "Enable" : "Disable",
                    InitialReplicationMethod =
                        (string.Compare(this.ReplicationMethod, Constants.OnlineReplicationMethod, StringComparison.OrdinalIgnoreCase) == 0) ? "OverNetwork" : "Offline",
                    OnlineReplicationStartTime    = this.ReplicationStartTime,
                    RecoveryPoints                = this.RecoveryPoints,
                    ReplicaDeletion               = this.AllowReplicaDeletion == true ? "Required" : "NotRequired",
                    ReplicationFrequencyInSeconds = replicationFrequencyInSeconds,
                    ReplicationPort               = this.ReplicationPort
                };
            }

            CreatePolicyInput createPolicyInput = new CreatePolicyInput()
            {
                Properties = createPolicyInputProperties
            };

            LongRunningOperationResponse responseBlue =
                RecoveryServicesClient.CreatePolicy(this.Name, createPolicyInput);

            JobResponse jobResponseBlue =
                RecoveryServicesClient
                .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(responseBlue.Location));

            WriteObject(new ASRJob(jobResponseBlue.Job));
        }
Exemple #7
0
        /// <summary>
        /// PE Reprotect.
        /// </summary>
        private void SetPEReprotect()
        {
            ReverseReplicationInputProperties plannedFailoverInputProperties = new ReverseReplicationInputProperties()
            {
                FailoverDirection       = this.Direction,
                ProviderSpecificDetails = new ReverseReplicationProviderSpecificInput()
            };

            ReverseReplicationInput input = new ReverseReplicationInput()
            {
                Properties = plannedFailoverInputProperties
            };

            // fetch the latest PE object
            ProtectableItemResponse protectableItemResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryProtectableItem(this.fabricName,
                                                                           this.ProtectionEntity.ProtectionContainerId, this.ProtectionEntity.Name);

            ReplicationProtectedItemResponse replicationProtectedItemResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryReplicationProtectedItem(this.fabricName,
                                                                                    this.ProtectionEntity.ProtectionContainerId, Utilities.GetValueFromArmId(protectableItemResponse.ProtectableItem.Properties.ReplicationProtectedItemId, ARMResourceTypeConstants.ReplicationProtectedItems));

            PolicyResponse policyResponse = RecoveryServicesClient.GetAzureSiteRecoveryPolicy(Utilities.GetValueFromArmId(replicationProtectedItemResponse.ReplicationProtectedItem.Properties.PolicyID, ARMResourceTypeConstants.ReplicationPolicies));

            this.ProtectionEntity = new ASRProtectionEntity(protectableItemResponse.ProtectableItem, replicationProtectedItemResponse.ReplicationProtectedItem);

            if (0 == string.Compare(
                    this.ProtectionEntity.ReplicationProvider,
                    Constants.HyperVReplicaAzure,
                    StringComparison.OrdinalIgnoreCase))
            {
                if (this.Direction == Constants.PrimaryToRecovery)
                {
                    HyperVReplicaAzureReprotectInput reprotectInput = new HyperVReplicaAzureReprotectInput()
                    {
                        HvHostVmId = this.ProtectionEntity.FabricObjectId,
                        VmName     = this.ProtectionEntity.FriendlyName,
                        OSType     = ((string.Compare(this.ProtectionEntity.OS, "Windows") == 0) || (string.Compare(this.ProtectionEntity.OS, "Linux") == 0)) ? this.ProtectionEntity.OS : "Windows",
                        VHDId      = this.ProtectionEntity.OSDiskId
                    };

                    HyperVReplicaAzureReplicationDetails providerSpecificDetails =
                        (HyperVReplicaAzureReplicationDetails)replicationProtectedItemResponse.ReplicationProtectedItem.Properties.ProviderSpecificDetails;

                    reprotectInput.StorageAccountId = providerSpecificDetails.RecoveryAzureStorageAccount;

                    input.Properties.ProviderSpecificDetails = reprotectInput;
                }
            }

            LongRunningOperationResponse response =
                RecoveryServicesClient.StartAzureSiteRecoveryReprotection(
                    this.fabricName,
                    this.protectionContainerName,
                    Utilities.GetValueFromArmId(replicationProtectedItemResponse.ReplicationProtectedItem.Id, ARMResourceTypeConstants.ReplicationProtectedItems),
                    input);

            JobResponse jobResponse =
                RecoveryServicesClient
                .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location));

            WriteObject(new ASRJob(jobResponse.Job));
        }
Exemple #8
0
        /// <summary>
        /// Starts PE Planned failover.
        /// </summary>
        private void StartPEPlannedFailover()
        {
            PlannedFailoverInputProperties plannedFailoverInputProperties = new PlannedFailoverInputProperties()
            {
                FailoverDirection       = this.Direction,
                ProviderSpecificDetails = new ProviderSpecificFailoverInput()
            };

            PlannedFailoverInput input = new PlannedFailoverInput()
            {
                Properties = plannedFailoverInputProperties
            };

            // fetch the latest PE object
            ProtectableItemResponse protectableItemResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryProtectableItem(this.fabricName,
                                                                           this.ProtectionEntity.ProtectionContainerId, this.ProtectionEntity.Name);

            ReplicationProtectedItemResponse replicationProtectedItemResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryReplicationProtectedItem(this.fabricName,
                                                                                    this.ProtectionEntity.ProtectionContainerId, Utilities.GetValueFromArmId(protectableItemResponse.ProtectableItem.Properties.ReplicationProtectedItemId, ARMResourceTypeConstants.ReplicationProtectedItems));

            PolicyResponse policyResponse = RecoveryServicesClient.GetAzureSiteRecoveryPolicy(Utilities.GetValueFromArmId(replicationProtectedItemResponse.ReplicationProtectedItem.Properties.PolicyID, ARMResourceTypeConstants.ReplicationPolicies));

            this.ProtectionEntity = new ASRProtectionEntity(protectableItemResponse.ProtectableItem, replicationProtectedItemResponse.ReplicationProtectedItem);


            if (0 == string.Compare(
                    this.ProtectionEntity.ReplicationProvider,
                    Constants.HyperVReplicaAzure,
                    StringComparison.OrdinalIgnoreCase))
            {
                if (this.Direction == Constants.PrimaryToRecovery)
                {
                    HyperVReplicaAzureFailoverProviderInput failoverInput = new HyperVReplicaAzureFailoverProviderInput()
                    {
                        PrimaryKekCertificatePfx   = null,
                        SecondaryKekCertificatePfx = null,
                        VaultLocation = this.GetCurrentValutLocation()
                    };
                    input.Properties.ProviderSpecificDetails = failoverInput;
                }
                else
                {
                    HyperVReplicaAzureFailbackProviderInput failbackInput = new HyperVReplicaAzureFailbackProviderInput()
                    {
                        DataSyncOption = this.Optimize == Constants.ForDowntime ? Constants.ForDowntime : Constants.ForSynchronization,
                        //ProviderIdForAlternateRecovery = "",
                        RecoveryVmCreationOption = "CreateVmIfNotFound" //CreateVmIfNotFound | NoAction
                    };
                    input.Properties.ProviderSpecificDetails = failbackInput;
                }
            }

            LongRunningOperationResponse response =
                RecoveryServicesClient.StartAzureSiteRecoveryPlannedFailover(
                    this.fabricName,
                    this.protectionContainerName,
                    Utilities.GetValueFromArmId(replicationProtectedItemResponse.ReplicationProtectedItem.Id, ARMResourceTypeConstants.ReplicationProtectedItems),
                    input);

            JobResponse jobResponse =
                RecoveryServicesClient
                .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location));

            WriteObject(new ASRJob(jobResponse.Job));
        }
Exemple #9
0
        /// <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>
        /// Creates an E2A Policy Object
        /// </summary>
        private void EnterpriseToAzurePolicyObject()
        {
            if (string.Compare(this.Policy.ReplicationProvider, Constants.HyperVReplicaAzure, StringComparison.OrdinalIgnoreCase) != 0)
            {
                throw new InvalidOperationException(
                          string.Format(
                              Properties.Resources.IncorrectReplicationProvider,
                              this.Policy.ReplicationProvider));
            }

            var replicationProviderSettings = this.Policy.ReplicationProviderSettings as ASRHyperVReplicaAzurePolicyDetails;

            this.replicationFrequencyInSeconds = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.ReplicationFrequencyInSeconds)) ?
                                                 PSRecoveryServicesClient.ConvertReplicationFrequencyToUshort(this.ReplicationFrequencyInSeconds) :
                                                 (ushort)replicationProviderSettings.ReplicationFrequencyInSeconds;
            this.recoveryPoints = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.RecoveryPoints)) ?
                                  this.RecoveryPoints :
                                  replicationProviderSettings.RecoveryPoints;
            this.applicationConsistentSnapshotFrequencyInHours = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.ApplicationConsistentSnapshotFrequencyInHours)) ?
                                                                 this.ApplicationConsistentSnapshotFrequencyInHours :
                                                                 replicationProviderSettings.ApplicationConsistentSnapshotFrequencyInHours;
            this.replicationStartTime = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.ReplicationStartTime)) ?
                                        this.replicationStartTime :
                                        replicationProviderSettings.OnlineReplicationStartTime;
            this.recoveryAzureStorageAccountId = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.RecoveryAzureStorageAccountId)) ?
                                                 this.RecoveryAzureStorageAccountId :
                                                 replicationProviderSettings.ActiveStorageAccountId;
            this.encryption = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.Encryption)) ?
                              this.Encryption :
                              ((string.Compare(replicationProviderSettings.Encryption, "Disabled", StringComparison.OrdinalIgnoreCase) == 0) ? Constants.Disable : Constants.Enable);

            var hyperVReplicaAzurePolicyInput = new HyperVReplicaAzurePolicyInput()
            {
                ApplicationConsistentSnapshotFrequencyInHours = this.applicationConsistentSnapshotFrequencyInHours,
                Encryption                   = this.encryption,
                OnlineIrStartTime            = this.replicationStartTime,
                RecoveryPointHistoryDuration = this.recoveryPoints,
                ReplicationInterval          = this.replicationFrequencyInSeconds
            };

            hyperVReplicaAzurePolicyInput.StorageAccounts =
                new System.Collections.Generic.List <string>();

            if (RecoveryAzureStorageAccountId != null)
            {
                string storageAccount = this.recoveryAzureStorageAccountId;
                hyperVReplicaAzurePolicyInput.StorageAccounts.Add(storageAccount);
            }

            var updatePolicyProperties = new UpdatePolicyProperties()
            {
                ReplicationProviderSettings = hyperVReplicaAzurePolicyInput
            };

            var updatePolicyInput = new UpdatePolicyInput()
            {
                Properties = updatePolicyProperties
            };

            LongRunningOperationResponse response =
                RecoveryServicesClient.UpdatePolicy(this.Policy.Name, updatePolicyInput);

            JobResponse jobResponse =
                RecoveryServicesClient
                .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location));

            WriteObject(new ASRJob(jobResponse.Job));
        }
        /// <summary>
        /// Starts PE Test failover.
        /// </summary>
        private void StartPETestFailover()
        {
            var request = new TestFailoverRequest();

            if (this.ProtectionEntity == null)
            {
                var pe = RecoveryServicesClient.GetAzureSiteRecoveryProtectionEntity(
                    this.ProtectionEntity.ProtectionContainerId,
                    this.ProtectionEntity.Name);
                this.ProtectionEntity = new ASRProtectionEntity(pe.ProtectionEntity);
            }

            request.FailoverDirection = this.Direction;
            request.NetworkID         = this.networkId;
            request.NetworkType       = this.networkType;

            if (string.IsNullOrEmpty(this.ProtectionEntity.ReplicationProvider))
            {
                // fetch the latest PE object
                // 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.
                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;
                    }
                }
            }

            request.ReplicationProvider         = this.ProtectionEntity.ReplicationProvider;
            request.ReplicationProviderSettings = new FailoverReplicationProviderSpecificInput();

            if (0 == string.Compare(
                    this.ProtectionEntity.ReplicationProvider,
                    Constants.HyperVReplicaAzure,
                    StringComparison.OrdinalIgnoreCase))
            {
                AzureFailoverInput failoverInput = new AzureFailoverInput()
                {
                    PrimaryKekCertificatePfx   = string.Empty,
                    SecondaryKekCertificatePfx = string.Empty,
                    VaultLocation = this.GetCurrentValutLocation()
                };
                request.ReplicationProviderSettings = failoverInput;
            }

            LongRunningOperationResponse response =
                RecoveryServicesClient.StartAzureSiteRecoveryTestFailover(
                    this.ProtectionEntity.ProtectionContainerId,
                    this.ProtectionEntity.Name,
                    request);

            JobResponse jobResponse =
                RecoveryServicesClient
                .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location));

            WriteObject(new ASRJob(jobResponse.Job));
        }
        /// <summary>
        /// Creates an E2E Policy object
        /// </summary>
        private void EnterpriseToEnterprisePolicyObject()
        {
            if (string.Compare(this.Policy.ReplicationProvider, Constants.HyperVReplica2012, StringComparison.OrdinalIgnoreCase) != 0 && string.Compare(this.Policy.ReplicationProvider, Constants.HyperVReplica2012R2, StringComparison.OrdinalIgnoreCase) != 0)
            {
                throw new InvalidOperationException(
                          string.Format(
                              Properties.Resources.IncorrectReplicationProvider,
                              this.Policy.ReplicationProvider));
            }

            var replicationProviderSettings = this.Policy.ReplicationProviderSettings as ASRHyperVReplicaPolicyDetails;

            this.replicationMethod = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.ReplicationMethod)) ?
                                     ((string.Compare(this.ReplicationMethod, Constants.OnlineReplicationMethod, StringComparison.OrdinalIgnoreCase) == 0) ? "OverNetwork" : "Offline") :
                                     ((string.Compare(replicationProviderSettings.InitialReplicationMethod, Constants.OnlineReplicationMethod, StringComparison.OrdinalIgnoreCase) == 0) ? "OverNetwork" : "Offline");
            this.replicationFrequencyInSeconds = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.ReplicationFrequencyInSeconds)) ?
                                                 PSRecoveryServicesClient.ConvertReplicationFrequencyToUshort(this.ReplicationFrequencyInSeconds) :
                                                 replicationProviderSettings.ReplicationFrequencyInSeconds;
            this.recoveryPoints = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.RecoveryPoints)) ?
                                  this.RecoveryPoints :
                                  replicationProviderSettings.RecoveryPoints;
            this.applicationConsistentSnapshotFrequencyInHours = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.ApplicationConsistentSnapshotFrequencyInHours)) ?
                                                                 this.ApplicationConsistentSnapshotFrequencyInHours :
                                                                 replicationProviderSettings.ApplicationConsistentSnapshotFrequencyInHours;
            this.compression = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.Compression)) ?
                               this.Compression :
                               replicationProviderSettings.Compression;
            this.replicationPort = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.ReplicationPort)) ?
                                   this.ReplicationPort :
                                   replicationProviderSettings.ReplicationPort;
            this.authentication = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.Authentication)) ?
                                  ((ushort)((string.Compare(this.Authentication, Constants.AuthenticationTypeKerberos, StringComparison.OrdinalIgnoreCase) == 0) ? 1 : 2)) :
                                  ((ushort)((string.Compare(replicationProviderSettings.AllowedAuthenticationType, Constants.AuthenticationTypeKerberos, StringComparison.OrdinalIgnoreCase) == 0) ? 1 : 2));
            this.replicationStartTime = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.ReplicationStartTime)) ?
                                        this.replicationStartTime :
                                        replicationProviderSettings.OnlineReplicationStartTime;
            this.replicaDeletion = this.MyInvocation.BoundParameters.ContainsKey(Utilities.GetMemberName(() => this.ReplicaDeletion)) ?
                                   this.ReplicaDeletion :
                                   replicationProviderSettings.ReplicaDeletionOption;

            var updatePolicyProperties = new UpdatePolicyProperties();

            if (string.Compare(this.Policy.ReplicationProvider, Constants.HyperVReplica2012, StringComparison.OrdinalIgnoreCase) == 0)
            {
                updatePolicyProperties.ReplicationProviderSettings = new HyperVReplica2012PolicyInput()
                {
                    AllowedAuthenticationType = this.authentication,
                    ApplicationConsistentSnapshotFrequencyInHours = this.applicationConsistentSnapshotFrequencyInHours,
                    Compression = this.compression,
                    InitialReplicationMethod   = this.replicationMethod,
                    OnlineReplicationStartTime = this.replicationStartTime,
                    RecoveryPoints             = this.recoveryPoints,
                    ReplicaDeletion            = this.replicaDeletion,
                    ReplicationPort            = this.replicationPort
                };
            }
            else
            {
                updatePolicyProperties.ReplicationProviderSettings = new HyperVReplica2012R2PolicyInput()
                {
                    AllowedAuthenticationType = this.authentication,
                    ApplicationConsistentSnapshotFrequencyInHours = this.applicationConsistentSnapshotFrequencyInHours,
                    Compression = this.compression,
                    InitialReplicationMethod      = this.replicationMethod,
                    OnlineReplicationStartTime    = this.replicationStartTime,
                    RecoveryPoints                = this.recoveryPoints,
                    ReplicaDeletion               = this.replicaDeletion,
                    ReplicationPort               = this.replicationPort,
                    ReplicationFrequencyInSeconds = replicationFrequencyInSeconds
                };
            }

            var updatePolicyInput = new UpdatePolicyInput()
            {
                Properties = updatePolicyProperties
            };

            LongRunningOperationResponse responseBlue =
                RecoveryServicesClient.UpdatePolicy(this.Policy.Name, updatePolicyInput);

            JobResponse jobResponseBlue =
                RecoveryServicesClient
                .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(responseBlue.Location));

            WriteObject(new ASRJob(jobResponseBlue.Job));
        }
Exemple #13
0
        /// <summary>
        /// Set PE protection.
        /// </summary>
        private void SetPEReprotect()
        {
            var request = new ReprotectRequest();

            request.FailoverDirection = this.Direction;

            if (string.IsNullOrEmpty(this.ProtectionEntity.ReplicationProvider))
            {
                // fetch the latest PE object
                // 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.
                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;
                    }
                }
            }

            request.ReplicationProvider         = this.ProtectionEntity.ReplicationProvider;
            request.ReplicationProviderSettings = new FailoverReplicationProviderSpecificInput();

            if ((this.Direction == Constants.PrimaryToRecovery &&
                 this.ProtectionEntity.ActiveLocation == Constants.RecoveryLocation) ||
                (this.Direction == Constants.RecoveryToPrimary &&
                 this.ProtectionEntity.ActiveLocation == Constants.PrimaryLocation))
            {
                throw new ArgumentException("Parameter value is not correct.", "Direction");
            }

            if (0 == string.Compare(
                    this.ProtectionEntity.ReplicationProvider,
                    Constants.HyperVReplicaAzure,
                    StringComparison.OrdinalIgnoreCase))
            {
                if (this.Direction == Constants.PrimaryToRecovery)
                {
                    AzureReprotectInput reprotectInput = new AzureReprotectInput()
                    {
                        HvHostVmId = this.ProtectionEntity.FabricObjectId,
                        VmName     = this.ProtectionEntity.Name,
                        OSType     = this.ProtectionEntity.OS,
                        VHDId      = this.ProtectionEntity.OSDiskId
                    };

                    request.ReplicationProviderSettings = reprotectInput;
                }
            }

            LongRunningOperationResponse response = RecoveryServicesClient.StartAzureSiteRecoveryReprotection(
                this.protectionContainerId,
                this.protectionEntityId,
                request);

            JobResponse jobResponse =
                RecoveryServicesClient
                .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location));

            WriteObject(new ASRJob(jobResponse.Job));
        }
Exemple #14
0
        private void DeleteResources(ClearResourcesInputs inputs)
        {
            if (inputs.NamespaceExists)
            {
                _ConsoleBuffer.Add("Connecting to Service Bus...");
                ServiceBusManagementClient sbMgmt = new ServiceBusManagementClient(inputs.Credentials);

                bool deleteNamespace = ConsoleHelper.AskAndPerformAction(
                    "Do you want to delete whole namespace " + inputs.SBNamespace + " including all entities under it?",
                    "Are you sure you want to delete namespace " + inputs.SBNamespace + "?",
                    "Are you sure you do not want to delete namespace " + inputs.SBNamespace + "?",
                    () =>
                {
                    _ConsoleBuffer.Add("Sending request to delete " + inputs.SBNamespace + " namespace...");
                    AzureOperationResponse nsResponse = sbMgmt.Namespaces.Delete(inputs.SBNamespace);
                    if (nsResponse.StatusCode == HttpStatusCode.OK)
                    {
                        _ConsoleBuffer.Add(inputs.SBNamespace + " namespace was deleted.");
                    }
                },
                    _ConsoleBuffer);

                //if we did not delete whole Namespace, maybe we want to delete some of its Event Hubs?
                if (!deleteNamespace)
                {
                    _ConsoleBuffer.Add("Reading list of Event Hubs from " + inputs.SBNamespace + " namespace...");

                    var nsDescription      = sbMgmt.Namespaces.GetNamespaceDescription(inputs.SBNamespace);
                    var nsConnectionString = nsDescription.NamespaceDescriptions.First(
                        (d) => String.Equals(d.AuthorizationType, "SharedAccessAuthorization")
                        ).ConnectionString;
                    var nsManager = NamespaceManager.CreateFromConnectionString(nsConnectionString);

                    var eventHubs = nsManager.GetEventHubs( );

                    foreach (var eventHubDescription in eventHubs)
                    {
                        EventHubDescription description = eventHubDescription;
                        ConsoleHelper.AskAndPerformAction(
                            "Do you want to delete Event Hub " + eventHubDescription.Path +
                            " including all messages under it?",
                            "Are you sure you want to delete Event Hub " + eventHubDescription.Path + "?",
                            "Are you sure you do not want to delete Event Hub " + eventHubDescription.Path + "?",
                            () =>
                        {
                            _ConsoleBuffer.Add("Sending request to delete " + description.Path + " Event Hub...");
                            nsManager.DeleteEventHub(description.Path);
                            _ConsoleBuffer.Add("Request to delete " + description.Path + " Event Hub was accepted.");
                        },
                            _ConsoleBuffer);
                    }
                }
            }

            //Deleting Storage
            _ConsoleBuffer.Add("Reading list of Storage Accounts...");
            StorageManagementClient stgMgmt         = new StorageManagementClient(inputs.Credentials);
            HashSet <string>        storageAccounts = new HashSet <string>( );

            foreach (var storageAccount in stgMgmt.StorageAccounts.List( ))
            {
                storageAccounts.Add(storageAccount.Name);
            }

            int deletedCount = 0;

            if (storageAccounts.Contains(inputs.StorageAccountName))
            {
                ConsoleHelper.AskAndPerformAction(
                    "Do you want to delete " + inputs.StorageAccountName + " storage account?",
                    "Are you sure you want to delete " + inputs.StorageAccountName + " storage account?",
                    "Are you sure you do not want to delete " + inputs.StorageAccountName + " storage account?",
                    () =>
                {
                    _ConsoleBuffer.Add("Sending request to delete " + inputs.StorageAccountName + " Storage account...");
                    AzureOperationResponse resultStg = stgMgmt.StorageAccounts.Delete(inputs.StorageAccountName);
                    deletedCount += 1;
                    if (resultStg.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        _ConsoleBuffer.Add("Storage account " + inputs.StorageAccountName + " was deleted.");
                    }
                },
                    _ConsoleBuffer);
            }
            if (deletedCount == 0)
            {
                _ConsoleBuffer.Add("No related Storage account was detected.");
            }

            //Deleting Stream Analytics jobs
            _ConsoleBuffer.Add("Reading list of Stream Analytics jobs...");
            StreamAnalyticsManagementClient saMgmt = new StreamAnalyticsManagementClient(inputs.Credentials);
            JobListResponse jobListResponse        = saMgmt.StreamingJobs.ListJobsInSubscription(new JobListParameters {
                PropertiesToExpand = string.Empty
            });

            deletedCount = 0;
            foreach (var job in jobListResponse.Value)
            {
                if (job.Name.StartsWith(inputs.NamePrefix))
                {
                    Job jobToAsk = job;
                    ConsoleHelper.AskAndPerformAction(
                        "Do you want to delete Stream Analytics job " + job.Name + "?",
                        "Are you sure you want to delete Stream Analytics job  " + job.Name + "?",
                        "Are you sure you do not want to delete namespace " + job.Name + "?",
                        () =>
                    {
                        //we need to figure out wat resourceGroup this job belongs to
                        //--//
                        const string resourceGroupPath = "/resourceGroups/";
                        const string providersPath     = "/providers/";

                        int resourceGroupPathIndex    = jobToAsk.Id.IndexOf(resourceGroupPath, System.StringComparison.Ordinal);
                        int providersPathIndex        = jobToAsk.Id.IndexOf(providersPath, System.StringComparison.Ordinal);
                        int resourceGroupIdStartIndex = resourceGroupPathIndex + resourceGroupPath.Length;

                        string resourceGroup = jobToAsk.Id.Substring(resourceGroupIdStartIndex, providersPathIndex - resourceGroupIdStartIndex);
                        //--//

                        deletedCount += 1;
                        _ConsoleBuffer.Add("Sending request to delete " + jobToAsk.Name + " Stream Analytics job...");
                        LongRunningOperationResponse response = saMgmt.StreamingJobs.Delete(resourceGroup, jobToAsk.Name);
                        if (response.Status == OperationStatus.Succeeded)
                        {
                            _ConsoleBuffer.Add("Stream Analytics job " + jobToAsk.Name + " was deleted.");
                        }
                    },
                        _ConsoleBuffer);
                }
            }
            if (deletedCount == 0)
            {
                _ConsoleBuffer.Add("No Stream Analytics job was deleted.");
            }
        }
Exemple #15
0
        /// <summary>
        /// ProcessRecord of the command.
        /// </summary>
        public override void ExecuteSiteRecoveryCmdlet()
        {
            base.ExecuteSiteRecoveryCmdlet();

            this.WriteWarningWithTimestamp(
                string.Format(Properties.Resources.CmdletWillBeDeprecatedSoon,
                              this.MyInvocation.MyCommand.Name,
                              "New-AzureRmSiteRecoveryReplicationProtectedItem or Remove-AzureRmSiteRecoveryReplicationProtectedItem"));

            if (0 != string.CompareOrdinal(this.Protection, Constants.DisableProtection) || ShouldProcess(this.ProtectionEntity.FriendlyName, "Disable Protection"))
            {
                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>
        /// Starts RPI Planned failover.
        /// </summary>
        private void StartRPIPlannedFailover()
        {
            var plannedFailoverInputProperties = new PlannedFailoverInputProperties()
            {
                FailoverDirection       = this.Direction,
                ProviderSpecificDetails = new ProviderSpecificFailoverInput()
            };

            var input = new PlannedFailoverInput()
            {
                Properties = plannedFailoverInputProperties
            };

            if (0 == string.Compare(
                    this.ReplicationProtectedItem.ReplicationProvider,
                    Constants.HyperVReplicaAzure,
                    StringComparison.OrdinalIgnoreCase))
            {
                if (this.Direction == Constants.PrimaryToRecovery)
                {
                    var failoverInput = new HyperVReplicaAzureFailoverProviderInput()
                    {
                        PrimaryKekCertificatePfx   = primaryKekCertpfx,
                        SecondaryKekCertificatePfx = secondaryKekCertpfx,
                        VaultLocation = this.GetCurrentVaultLocation()
                    };
                    input.Properties.ProviderSpecificDetails = failoverInput;
                }
                else
                {
                    var failbackInput = new HyperVReplicaAzureFailbackProviderInput()
                    {
                        DataSyncOption           = this.Optimize == Constants.ForDownTime ? Constants.ForDownTime : Constants.ForSynchronization,
                        RecoveryVmCreationOption = String.Compare(this.CreateVmIfNotFound, Constants.Yes, StringComparison.OrdinalIgnoreCase) == 0 ? Constants.CreateVmIfNotFound : Constants.NoAction
                    };

                    if (String.Compare(this.CreateVmIfNotFound, Constants.Yes, StringComparison.OrdinalIgnoreCase) == 0 &&
                        string.Compare(RecoveryServicesClient.GetAzureSiteRecoveryFabric(this.fabricName).Fabric.Properties.CustomDetails.InstanceType, Constants.HyperVSite) == 0)
                    {
                        if (this.ServicesProvider == null || string.Compare(this.ServicesProvider.FabricType, Constants.HyperVSite) != 0)
                        {
                            throw new InvalidOperationException(
                                      Properties.Resources.ImproperServerObjectPassedForHyperVFailback);
                        }
                        else
                        {
                            failbackInput.ProviderIdForAlternateRecovery = this.ServicesProvider.ID;
                        }
                    }

                    input.Properties.ProviderSpecificDetails = failbackInput;
                }
            }

            LongRunningOperationResponse response =
                RecoveryServicesClient.StartAzureSiteRecoveryPlannedFailover(
                    this.fabricName,
                    this.protectionContainerName,
                    this.ReplicationProtectedItem.Name,
                    input);

            JobResponse jobResponse =
                RecoveryServicesClient
                .GetAzureSiteRecoveryJobDetails(PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location));

            WriteObject(new ASRJob(jobResponse.Job));
        }