public void DeviceRestoreScenarioTest()
        {
            using (var context = UndoContext.Current)
            {
                context.Start();

                var client = GetServiceClient <StorSimpleManagementClient>();

                // Listing all Devices
                var devices = client.Devices.List(GetCustomRequestHeaders());

                var onlineDeviceIds = from deviceInfo in devices.Devices
                                      where deviceInfo.Status == DeviceStatus.Online
                                      select deviceInfo.DeviceId;
                Assert.True(onlineDeviceIds.Count() >= 2);
                var sourceDeviceId = onlineDeviceIds.ElementAt(0);
                var targetDeviceId = onlineDeviceIds.ElementAt(1);

                CustomRequestHeaders hdrs = new CustomRequestHeaders();
                hdrs.ClientRequestId = Guid.NewGuid().ToString();
                hdrs.Language        = "en-us";

                //Get service configuration
                var serviceConfigList = client.ServiceConfig.Get(GetCustomRequestHeaders());

                Assert.True(serviceConfigList != null);

                var existingSac = serviceConfigList.CredentialChangeList.Updated.FirstOrDefault();

                Assert.True(existingSac != null);

                var dataContainerName = TestUtilities.GenerateName("DCName");

                // new Data container request object
                var dc = new DataContainerRequest();

                dc.IsDefault                       = false;
                dc.Name                            = dataContainerName;
                dc.BandwidthRate                   = 256;
                dc.VolumeCount                     = 0;
                dc.IsEncryptionEnabled             = false;
                dc.PrimaryStorageAccountCredential = existingSac;

                //Create DataContainer call
                var taskStatus = client.DataContainer.Create(sourceDeviceId, dc, hdrs);

                //Assert the task status
                Assert.NotNull(taskStatus);
                Assert.True(taskStatus.Status == AsyncTaskStatus.Completed);
                Assert.True(taskStatus.Result == AsyncTaskResult.Succeeded);

                //Get Data Container call
                var Createddatacontainer = client.DataContainer.Get(sourceDeviceId, dataContainerName, hdrs);

                //Assert the returned data container object
                Assert.True(Createddatacontainer != null);
                Assert.True(Createddatacontainer.DataContainerInfo.Name.Equals(dataContainerName));

                //ACR list for Virtual disk creation
                List <AccessControlRecord> acrList = new List <AccessControlRecord>();

                for (var i = 0; i < 1; i++)
                {
                    AccessControlRecord acr = new AccessControlRecord()
                    {
                        Name          = TestUtilities.GenerateName("VDnewTestAcr"),
                        InitiatorName = TestUtilities.GenerateName("VDinitiator") + i
                    };
                    acrList.Add(acr);
                }

                //Virtual disk create request object
                var virtualDiskToCreate = new VirtualDiskRequest()
                {
                    Name                   = TestUtilities.GenerateName("VD1Name"),
                    AccessType             = AccessType.ReadWrite,
                    AcrList                = acrList,
                    AppType                = AppType.PrimaryVolume,
                    IsDefaultBackupEnabled = true,
                    SizeInBytes            = 10737418240,
                    DataContainer          = Createddatacontainer.DataContainerInfo,
                    Online                 = true
                };

                //Virtual disk create call
                taskStatus = client.VirtualDisk.Create(sourceDeviceId, virtualDiskToCreate, hdrs);

                //Asserting the task status
                Assert.NotNull(taskStatus);
                Assert.True(taskStatus.Status == AsyncTaskStatus.Completed);
                Assert.True(taskStatus.Result == AsyncTaskResult.Succeeded);

                //Virtual disk get call
                var createdVirtualDisk = client.VirtualDisk.GetByName(sourceDeviceId, virtualDiskToCreate.Name, hdrs);

                Assert.True(createdVirtualDisk != null);
                Assert.True(createdVirtualDisk.VirtualDiskInfo.Name.Equals(virtualDiskToCreate.Name));

                var volumeIds = new List <string>();
                volumeIds.Add(createdVirtualDisk.VirtualDiskInfo.InstanceId);

                var dailySchedule = new BackupScheduleBase();
                dailySchedule.BackupType                 = BackupType.CloudSnapshot;
                dailySchedule.Status                     = ScheduleStatus.Enabled;
                dailySchedule.RetentionCount             = 5;
                dailySchedule.StartTime                  = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz");
                dailySchedule.Recurrence                 = new ScheduleRecurrence();
                dailySchedule.Recurrence.RecurrenceType  = RecurrenceType.Daily;
                dailySchedule.Recurrence.RecurrenceValue = 5;

                var backupPolicyToCreate = new NewBackupPolicyConfig();
                backupPolicyToCreate.Name            = TestUtilities.GenerateName("PolicyName");
                backupPolicyToCreate.VolumeIds       = volumeIds;
                backupPolicyToCreate.BackupSchedules = new List <BackupScheduleBase>();
                backupPolicyToCreate.BackupSchedules.Add(dailySchedule);

                //BackupPolicy create call
                taskStatus = client.BackupPolicy.Create(sourceDeviceId, backupPolicyToCreate, hdrs);

                //Asserting the task status
                Assert.NotNull(taskStatus);
                Assert.True(taskStatus.Status == AsyncTaskStatus.Completed);
                Assert.True(taskStatus.Result == AsyncTaskResult.Succeeded);

                //BackupPolicy get by name call
                var createdBackupPolicy = client.BackupPolicy.GetBackupPolicyDetailsByName(sourceDeviceId, backupPolicyToCreate.Name, hdrs);

                //Assert the returned BackupPolicy object
                Assert.True(createdBackupPolicy != null);
                Assert.True(createdBackupPolicy.BackupPolicyDetails.Name.Equals(backupPolicyToCreate.Name));

                BackupNowRequest backupNowRequest = new BackupNowRequest();
                backupNowRequest.Type = BackupType.CloudSnapshot;


                //BackupSets Create call
                taskStatus = client.Backup.Create(sourceDeviceId, createdBackupPolicy.BackupPolicyDetails.InstanceId, backupNowRequest, hdrs);

                //Asserting the task status
                Assert.NotNull(taskStatus);
                Assert.True(taskStatus.Status == AsyncTaskStatus.Completed);
                Assert.True(taskStatus.Result == AsyncTaskResult.Succeeded);

                GetBackupResponse backupSetResult;

                do
                {
                    //BackupSets Get call
                    backupSetResult = client.Backup.Get(sourceDeviceId, "BackupPolicy", Boolean.FalseString, createdBackupPolicy.BackupPolicyDetails.InstanceId, null, null, null, null, hdrs);
                    TestUtilities.Wait(1000);
                } while (!backupSetResult.BackupSetsList.Any());

                var dcGroupsGetResponse = client.DeviceFailover.ListDCGroups(sourceDeviceId, hdrs);

                var dcIdList = from drDc in dcGroupsGetResponse.DataContainerGroupResponse.DCGroups[0].DCGroup
                               select drDc.InstanceId;

                var drRequest = new DeviceFailoverRequest();
                drRequest.CleanupPrimary   = false;
                drRequest.DataContainerIds = dcIdList.ToList();
                drRequest.ReturnWorkflowId = true;
                drRequest.TargetDeviceId   = targetDeviceId;

                //trigger failover call
                var jobResponse = client.DeviceFailover.Trigger(sourceDeviceId, drRequest, hdrs);

                //Asserting the task status
                Assert.NotNull(jobResponse);

                //track device job for its completion
                var  deviceJobResponse = new GetDeviceJobResponse();
                int  retryLimit        = 30;
                int  pollInterval      = 60 * 1000;
                int  retryCount        = 0;
                bool found             = false;

                do
                {
                    TestUtilities.Wait(pollInterval);
                    deviceJobResponse = client.DeviceJob.Get(null, null, null, jobResponse.JobId, null, null, 0, 1, hdrs);
                    if (deviceJobResponse != null)
                    {
                        found = true;
                    }
                    retryCount++;
                } while ((!found || deviceJobResponse.DeviceJobList[0].Status == "Running") && (retryCount < retryLimit));

                Assert.NotNull(deviceJobResponse);
                Assert.Equal(deviceJobResponse.DeviceJobList[0].Status, "Completed");
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Trigger device failover.
        /// </summary>
        /// <param name='deviceId'>
        /// Required. The device identifier
        /// </param>
        /// <param name='drRequest'>
        /// Required. The details of the device failover request.
        /// </param>
        /// <param name='customRequestHeaders'>
        /// Required. The Custom Request Headers which client must use.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// This is the Job Response for all Device Job Related Calls
        /// </returns>
        public async Task <JobResponse> TriggerAsync(string deviceId, DeviceFailoverRequest drRequest, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
        {
            // Validate
            if (deviceId == null)
            {
                throw new ArgumentNullException("deviceId");
            }
            if (drRequest == null)
            {
                throw new ArgumentNullException("drRequest");
            }
            if (drRequest.DataContainerIds == null)
            {
                throw new ArgumentNullException("drRequest.DataContainerIds");
            }
            if (drRequest.TargetDeviceId == null)
            {
                throw new ArgumentNullException("drRequest.TargetDeviceId");
            }
            if (customRequestHeaders == null)
            {
                throw new ArgumentNullException("customRequestHeaders");
            }

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

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("deviceId", deviceId);
                tracingParameters.Add("drRequest", drRequest);
                tracingParameters.Add("customRequestHeaders", customRequestHeaders);
                TracingAdapter.Enter(invocationId, this, "TriggerAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/cloudservices/";
            url = url + Uri.EscapeDataString(this.Client.CloudServiceName);
            url = url + "/resources/";
            url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            url = url + "/~/";
            url = url + "CisVault";
            url = url + "/";
            url = url + Uri.EscapeDataString(this.Client.ResourceName);
            url = url + "/api/devices/";
            url = url + Uri.EscapeDataString(deviceId);
            url = url + "/failover";
            List <string> queryParameters = new List <string>();

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

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

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

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

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/xml");
                httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language);
                httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
                httpRequest.Headers.Add("x-ms-version", "2014-01-01");

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

                // Serialize Request
                string    requestContent = null;
                XDocument requestDoc     = new XDocument();

                XElement dRRequestV2Element = new XElement(XName.Get("DRRequest_V2", "http://windowscloudbackup.com/CiS/V2013_03"));
                requestDoc.Add(dRRequestV2Element);

                XElement cleanupPrimaryElement = new XElement(XName.Get("CleanupPrimary", "http://windowscloudbackup.com/CiS/V2013_03"));
                cleanupPrimaryElement.Value = drRequest.CleanupPrimary.ToString().ToLower();
                dRRequestV2Element.Add(cleanupPrimaryElement);

                XElement dataContainerIdsSequenceElement = new XElement(XName.Get("DataContainerIds", "http://windowscloudbackup.com/CiS/V2013_03"));
                foreach (string dataContainerIdsItem in drRequest.DataContainerIds)
                {
                    XElement dataContainerIdsItemElement = new XElement(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"));
                    dataContainerIdsItemElement.Value = dataContainerIdsItem;
                    dataContainerIdsSequenceElement.Add(dataContainerIdsItemElement);
                }
                dRRequestV2Element.Add(dataContainerIdsSequenceElement);

                XElement returnWorkflowIdElement = new XElement(XName.Get("ReturnWorkflowId", "http://windowscloudbackup.com/CiS/V2013_03"));
                returnWorkflowIdElement.Value = drRequest.ReturnWorkflowId.ToString().ToLower();
                dRRequestV2Element.Add(returnWorkflowIdElement);

                XElement targetDeviceIdElement = new XElement(XName.Get("TargetDeviceId", "http://windowscloudbackup.com/CiS/V2013_03"));
                targetDeviceIdElement.Value = drRequest.TargetDeviceId;
                dRRequestV2Element.Add(targetDeviceIdElement);

                requestContent      = requestDoc.ToString();
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml; charset=utf-8");

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

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

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

                        result = new JobResponse();
                        XDocument responseDoc = XDocument.Parse(responseContent);

                        XElement stringElement = responseDoc.Element(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/"));
                        if (stringElement != null)
                        {
                            string stringInstance = stringElement.Value;
                            result.JobId = stringInstance;
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Ejemplo n.º 3
0
        public override void ExecuteCmdlet()
        {
            try
            {
                string sourceDeviceIdentifierInMessage = string.IsNullOrEmpty(DeviceName) ? DeviceId : DeviceName;
                string targetDeviceIdentifierInMessage = string.IsNullOrEmpty(TargetDeviceName) ? TargetDeviceId : TargetDeviceName;
                ConfirmAction(
                    Force.IsPresent,
                    string.Format(Resources.StartDeviceFailoverJobWarningMessage, sourceDeviceIdentifierInMessage, targetDeviceIdentifierInMessage),
                    string.Format(Resources.StartDeviceFailoverJobMessage, sourceDeviceIdentifierInMessage, targetDeviceIdentifierInMessage),
                    string.Empty,
                    () =>
                {
                    string deviceId       = null;
                    string targetDeviceId = null;

                    switch (ParameterSetName)
                    {
                    case StorSimpleCmdletParameterSet.IdentifyById:
                        deviceId       = DeviceId;
                        targetDeviceId = TargetDeviceId;
                        break;

                    case StorSimpleCmdletParameterSet.IdentifyByName:
                        deviceId       = StorSimpleClient.GetDeviceId(DeviceName);
                        targetDeviceId = StorSimpleClient.GetDeviceId(TargetDeviceName);
                        if (deviceId == null)
                        {
                            throw new ArgumentException(string.Format(Resources.NoDeviceFoundWithGivenNameInResourceMessage, StorSimpleContext.ResourceName, DeviceName));
                        }
                        if (targetDeviceId == null)
                        {
                            throw new ArgumentException(string.Format(Resources.NoDeviceFoundWithGivenNameInResourceMessage, StorSimpleContext.ResourceName, TargetDeviceName));
                        }
                        break;

                    default:
                        break;
                    }

                    if (string.IsNullOrEmpty(deviceId) || string.IsNullOrEmpty(targetDeviceId))
                    {
                        WriteObject(null);
                        return;
                    }

                    if (!ValidTargetDeviceForFailover(deviceId, targetDeviceId))
                    {
                        WriteObject(null);
                        return;
                    }

                    var vcIdList = StorSimpleClient.GetVcIdListFromVcGroups(VolumecontainerGroups);

                    var drRequest = new DeviceFailoverRequest()
                    {
                        DataContainerIds = vcIdList,
                        TargetDeviceId   = targetDeviceId,
                        CleanupPrimary   = true,
                        ReturnWorkflowId = true
                    };

                    var jobResponse = StorSimpleClient.TriggerFailover(deviceId, drRequest);
                    HandleDeviceJobResponse(jobResponse, "start");
                });
            }
            catch (Exception exception)
            {
                this.HandleException(exception);
            }
        }
 public JobResponse TriggerFailover(string deviceId, DeviceFailoverRequest drRequest)
 {
     return(GetStorSimpleClient().DeviceFailover.Trigger(deviceId, drRequest, GetCustomRequestHeaders()));
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Trigger device failover.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.StorSimple.IDeviceFailoverOperations.
 /// </param>
 /// <param name='deviceId'>
 /// Required. The device identifier
 /// </param>
 /// <param name='drRequest'>
 /// Required. The details of the device failover request.
 /// </param>
 /// <param name='customRequestHeaders'>
 /// Required. The Custom Request Headers which client must use.
 /// </param>
 /// <returns>
 /// This is the Job Response for all Device Job Related Calls
 /// </returns>
 public static JobResponse Trigger(this IDeviceFailoverOperations operations, string deviceId, DeviceFailoverRequest drRequest, CustomRequestHeaders customRequestHeaders)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((IDeviceFailoverOperations)s).TriggerAsync(deviceId, drRequest, customRequestHeaders);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Trigger device failover.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.WindowsAzure.Management.StorSimple.IDeviceFailoverOperations.
 /// </param>
 /// <param name='deviceId'>
 /// Required. The device identifier
 /// </param>
 /// <param name='drRequest'>
 /// Required. The details of the device failover request.
 /// </param>
 /// <param name='customRequestHeaders'>
 /// Required. The Custom Request Headers which client must use.
 /// </param>
 /// <returns>
 /// This is the Job Response for all Device Job Related Calls
 /// </returns>
 public static Task <JobResponse> TriggerAsync(this IDeviceFailoverOperations operations, string deviceId, DeviceFailoverRequest drRequest, CustomRequestHeaders customRequestHeaders)
 {
     return(operations.TriggerAsync(deviceId, drRequest, customRequestHeaders, CancellationToken.None));
 }