public NodeFileOperationParameters(BatchAccountContext context, string jobId, string taskId, string poolId, string computeNodeId, string nodeFileName,
            PSNodeFile nodeFile, IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, additionalBehaviors)
        {
            PSNodeFileType? nodeFileType = null;

            if (nodeFile != null)
            {
                nodeFileType = PSNodeFileType.PSNodeFileInstance;
            }
            else if (!string.IsNullOrWhiteSpace(nodeFileName))
            {
                if (!string.IsNullOrWhiteSpace(jobId) && !string.IsNullOrWhiteSpace(taskId))
                {
                    nodeFileType = PSNodeFileType.Task;
                }
                else if (!string.IsNullOrWhiteSpace(poolId) && !string.IsNullOrWhiteSpace(computeNodeId))
                {
                    nodeFileType = PSNodeFileType.ComputeNode;
                }
            }

            if (nodeFileType == null)
            {
                throw new ArgumentException(Resources.NoNodeFile);
            }
            this.NodeFileType = nodeFileType.Value;

            this.JobId = jobId;
            this.TaskId = taskId;
            this.PoolId = poolId;
            this.ComputeNodeId = computeNodeId;
            this.NodeFileName = nodeFileName;
            this.NodeFile = nodeFile;
        }
        public static void AssertBatchAccountContextsAreEqual(BatchAccountContext context1, BatchAccountContext context2)
        {
            if (context1 == null)
            {
                Assert.Null(context2);
                return;
            }
            if (context2 == null)
            {
                Assert.Null(context1);
                return;
            }

            Assert.Equal<string>(context1.AccountEndpoint, context2.AccountEndpoint);
            Assert.Equal<string>(context1.AccountName, context2.AccountName);
            Assert.Equal<string>(context1.Id, context2.Id);
            Assert.Equal<string>(context1.Location, context2.Location);
            Assert.Equal<string>(context1.PrimaryAccountKey, context2.PrimaryAccountKey);
            Assert.Equal<string>(context1.ResourceGroupName, context2.ResourceGroupName);
            Assert.Equal<string>(context1.SecondaryAccountKey, context2.SecondaryAccountKey);
            Assert.Equal<string>(context1.State, context2.State);
            Assert.Equal<string>(context1.Subscription, context2.Subscription);
            Assert.Equal<string>(context1.TagsTable, context2.TagsTable);
            Assert.Equal<string>(context1.TaskTenantUrl, context2.TaskTenantUrl);
        }
        public NewTaskParameters(BatchAccountContext context, string jobId, PSCloudJob job, string taskId, IEnumerable<BatchClientBehavior> additionalBehaviors = null) 
            : base(context, jobId, job, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(taskId))
            {
                throw new ArgumentNullException("taskId");
            }

            this.TaskId = taskId;
        }
        public ChangeOSVersionParameters(BatchAccountContext context, string poolId, PSCloudPool pool, string targetOSVersion,
            IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, poolId, pool, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(targetOSVersion))
            {
                throw new ArgumentNullException("targetOSVersion");
            }

            this.TargetOSVersion = targetOSVersion;
        }
        public NewWorkItemParameters(BatchAccountContext context, string workItemName, IEnumerable<BatchClientBehavior> additionalBehaviors = null)
            : base(context, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(workItemName))
            {
                throw new ArgumentNullException("poolName");
            }

            this.WorkItemName = workItemName;
        }
        public AutoScaleParameters(BatchAccountContext context, string poolId, PSCloudPool pool, string autoScaleFormula,
            IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, poolId, pool, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(autoScaleFormula))
            {
                throw new ArgumentNullException("autoScaleFormula");
            }

            this.AutoScaleFormula = autoScaleFormula;
        }
Exemplo n.º 7
0
        public NewPoolParameters(BatchAccountContext context, string poolId, IEnumerable<BatchClientBehavior> additionalBehaviors = null)
            : base(context, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(poolId))
            {
                throw new ArgumentNullException("poolId");
            }

            this.PoolId = poolId;
        }
        public NewJobScheduleParameters(BatchAccountContext context, string jobScheduleId, IEnumerable<BatchClientBehavior> additionalBehaviors = null)
            : base(context, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(jobScheduleId))
            {
                throw new ArgumentNullException("jobScheduleId");
            }

            this.JobScheduleId = jobScheduleId;
        }
        public NewBulkTaskParameters(BatchAccountContext context, string jobId, PSCloudJob job, PSCloudTask[] tasks, IEnumerable<BatchClientBehavior> additionalBehaviors = null)
            : base(context, jobId, job, additionalBehaviors)
        {
            if (tasks == null)
            {
                throw new ArgumentNullException("taskCollection");
            }

            this.Tasks = tasks;
        }
        protected BatchClientParametersBase(BatchAccountContext context, IEnumerable<BatchClientBehavior> additionalBehaviors = null)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            this.Context = context;
            this.AdditionalBehaviors = additionalBehaviors;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Gets all pools lifetime summary statistics
        /// </summary>
        /// <param name="context">The account to use.</param>
        /// <param name="additionBehaviors">Additional client behaviors to perform.</param>
        public PSPoolStatistics GetAllPoolsLifetimeStatistics(BatchAccountContext context, IEnumerable<BatchClientBehavior> additionBehaviors = null)
        {
            PoolOperations poolOperations = context.BatchOMClient.PoolOperations;

            WriteVerbose(string.Format(Resources.GetAllPoolsLifetimeStatistics));

            PoolStatistics poolStatistics = poolOperations.GetAllPoolsLifetimeStatistics(additionBehaviors);
            PSPoolStatistics psPoolStatistics = new PSPoolStatistics(poolStatistics);
            return psPoolStatistics;
        }
        public WorkItemOperationParameters(BatchAccountContext context, string workItemName, PSCloudWorkItem workItem,
            IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(workItemName) && workItem == null)
            {
                throw new ArgumentNullException(Resources.NoWorkItem);
            }

            this.WorkItemName = workItemName;
            this.WorkItem = workItem;
        }
        public NewCertificateParameters(BatchAccountContext context, string filePath, byte[] rawData,
            IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(filePath) && rawData == null)
            {
                throw new ArgumentException(Resources.NoCertificateData);
            }

            this.FilePath = filePath;
            this.RawData = rawData;
        }
        public PoolOperationParameters(BatchAccountContext context, string poolName, PSCloudPool pool,
            IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(poolName) && pool == null)
            {
                throw new ArgumentNullException(Resources.NoPool);
            }

            this.PoolName = poolName;
            this.Pool = pool;
        }
        public JobOperationParameters(BatchAccountContext context, string jobId, PSCloudJob job,
            IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(jobId) && job == null)
            {
                throw new ArgumentNullException(Resources.NoJob);
            }

            this.JobId = jobId;
            this.Job = job;
        }
        public DownloadRemoteDesktopProtocolFileOptions(BatchAccountContext context, string poolId, string computeNodeId, PSComputeNode computeNode, string destinationPath,
            Stream stream, IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, poolId, computeNodeId, computeNode, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(destinationPath) && stream == null)
            {
                throw new ArgumentNullException(Resources.NoDownloadDestination);
            }

            this.DestinationPath = destinationPath;
            this.Stream = stream;
        }
        public DownloadVMFileOptions(BatchAccountContext context, string poolName, string vmName, string vmFileName, PSVMFile vmFile, string destinationPath, 
            Stream stream, IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, poolName, vmName, vmFileName, vmFile, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(destinationPath) && stream == null)
            {
                throw new ArgumentNullException(Resources.NoDownloadDestination);
            }

            this.DestinationPath = destinationPath;
            this.Stream = stream;
        }
        public RemoveComputeNodeParameters(BatchAccountContext context, string poolId, string[] computeNodeIds, PSComputeNode computeNode,
            IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, additionalBehaviors)
        {
            if ((string.IsNullOrWhiteSpace(poolId) || computeNodeIds == null) && computeNode == null)
            {
                throw new ArgumentNullException(Resources.NoComputeNode);
            }

            this.PoolId = poolId;
            this.ComputeNodeIds = computeNodeIds;
            this.ComputeNode = computeNode;
        }
        public VMUserOperationParameters(BatchAccountContext context, string poolName, string vmName, string vmUserName,
            IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(poolName) || string.IsNullOrWhiteSpace(vmName) || string.IsNullOrWhiteSpace(vmUserName))
            {
                throw new ArgumentNullException(Resources.NoVMUser);
            }

            this.PoolName = poolName;
            this.VMName = vmName;
            this.VMUserName = vmUserName;
        }
        public TaskOperationParameters(BatchAccountContext context, string jobId, string taskId, PSCloudTask task,
            IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, additionalBehaviors)
        {
            if ((string.IsNullOrWhiteSpace(jobId) || string.IsNullOrWhiteSpace(taskId)) && task == null)
            {
                throw new ArgumentNullException(Resources.NoTask);
            }

            this.JobId = jobId;
            this.TaskId = taskId;
            this.Task = task;
        }
        public DownloadNodeFileOptions(BatchAccountContext context, string jobId, string taskId, string poolId, string computeNodeId, string nodeFileName,
            PSNodeFile nodeFile, string destinationPath, Stream stream, IEnumerable<BatchClientBehavior> additionalBehaviors = null)
            : base(context, jobId, taskId, poolId, computeNodeId, nodeFileName, nodeFile, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(destinationPath) && stream == null)
            {
                throw new ArgumentNullException(Resources.NoDownloadDestination);
            }

            this.DestinationPath = destinationPath;
            this.Stream = stream;
        }
        public ComputeNodeUserOperationParameters(BatchAccountContext context, string poolId, string computeNodeId, string computeNodeUserName,
            IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(poolId) || string.IsNullOrWhiteSpace(computeNodeId) || string.IsNullOrWhiteSpace(computeNodeUserName))
            {
                throw new ArgumentNullException(Resources.NoComputeNodeUser);
            }

            this.PoolId = poolId;
            this.ComputeNodeId = computeNodeId;
            this.ComputeNodeUserName = computeNodeUserName;
        }
        public ScenarioTestContext(BatchAccountContext context) : base()
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // Only set the properties needed for interacting with the Batch service.
            this.AccountName = context.AccountName;
            this.PrimaryAccountKey = context.PrimaryAccountKey;
            this.SecondaryAccountKey = context.SecondaryAccountKey;
            this.TaskTenantUrl = context.TaskTenantUrl;
        }
        public TaskFileOperationParameters(BatchAccountContext context, string workItemName, string jobName, string taskName, string taskFileName,
            PSTaskFile taskFile, IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, additionalBehaviors)
        {
            if ((string.IsNullOrWhiteSpace(workItemName) || string.IsNullOrWhiteSpace(jobName) || string.IsNullOrWhiteSpace(taskName) || 
                string.IsNullOrWhiteSpace(taskFileName)) && taskFile == null)
            {
                throw new ArgumentNullException(Resources.NoTaskFile);
            }

            this.WorkItemName = workItemName;
            this.JobName = jobName;
            this.TaskName = taskName;
            this.TaskFileName = taskFileName;
            this.TaskFile = taskFile;
        }
        public CertificateOperationParameters(BatchAccountContext context, string thumbprintAlgorithm, string thumbprint,
            IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, additionalBehaviors)
        {
            if (string.IsNullOrWhiteSpace(thumbprintAlgorithm))
            {
                throw new ArgumentNullException("thumbprintAlgorithm");
            }

            if (string.IsNullOrWhiteSpace(thumbprint))
            {
                throw new ArgumentNullException("thumbprint");
            }

            this.ThumbprintAlgorithm = thumbprintAlgorithm;
            this.Thumbprint = thumbprint;
        }
Exemplo n.º 26
0
        public ListNodeFileOptions(BatchAccountContext context, string jobId, string taskId, PSCloudTask task, string poolId, string computeNodeId, PSComputeNode computeNode,
            IEnumerable<BatchClientBehavior> additionalBehaviors = null) : base(context, additionalBehaviors)
        {
            if ((!string.IsNullOrWhiteSpace(jobId) && !string.IsNullOrWhiteSpace(taskId)) || task != null)
            {
                this.NodeFileType = PSNodeFileType.Task;
            }
            else if ((!string.IsNullOrWhiteSpace(poolId) && !string.IsNullOrWhiteSpace(computeNodeId)) || computeNode != null)
            {
                this.NodeFileType = PSNodeFileType.ComputeNode;
            }
            else
            {
                throw new ArgumentException(Resources.NoNodeFileParent);
            }

            this.JobId = jobId;
            this.TaskId = taskId;
            this.Task = task;
            this.PoolId = poolId;
            this.ComputeNodeId = computeNodeId;
            this.ComputeNode = computeNode;
        }
        /// <summary>
        /// Terminates the specified job schedule.
        /// </summary>
        /// <param name="context">The account to use.</param>
        /// <param name="jobScheduleId">The id of the job schedule to terminate.</param>
        /// <param name="additionBehaviors">Additional client behaviors to perform.</param>
        public void TerminateJobSchedule(BatchAccountContext context, string jobScheduleId, IEnumerable<BatchClientBehavior> additionBehaviors = null)
        {
            if (string.IsNullOrWhiteSpace(jobScheduleId))
            {
                throw new ArgumentNullException("jobScheduleId");
            }

            WriteVerbose(string.Format(Resources.TerminateJobSchedule, jobScheduleId));

            JobScheduleOperations jobScheduleOperations = context.BatchOMClient.JobScheduleOperations;
            jobScheduleOperations.TerminateJobSchedule(jobScheduleId, additionBehaviors);
        }
Exemplo n.º 28
0
 public PoolResizeParameters(BatchAccountContext context, string poolId, PSCloudPool pool, IEnumerable <BatchClientBehavior> additionalBehaviors = null)
     : base(context, poolId, pool, additionalBehaviors)
 {
 }
Exemplo n.º 29
0
        public void NewBatchCertificateRequestBodyTest()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

            X509Certificate2 cert = new X509Certificate2(BatchTestHelpers.TestCertificateFileName);
            string           certDataBase64String = Convert.ToBase64String(cert.RawData);

            CertificateAddParameter requestParameters = null;

            // Don't go to the service on an Add Certificate call
            RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
            {
                CertificateAddBatchRequest request = (CertificateAddBatchRequest)baseRequest;

                request.ServiceRequestFunc = (cancellationToken) =>
                {
                    requestParameters = request.Parameters;

                    var response = new AzureOperationHeaderResponse <CertificateAddHeaders>();
                    Task <AzureOperationHeaderResponse <CertificateAddHeaders> > task = Task.FromResult(response);
                    return(task);
                };
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            // Verify that when just the raw data is specified, the request body matches expectations
            cmdlet.RawData = cert.RawData;
            cmdlet.ExecuteCmdlet();
            Assert.Equal(CertificateFormat.Cer, requestParameters.CertificateFormat);
            Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm);
            Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant());
            Assert.True(string.IsNullOrEmpty(requestParameters.Password));
            Assert.Equal(certDataBase64String, requestParameters.Data);

            // Verify that when the raw data is specified with a password, the request body matches expectations
            cmdlet.RawData  = cert.RawData;
            cmdlet.Password = BatchTestHelpers.TestCertificatePassword.ConvertToSecureString();
            cmdlet.ExecuteCmdlet();
            Assert.Equal(CertificateFormat.Pfx, requestParameters.CertificateFormat);
            Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm);
            Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant());
            Assert.Equal(BatchTestHelpers.TestCertificatePassword, requestParameters.Password);
            Assert.Equal(certDataBase64String, requestParameters.Data);

            // Verify that when just a file path is specified, the request body matches expectations
            cmdlet.RawData  = null;
            cmdlet.Password = null;
            cmdlet.FilePath = BatchTestHelpers.TestCertificateFileName;
            cmdlet.ExecuteCmdlet();
            Assert.Equal(CertificateFormat.Cer, requestParameters.CertificateFormat);
            Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm);
            Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant());
            Assert.True(string.IsNullOrEmpty(requestParameters.Password));
            Assert.Equal(certDataBase64String, requestParameters.Data);

            // Verify that when a file path is specified with a password, the request body matches expectations
            cmdlet.Password = BatchTestHelpers.TestCertificatePassword.ConvertToSecureString();
            cmdlet.ExecuteCmdlet();
            Assert.Equal(CertificateFormat.Pfx, requestParameters.CertificateFormat);
            Assert.Equal(BatchTestHelpers.TestCertificateAlgorithm, requestParameters.ThumbprintAlgorithm);
            Assert.Equal(cert.Thumbprint.ToLowerInvariant(), requestParameters.Thumbprint.ToLowerInvariant());
            Assert.Equal(BatchTestHelpers.TestCertificatePassword, requestParameters.Password);
            Assert.Equal(certDataBase64String, requestParameters.Data);
        }
        /// <summary>
        /// Commits changes to a PSCloudJobSchedule object to the Batch Service.
        /// </summary>
        /// <param name="context">The account to use.</param>
        /// <param name="jobSchedule">The PSCloudJobSchedule object representing the job schedule to update.</param>
        /// <param name="additionBehaviors">Additional client behaviors to perform.</param>
        public void UpdateJobSchedule(BatchAccountContext context, PSCloudJobSchedule jobSchedule, IEnumerable<BatchClientBehavior> additionBehaviors = null)
        {
            if (jobSchedule == null)
            {
                throw new ArgumentNullException("jobSchedule");
            }

            WriteVerbose(string.Format(Resources.UpdatingJobSchedule, jobSchedule.Id));

            Utils.Utils.BoundJobScheduleSyncCollections(jobSchedule);
            jobSchedule.omObject.Commit(additionBehaviors);
        }
        public void SetBatchPoolParametersGetPassedToRequestTest()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

            cmdlet.Pool = new PSCloudPool(BatchTestHelpers.CreateFakeBoundPool(context));

            // Update the pool
            cmdlet.Pool.StartTask             = new PSStartTask("cmd /c echo start task");
            cmdlet.Pool.CertificateReferences = new List <PSCertificateReference>()
            {
                new PSCertificateReference()
                {
                    StoreLocation       = Azure.Batch.Common.CertStoreLocation.LocalMachine,
                    Thumbprint          = "thumbprint",
                    ThumbprintAlgorithm = "sha1",
                    StoreName           = "My",
                    Visibility          = Azure.Batch.Common.CertificateVisibility.StartTask
                }
            };
            cmdlet.Pool.ApplicationPackageReferences = new List <PSApplicationPackageReference>()
            {
                new PSApplicationPackageReference()
                {
                    ApplicationId = "myApp",
                    Version       = "1.0"
                }
            };
            cmdlet.Pool.Metadata = new Dictionary <string, string>
            {
                { "meta1", "value1" }
            };

            PoolUpdatePropertiesParameter requestParameters = null;

            // Store the request parameters
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                PoolUpdatePropertiesParameter,
                PoolUpdatePropertiesOptions,
                AzureOperationHeaderResponse <PoolUpdatePropertiesHeaders> >(requestAction: (r) =>
            {
                requestParameters = r.Parameters;
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };
            cmdlet.ExecuteCmdlet();

            // Verify the request parameters match the cmdlet parameters
            Assert.Equal(cmdlet.Pool.StartTask.CommandLine, requestParameters.StartTask.CommandLine);
            Assert.Equal(cmdlet.Pool.CertificateReferences.Count, requestParameters.CertificateReferences.Count);
            Assert.Equal(cmdlet.Pool.CertificateReferences[0].StoreName, requestParameters.CertificateReferences[0].StoreName);
            Assert.Equal(cmdlet.Pool.CertificateReferences[0].Thumbprint, requestParameters.CertificateReferences[0].Thumbprint);
            Assert.Equal(cmdlet.Pool.CertificateReferences[0].ThumbprintAlgorithm, requestParameters.CertificateReferences[0].ThumbprintAlgorithm);
            Assert.Equal(cmdlet.Pool.ApplicationPackageReferences.Count, requestParameters.ApplicationPackageReferences.Count);
            Assert.Equal(cmdlet.Pool.ApplicationPackageReferences[0].ApplicationId, requestParameters.ApplicationPackageReferences[0].ApplicationId);
            Assert.Equal(cmdlet.Pool.ApplicationPackageReferences[0].Version, requestParameters.ApplicationPackageReferences[0].Version);
            Assert.Equal(cmdlet.Pool.Metadata.Count, requestParameters.Metadata.Count);
            Assert.Contains(
                requestParameters.Metadata,
                metadata => metadata.Name == "meta1" && metadata.Value == cmdlet.Pool.Metadata["meta1"].ToString());
        }
        public void SetBatchJobScheduleParametersGetPassedToRequestTest()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

            cmdlet.JobSchedule = new PSCloudJobSchedule(BatchTestHelpers.CreateFakeBoundJobSchedule(context));

            // Make changes to the job schedule
            PSJobSpecification jobSpec = new PSJobSpecification()
            {
                DisplayName = "job display name",
                CommonEnvironmentSettings = new Dictionary <string, string>
                {
                    { "common1", "val1" },
                    { "common2", "val2" }
                },
                JobManagerTask     = new PSJobManagerTask("job manager", "cmd /c echo job manager"),
                JobPreparationTask = new PSJobPreparationTask("cmd /c echo job prep"),
                JobReleaseTask     = new PSJobReleaseTask("cmd /c echo job release"),
                PoolInformation    = new PSPoolInformation()
                {
                    PoolId = "myPool"
                }
            };

            cmdlet.JobSchedule.JobSpecification = jobSpec;

            PSSchedule schedule = new PSSchedule()
            {
                DoNotRunAfter      = DateTime.Now.AddYears(1),
                DoNotRunUntil      = DateTime.Now.AddDays(1),
                RecurrenceInterval = TimeSpan.FromDays(1),
                StartWindow        = TimeSpan.FromHours(1)
            };

            cmdlet.JobSchedule.Schedule = schedule;

            cmdlet.JobSchedule.Metadata = new Dictionary <string, string>
            {
                { "metadata1", "value1" }
            };

            // Store the request parameters
            JobScheduleUpdateParameter requestParameters = null;
            RequestInterceptor         interceptor       = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                JobScheduleUpdateParameter,
                JobScheduleUpdateOptions,
                AzureOperationHeaderResponse <JobScheduleUpdateHeaders> >(requestAction: (r) =>
            {
                requestParameters = r.Parameters;
            });

            cmdlet.AdditionalBehaviors = new BatchClientBehavior[] { interceptor };
            cmdlet.ExecuteCmdlet();

            // Verify that the request parameters contain the updated properties
            Assert.Equal(jobSpec.CommonEnvironmentSettings.Count, requestParameters.JobSpecification.CommonEnvironmentSettings.Count);
            Assert.Contains(
                requestParameters.JobSpecification.CommonEnvironmentSettings,
                setting => setting.Name == "common1" && setting.Value == jobSpec.CommonEnvironmentSettings["common1"].ToString());
            Assert.Contains(
                requestParameters.JobSpecification.CommonEnvironmentSettings,
                setting => setting.Name == "common2" && setting.Value == jobSpec.CommonEnvironmentSettings["common2"].ToString());
            Assert.Equal(jobSpec.JobManagerTask.Id, requestParameters.JobSpecification.JobManagerTask.Id);
            Assert.Equal(jobSpec.JobPreparationTask.CommandLine, requestParameters.JobSpecification.JobPreparationTask.CommandLine);
            Assert.Equal(jobSpec.JobReleaseTask.CommandLine, requestParameters.JobSpecification.JobReleaseTask.CommandLine);
            Assert.Equal(jobSpec.PoolInformation.PoolId, requestParameters.JobSpecification.PoolInfo.PoolId);
            Assert.Equal(schedule.DoNotRunAfter, requestParameters.Schedule.DoNotRunAfter);
            Assert.Equal(schedule.DoNotRunUntil, requestParameters.Schedule.DoNotRunUntil);
            Assert.Equal(schedule.RecurrenceInterval, requestParameters.Schedule.RecurrenceInterval);
            Assert.Equal(schedule.StartWindow, requestParameters.Schedule.StartWindow);
            Assert.Equal(cmdlet.JobSchedule.Metadata.Count, requestParameters.Metadata.Count);
            Assert.Contains(
                requestParameters.Metadata,
                metadata => metadata.Name == "metadata1" && metadata.Value == cmdlet.JobSchedule.Metadata["metadata1"].ToString());
        }
        public void WhenGetBatchPoolNodeCountsCommandIsCalledWithoutFilter_ShouldReturnAllPools()
        {
            // Setup cmdlet to get a pool by id
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            var poolNodeCounts1 = new ProxyModels.PoolNodeCounts()
            {
                PoolId    = "Pool1",
                Dedicated = new ProxyModels.NodeCounts(
                    creating: 1,
                    idle: 2,
                    offline: 3,
                    preempted: 4,
                    rebooting: 5,
                    reimaging: 6,
                    running: 7,
                    starting: 8,
                    startTaskFailed: 9,
                    leavingPool: 10,
                    unknown: 11,
                    unusable: 12,
                    waitingForStartTask: 13,
                    total: 91), // Total
                LowPriority = new ProxyModels.NodeCounts(
                    creating: 1,
                    idle: 2,
                    offline: 3,
                    preempted: 4,
                    rebooting: 5,
                    reimaging: 6,
                    running: 7,
                    starting: 8,
                    startTaskFailed: 9,
                    leavingPool: 10,
                    unknown: 11,
                    unusable: 12,
                    waitingForStartTask: 13,
                    total: 91), // Total
            };

            var poolNodeCounts2 = new ProxyModels.PoolNodeCounts()
            {
                PoolId    = "Pool2",
                Dedicated = new ProxyModels.NodeCounts(
                    creating: 11,
                    idle: 12,
                    offline: 13,
                    preempted: 14,
                    rebooting: 15,
                    reimaging: 16,
                    running: 17,
                    starting: 18,
                    startTaskFailed: 19,
                    leavingPool: 20,
                    unknown: 21,
                    unusable: 22,
                    waitingForStartTask: 23,
                    total: 221), // Total
                LowPriority = new ProxyModels.NodeCounts(
                    creating: 11,
                    idle: 12,
                    offline: 13,
                    preempted: 14,
                    rebooting: 15,
                    reimaging: 16,
                    running: 17,
                    starting: 18,
                    startTaskFailed: 19,
                    leavingPool: 20,
                    unknown: 21,
                    unusable: 22,
                    waitingForStartTask: 23,
                    total: 221), // Total
            };

            // Simulate node state counts for two pools are returned
            var poolsNodeCounts = new List <ProxyModels.PoolNodeCounts>()
            {
                poolNodeCounts1,
                poolNodeCounts2
            };

            // Build a PoolNodeCounts instead of querying the service on a Get PoolNodeCounts call
            AzureOperationResponse <IPage <ProxyModels.PoolNodeCounts>, ProxyModels.AccountListPoolNodeCountsHeaders> response =
                BatchTestHelpers.CreatePoolNodeCountsGetResponse(poolsNodeCounts);
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                ProxyModels.AccountListPoolNodeCountsOptions,
                AzureOperationResponse <IPage <ProxyModels.PoolNodeCounts>, ProxyModels.AccountListPoolNodeCountsHeaders> >(response);

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            List <PSPoolNodeCounts> psPoolsNodeCounts = new List <PSPoolNodeCounts>();

            commandRuntimeMock.Setup(r =>
                                     r.WriteObject(It.IsAny <PSPoolNodeCounts>()))
            .Callback <object>(p => psPoolsNodeCounts.Add((PSPoolNodeCounts)p));

            cmdlet.ExecuteCmdlet();

            var psPoolNodeCounts1 = psPoolsNodeCounts.FirstOrDefault(c => c.PoolId == "Pool1");

            var psPoolNodeCounts2 = psPoolsNodeCounts.FirstOrDefault(c => c.PoolId == "Pool2");

            Assert.NotNull(psPoolNodeCounts1);
            Assert.NotNull(psPoolNodeCounts2);

            var comparer = new PoolNodeCountsObjectComparer();

            Assert.True(comparer.AreEqual(poolNodeCounts1, psPoolNodeCounts1));
            Assert.True(comparer.AreEqual(poolNodeCounts2, psPoolNodeCounts2));
        }
        public void WhenGettingATaskFromTheService_ExitConditionsAreMapped()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.Id           = "task-1";
            cmdlet.JobId        = "job-1";
            cmdlet.Filter       = null;

            // Build a CloudTask instead of querying the service on a Get CloudTask call
            ProxyModels.ExitOptions none = new ProxyModels.ExitOptions {
                JobAction = ProxyModels.JobAction.None
            };
            ProxyModels.ExitOptions terminate = new ProxyModels.ExitOptions {
                JobAction = ProxyModels.JobAction.Terminate
            };

            ProxyModels.CloudTask cloudTask = new ProxyModels.CloudTask
            {
                Id             = "task-1",
                ExitConditions = new ProxyModels.ExitConditions
                {
                    ExitCodeRanges     = new[] { new ProxyModels.ExitCodeRangeMapping(2, 5, none) },
                    ExitCodes          = new[] { new ProxyModels.ExitCodeMapping(4, terminate) },
                    PreProcessingError = terminate,
                    FileUploadError    = none,
                    DefaultProperty    = none,
                }
            };

            AzureOperationResponse <ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> response = BatchTestHelpers.CreateCloudTaskGetResponse(cloudTask);

            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <ProxyModels.TaskGetOptions,
                                                                                                    AzureOperationResponse <ProxyModels.CloudTask, ProxyModels.TaskGetHeaders> >(response);

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            var pipeline = new List <PSCloudTask>();

            commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCloudTask>())).Callback <object>(t => pipeline.Add((PSCloudTask)t));

            cmdlet.ExecuteCmdlet();

            // Verify that the cmdlet wrote the task returned from the OM to the pipeline
            Assert.Equal(1, pipeline.Count);
            Assert.Equal(cmdlet.Id, pipeline[0].Id);

            PSExitConditions psExitConditions = pipeline[0].ExitConditions;

            Assert.Equal(psExitConditions.Default.JobAction, JobAction.None);
            Assert.Equal(psExitConditions.ExitCodeRanges.First().ExitOptions.JobAction, JobAction.None);
            Assert.Equal(psExitConditions.PreProcessingError.JobAction, JobAction.Terminate);
            Assert.Equal(psExitConditions.FileUploadError.JobAction, JobAction.None);

            Assert.Equal(4, psExitConditions.ExitCodes.First().Code);
            Assert.Equal(JobAction.Terminate, psExitConditions.ExitCodes.First().ExitOptions.JobAction);
            Assert.Equal(2, psExitConditions.ExitCodeRanges.First().Start);
            Assert.Equal(5, psExitConditions.ExitCodeRanges.First().End);
            Assert.Equal(JobAction.None, psExitConditions.ExitCodeRanges.First().ExitOptions.JobAction);
        }
        /// <summary>
        /// Uploads an application package to Storage
        /// </summary>
        public static ApplicationPackage CreateApplicationPackage(BatchController controller, BatchAccountContext context, string applicationName, string version, string filePath)
        {
            ApplicationPackage applicationPackage = null;

            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                applicationPackage = controller.BatchManagementClient.ApplicationPackage.Create(
                    context.ResourceGroupName,
                    context.AccountName,
                    applicationName,
                    version);

                CloudBlockBlob blob = new CloudBlockBlob(new Uri(applicationPackage.StorageUrl));
#if NETSTANDARD
                Task.Run(() => blob.UploadFromFileAsync(filePath)).Wait();
#else
                blob.UploadFromFile(filePath, FileMode.Open);
#endif
            }

            return(applicationPackage);
        }
Exemplo n.º 36
0
 public ListTaskOptions(BatchAccountContext context, string jobId, PSCloudJob job, IEnumerable <BatchClientBehavior> additionalBehaviors = null)
     : base(context, jobId, job, additionalBehaviors)
 {
 }
Exemplo n.º 37
0
        /// <summary>
        /// Deletes a job used in a Scenario test.
        /// </summary>
        public static void DeleteJob(BatchController controller, BatchAccountContext context, string jobId)
        {
            BatchClient client = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            client.DeleteJob(context, jobId);
        }
Exemplo n.º 38
0
        /// <summary>
        /// Deletes a certificate.
        /// </summary>
        public static void WaitForCertificateToFailDeletion(BatchController controller, BatchAccountContext context, string thumbprintAlgorithm, string thumbprint)
        {
            BatchClient client = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            ListCertificateOptions parameters = new ListCertificateOptions(context)
            {
                ThumbprintAlgorithm = BatchTestHelpers.TestCertificateAlgorithm,
                Thumbprint          = thumbprint
            };

            PSCertificate cert = client.ListCertificates(parameters).First();

            DateTime timeout = DateTime.Now.AddMinutes(2);

            while (cert.State != CertificateState.DeleteFailed)
            {
                if (DateTime.Now > timeout)
                {
                    throw new TimeoutException("Timed out waiting for failed certificate deletion");
                }
                Sleep(10000);
                cert = client.ListCertificates(parameters).First();
            }
        }
Exemplo n.º 39
0
        public void ExitConditionsAreSentToService()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

            TaskAddParameter requestParameters = null;

            RequestInterceptor interceptor = new RequestInterceptor((baseRequest) =>
            {
                TaskAddBatchRequest request = (TaskAddBatchRequest)baseRequest;

                request.ServiceRequestFunc = (cancellationToken) =>
                {
                    requestParameters = request.Parameters;

                    var response = new AzureOperationHeaderResponse <TaskAddHeaders>();
                    Task <AzureOperationHeaderResponse <TaskAddHeaders> > task = Task.FromResult(response);
                    return(task);
                };
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior> {
                interceptor
            };

            var none = new PSExitOptions {
                omObject = new Azure.Batch.ExitOptions {
                    JobAction = Azure.Batch.Common.JobAction.None
                }
            };
            var terminate = new PSExitOptions {
                omObject = new Azure.Batch.ExitOptions {
                    JobAction = Azure.Batch.Common.JobAction.Terminate
                }
            };

            cmdlet.ExitConditions = new PSExitConditions
            {
                ExitCodes = new List <PSExitCodeMapping> {
                    new PSExitCodeMapping(0, none)
                },
                SchedulingError = terminate,
                ExitCodeRanges  = new List <PSExitCodeRangeMapping> {
                    new PSExitCodeRangeMapping(1, 5, terminate)
                },
                Default = none,
            };

            cmdlet.JobId = "job-Id";
            cmdlet.Id    = "task-id";
            cmdlet.ExecuteCmdlet();

            var exitConditions = requestParameters.ExitConditions;

            Assert.Equal(1, exitConditions.ExitCodeRanges.First().Start);
            Assert.Equal(5, exitConditions.ExitCodeRanges.First().End);
            Assert.Equal(ProxyModels.JobAction.Terminate, exitConditions.ExitCodeRanges.First().ExitOptions.JobAction);
            Assert.Equal(ProxyModels.JobAction.None, exitConditions.ExitCodes.First().ExitOptions.JobAction);
            Assert.Equal(ProxyModels.JobAction.Terminate, exitConditions.SchedulingError.JobAction);
            Assert.Equal(ProxyModels.JobAction.None, exitConditions.DefaultProperty.JobAction);
        }
Exemplo n.º 40
0
        public void NewBatchJobPoolUserAccountsGetPassedToRequest()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

            cmdlet.Id = "testJob";

            PSUserAccount adminUser    = new PSUserAccount("admin", "password1", Azure.Batch.Common.ElevationLevel.Admin);
            PSUserAccount nonAdminUser = new PSUserAccount("user2", "password2", Azure.Batch.Common.ElevationLevel.NonAdmin);
            PSUserAccount sshUser      = new PSUserAccount("user3", "password3", Azure.Batch.Common.ElevationLevel.Admin, new PSLinuxUserConfiguration(uid: 1, gid: 2, sshPrivateKey: "my ssh key"));

            cmdlet.PoolInformation = new PSPoolInformation
            {
                AutoPoolSpecification = new PSAutoPoolSpecification
                {
                    AutoPoolIdPrefix   = "prefix",
                    PoolLifetimeOption = Azure.Batch.Common.PoolLifetimeOption.Job,
                    PoolSpecification  = new PSPoolSpecification
                    {
                        CloudServiceConfiguration = new PSCloudServiceConfiguration("4", "*"),
                        UserAccounts = new List <PSUserAccount>()
                        {
                            adminUser, nonAdminUser, sshUser
                        }
                    }
                }
            };

            JobAddParameter requestParameters = null;

            // Store the request parameters
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                JobAddParameter,
                JobAddOptions,
                AzureOperationHeaderResponse <JobAddHeaders> >(requestAction: (r) =>
            {
                requestParameters = r.Parameters;
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };
            cmdlet.ExecuteCmdlet();

            // Verify the request parameters match the cmdlet parameters
            Assert.Equal(3, cmdlet.PoolInformation.AutoPoolSpecification.PoolSpecification.UserAccounts.Count);
            Assert.Equal(adminUser.Name, requestParameters.PoolInfo.AutoPoolSpecification.Pool.UserAccounts[0].Name);
            Assert.Equal(adminUser.Password, requestParameters.PoolInfo.AutoPoolSpecification.Pool.UserAccounts[0].Password);
            Assert.Equal(adminUser.ElevationLevel.ToString().ToLowerInvariant(),
                         requestParameters.PoolInfo.AutoPoolSpecification.Pool.UserAccounts[0].ElevationLevel.ToString().ToLowerInvariant());
            Assert.Equal(nonAdminUser.Name, requestParameters.PoolInfo.AutoPoolSpecification.Pool.UserAccounts[1].Name);
            Assert.Equal(nonAdminUser.Password, requestParameters.PoolInfo.AutoPoolSpecification.Pool.UserAccounts[1].Password);
            Assert.Equal(nonAdminUser.ElevationLevel.ToString().ToLowerInvariant(),
                         requestParameters.PoolInfo.AutoPoolSpecification.Pool.UserAccounts[1].ElevationLevel.ToString().ToLowerInvariant());
            Assert.Equal(sshUser.Name, requestParameters.PoolInfo.AutoPoolSpecification.Pool.UserAccounts[2].Name);
            Assert.Equal(sshUser.Password, requestParameters.PoolInfo.AutoPoolSpecification.Pool.UserAccounts[2].Password);
            Assert.Equal(sshUser.ElevationLevel.ToString().ToLowerInvariant(),
                         requestParameters.PoolInfo.AutoPoolSpecification.Pool.UserAccounts[2].ElevationLevel.ToString().ToLowerInvariant());
            Assert.Equal(sshUser.LinuxUserConfiguration.Uid, requestParameters.PoolInfo.AutoPoolSpecification.Pool.UserAccounts[2].LinuxUserConfiguration.Uid);
            Assert.Equal(sshUser.LinuxUserConfiguration.Gid, requestParameters.PoolInfo.AutoPoolSpecification.Pool.UserAccounts[2].LinuxUserConfiguration.Gid);
            Assert.Equal(sshUser.LinuxUserConfiguration.SshPrivateKey, requestParameters.PoolInfo.AutoPoolSpecification.Pool.UserAccounts[2].LinuxUserConfiguration.SshPrivateKey);
        }
        public void WhenPSNodeCountsFormatObjectIsCalled_ShouldSerlializeNodeCountsToString()
        {
            const int creating            = 1;
            const int idle                = 2;
            const int offline             = 3;
            const int preempted           = 4;
            const int rebooting           = 5;
            const int reimaging           = 6;
            const int running             = 7;
            const int starting            = 8;
            const int startTaskFailed     = 9;
            const int leavingPool         = 10;
            const int unknown             = 11;
            const int unusable            = 12;
            const int waitingForStartTask = 13;
            const int total               = 91;

            var poolNodeCounts = new ProxyModels.PoolNodeCounts()
            {
                PoolId = "Pool1",
                // all non-zero properties
                Dedicated = new ProxyModels.NodeCounts(
                    creating: creating,
                    idle: idle,
                    offline: offline,
                    preempted: preempted,
                    rebooting: rebooting,
                    reimaging: reimaging,
                    running: running,
                    starting: starting,
                    startTaskFailed: startTaskFailed,
                    leavingPool: leavingPool,
                    unknown: unknown,
                    unusable: unusable,
                    waitingForStartTask: waitingForStartTask,
                    total: total), // Total
                // all zero properties
                LowPriority = new ProxyModels.NodeCounts(
                    creating: 0,
                    idle: 0,
                    offline: 0,
                    preempted: 0,
                    rebooting: 0,
                    reimaging: 0,
                    running: 0,
                    starting: 0,
                    startTaskFailed: 0,
                    leavingPool: 0,
                    unknown: 0,
                    unusable: 0,
                    waitingForStartTask: 0,
                    total: 0), // Total
            };

            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

            // Build a PoolNodeCounts instead of querying the service on a Get PoolNodeCounts call
            AzureOperationResponse <IPage <ProxyModels.PoolNodeCounts>, ProxyModels.AccountListPoolNodeCountsHeaders> response =
                BatchTestHelpers.CreatePoolNodeCountsGetResponse(new [] { poolNodeCounts });
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                ProxyModels.AccountListPoolNodeCountsOptions,
                AzureOperationResponse <IPage <ProxyModels.PoolNodeCounts>, ProxyModels.AccountListPoolNodeCountsHeaders> >(response);

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            List <PSPoolNodeCounts> psPoolsNodeCounts = new List <PSPoolNodeCounts>();

            commandRuntimeMock.Setup(r =>
                                     r.WriteObject(It.IsAny <PSPoolNodeCounts>()))
            .Callback <object>(p => psPoolsNodeCounts.Add((PSPoolNodeCounts)p));

            cmdlet.ExecuteCmdlet();

            var          str           = PSNodeCounts.FormatObject(psPoolsNodeCounts[0].Dedicated);
            const string segmentFormat = "{0}: {1}";

            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.Creating), creating), str);
            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.Idle), idle), str);
            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.Offline), offline), str);
            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.Preempted), preempted), str);
            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.Rebooting), rebooting), str);
            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.Reimaging), reimaging), str);
            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.Running), running), str);
            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.Starting), starting), str);
            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.StartTaskFailed), startTaskFailed), str);
            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.LeavingPool), leavingPool), str);
            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.Unknown), unknown), str);
            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.Unusable), unusable), str);
            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.WaitingForStartTask), waitingForStartTask), str);
            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.Total), total), str);
            Assert.EndsWith(string.Format(segmentFormat, nameof(PSNodeCounts.Total), total), str);

            str = PSNodeCounts.FormatObject(psPoolsNodeCounts[0].LowPriority);

            Assert.Contains(string.Format(segmentFormat, nameof(PSNodeCounts.Total), 0), str);
        }
 public ReimageComputeNodeParameters(BatchAccountContext context, string poolId, string computeNodeId, PSComputeNode computeNode,
                                     IEnumerable <BatchClientBehavior> additionalBehaviors = null)
     : base(context, poolId, computeNodeId, computeNode, additionalBehaviors)
 {
 }
Exemplo n.º 43
0
        public void NewBatchPoolParametersGetPassedToRequestTest()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

            cmdlet.Id = "testPool";
            cmdlet.ApplicationLicenses = new List <string>()
            {
                "foo", "bar"
            };
            cmdlet.CertificateReferences = new PSCertificateReference[]
            {
                new PSCertificateReference()
                {
                    StoreLocation       = Azure.Batch.Common.CertStoreLocation.LocalMachine,
                    Thumbprint          = "thumbprint",
                    ThumbprintAlgorithm = "sha1",
                    StoreName           = "My",
                    Visibility          = Azure.Batch.Common.CertificateVisibility.StartTask
                }
            };
            cmdlet.CloudServiceConfiguration = new PSCloudServiceConfiguration("4", "*");
            cmdlet.DisplayName = "display name";
            cmdlet.InterComputeNodeCommunicationEnabled = true;
            cmdlet.MaxTasksPerComputeNode = 4;
            cmdlet.Metadata = new Dictionary <string, string>();
            cmdlet.Metadata.Add("meta1", "value1");
            cmdlet.ResizeTimeout = TimeSpan.FromMinutes(20);
            cmdlet.StartTask     = new PSStartTask("cmd /c echo start task");
            cmdlet.TargetDedicatedComputeNodes   = 3;
            cmdlet.TargetLowPriorityComputeNodes = 2;
            cmdlet.TaskSchedulingPolicy          = new PSTaskSchedulingPolicy(Azure.Batch.Common.ComputeNodeFillType.Spread);
            cmdlet.VirtualMachineConfiguration   = new PSVirtualMachineConfiguration(new PSImageReference("offer", "publisher", "sku"), "node agent");
            cmdlet.VirtualMachineSize            = "small";
            cmdlet.MountConfiguration            = new[] { new PSMountConfiguration(new PSAzureBlobFileSystemConfiguration("foo", "bar", "baz", AzureStorageAuthenticationKey.FromAccountKey("abc"))) };

            PoolAddParameter requestParameters = null;

            // Store the request parameters
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                PoolAddParameter,
                PoolAddOptions,
                AzureOperationHeaderResponse <PoolAddHeaders> >(requestAction: (r) =>
            {
                requestParameters = r.Parameters;
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };
            commandRuntimeMock.Setup(cr => cr.ShouldProcess(It.IsAny <string>())).Returns(true);
            cmdlet.ExecuteCmdlet();

            // Verify the request parameters match the cmdlet parameters
            Assert.Equal(cmdlet.ApplicationLicenses[0], requestParameters.ApplicationLicenses[0]);
            Assert.Equal(cmdlet.ApplicationLicenses[1], requestParameters.ApplicationLicenses[1]);
            Assert.Equal(cmdlet.CertificateReferences.Length, requestParameters.CertificateReferences.Count);
            Assert.Equal(cmdlet.CertificateReferences[0].StoreName, requestParameters.CertificateReferences[0].StoreName);
            Assert.Equal(cmdlet.CertificateReferences[0].Thumbprint, requestParameters.CertificateReferences[0].Thumbprint);
            Assert.Equal(cmdlet.CertificateReferences[0].ThumbprintAlgorithm, requestParameters.CertificateReferences[0].ThumbprintAlgorithm);
            Assert.Equal(cmdlet.CloudServiceConfiguration.OSFamily, requestParameters.CloudServiceConfiguration.OsFamily);
            Assert.Equal(cmdlet.CloudServiceConfiguration.OSVersion, requestParameters.CloudServiceConfiguration.OsVersion);
            Assert.Equal(cmdlet.DisplayName, requestParameters.DisplayName);
            Assert.Equal(cmdlet.InterComputeNodeCommunicationEnabled, requestParameters.EnableInterNodeCommunication);
            Assert.Equal(cmdlet.MaxTasksPerComputeNode, requestParameters.MaxTasksPerNode);
            Assert.Equal(cmdlet.Metadata.Count, requestParameters.Metadata.Count);
            Assert.Equal(cmdlet.Metadata["meta1"], requestParameters.Metadata[0].Value);
            Assert.Equal(cmdlet.ResizeTimeout, requestParameters.ResizeTimeout);
            Assert.Equal(cmdlet.StartTask.CommandLine, requestParameters.StartTask.CommandLine);
            Assert.Equal(cmdlet.TargetDedicatedComputeNodes, requestParameters.TargetDedicatedNodes);
            Assert.Equal(cmdlet.TargetLowPriorityComputeNodes, requestParameters.TargetLowPriorityNodes);
            Assert.Equal(cmdlet.TaskSchedulingPolicy.ComputeNodeFillType.ToString(), requestParameters.TaskSchedulingPolicy.NodeFillType.ToString());
            Assert.Equal(cmdlet.VirtualMachineConfiguration.NodeAgentSkuId, requestParameters.VirtualMachineConfiguration.NodeAgentSKUId);
            Assert.Equal(cmdlet.VirtualMachineConfiguration.ImageReference.Publisher, requestParameters.VirtualMachineConfiguration.ImageReference.Publisher);
            Assert.Equal(cmdlet.VirtualMachineConfiguration.ImageReference.Offer, requestParameters.VirtualMachineConfiguration.ImageReference.Offer);
            Assert.Equal(cmdlet.VirtualMachineConfiguration.ImageReference.Sku, requestParameters.VirtualMachineConfiguration.ImageReference.Sku);
            Assert.Equal(cmdlet.VirtualMachineSize, requestParameters.VmSize);
            Assert.Equal(cmdlet.MountConfiguration[0].AzureBlobFileSystemConfiguration.AccountName, requestParameters.MountConfiguration[0].AzureBlobFileSystemConfiguration.AccountName);
            Assert.Equal(cmdlet.MountConfiguration[0].AzureBlobFileSystemConfiguration.AccountKey, requestParameters.MountConfiguration[0].AzureBlobFileSystemConfiguration.AccountKey);
            Assert.Equal(cmdlet.MountConfiguration[0].AzureBlobFileSystemConfiguration.ContainerName, requestParameters.MountConfiguration[0].AzureBlobFileSystemConfiguration.ContainerName);
            Assert.Equal(cmdlet.MountConfiguration[0].AzureBlobFileSystemConfiguration.RelativeMountPath, requestParameters.MountConfiguration[0].AzureBlobFileSystemConfiguration.RelativeMountPath);
        }
        /// <summary>
        /// Uploads an application package to Storage
        /// </summary>
        public static AddApplicationPackageResult CreateApplicationPackage(BatchController controller, BatchAccountContext context, string applicationId, string version, string filePath)
        {
            AddApplicationPackageResult applicationPackage = null;

            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                applicationPackage = controller.BatchManagementClient.Application.AddApplicationPackage(
                    context.ResourceGroupName,
                    context.AccountName,
                    applicationId,
                    version);

                CloudBlockBlob blob = new CloudBlockBlob(new Uri(applicationPackage.StorageUrl));
                blob.UploadFromFile(filePath, FileMode.Open);
            }

            return(applicationPackage);
        }
Exemplo n.º 45
0
 public ListTaskFileOptions(BatchAccountContext context, string workItemName, string jobName, string taskName, PSCloudTask task,
                            IEnumerable <BatchClientBehavior> additionalBehaviors = null) : base(context, workItemName, jobName, taskName, task, additionalBehaviors)
 {
 }
Exemplo n.º 46
0
 /// <summary>
 /// Creates a test workitem for use in Scenario tests.
 /// </summary>
 public static void CreateTestWorkItem(BatchController controller, BatchAccountContext context, string workItemName)
 {
     CreateTestWorkItem(controller, context, workItemName, null);
 }
Exemplo n.º 47
0
        public void GetBatchJobPreparationAndReleaseTaskStatusTestMaxCountTest()
        {
            // Verify default max count
            Assert.Equal(Utils.Constants.DefaultMaxCount, cmdlet.MaxCount);

            // Setup cmdlet to list jobs without filters and a max count
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;
            cmdlet.Id           = "test";
            cmdlet.Filter       = null;
            const int maxCount = 2;

            cmdlet.MaxCount = maxCount;

            const string poolId = "Test";
            // Build some PrepAndReleaseTaskStatuses instead of querying the service on a List CloudJobs call
            var       taskExecutionInformationList = new List <ProxyModels.JobPreparationAndReleaseTaskExecutionInformation>();
            const int countReturned = 3;

            for (int i = 0; i < countReturned; i++)
            {
                var jpjrInfo = new ProxyModels.JobPreparationAndReleaseTaskExecutionInformation(
                    poolId: poolId,
                    nodeId: Guid.NewGuid().ToString(),
                    jobPreparationTaskExecutionInfo: new ProxyModels.JobPreparationTaskExecutionInformation(
                        retryCount: 0,
                        state: ProxyModels.JobPreparationTaskState.Completed,
                        startTime: DateTime.UtcNow),
                    jobReleaseTaskExecutionInfo: new ProxyModels.JobReleaseTaskExecutionInformation(
                        state: ProxyModels.JobReleaseTaskState.Completed,
                        startTime: DateTime.UtcNow));
                taskExecutionInformationList.Add(jpjrInfo);
            }

            var response = BatchTestHelpers.CreateJobPreparationAndReleaseTaskStatusListResponse(taskExecutionInformationList);
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                ProxyModels.JobListPreparationAndReleaseTaskStatusOptions,
                AzureOperationResponse <IPage <ProxyModels.JobPreparationAndReleaseTaskExecutionInformation>, ProxyModels.JobListPreparationAndReleaseTaskStatusHeaders> >(response);

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            var pipeline = new List <PSJobPreparationAndReleaseTaskExecutionInformation>();

            commandRuntimeMock.Setup(r =>
                                     r.WriteObject(It.IsAny <PSJobPreparationAndReleaseTaskExecutionInformation>()))
            .Callback <object>(j => pipeline.Add((PSJobPreparationAndReleaseTaskExecutionInformation)j));

            cmdlet.ExecuteCmdlet();

            // Verify that the max count was respected
            Assert.Equal(maxCount, pipeline.Count);

            // Verify setting max count <= 0 doesn't return nothing
            cmdlet.MaxCount = -5;
            pipeline.Clear();
            cmdlet.ExecuteCmdlet();

            Assert.Equal(countReturned, pipeline.Count);
        }
 public ListJobPreparationAndReleaseStatusOptions(BatchAccountContext context,
                                                  IEnumerable <BatchClientBehavior> additionalBehaviors = null)
     : base(context, additionalBehaviors)
 {
 }
Exemplo n.º 49
0
        /// <summary>
        /// Verifies that two BatchAccountContext objects are equal
        /// </summary>
        public static void AssertBatchAccountContextsAreEqual(BatchAccountContext context1, BatchAccountContext context2)
        {
            if (context1 == null)
            {
                Assert.Null(context2);
                return;
            }
            if (context2 == null)
            {
                Assert.Null(context1);
                return;
            }

            Assert.Equal <string>(context1.AccountEndpoint, context2.AccountEndpoint);
            Assert.Equal <string>(context1.AccountName, context2.AccountName);
            Assert.Equal <string>(context1.Id, context2.Id);
            Assert.Equal <string>(context1.Location, context2.Location);
            Assert.Equal <string>(context1.PrimaryAccountKey, context2.PrimaryAccountKey);
            Assert.Equal <string>(context1.ResourceGroupName, context2.ResourceGroupName);
            Assert.Equal <string>(context1.SecondaryAccountKey, context2.SecondaryAccountKey);
            Assert.Equal <string>(context1.State, context2.State);
            Assert.Equal <string>(context1.Subscription, context2.Subscription);
            Assert.Equal <string>(context1.TagsTable, context2.TagsTable);
            Assert.Equal <string>(context1.TaskTenantUrl, context2.TaskTenantUrl);
        }
        /// <summary>
        /// Creates a test pool for use in Scenario tests.
        /// </summary>
        public static void CreateTestPool(BatchController controller, BatchAccountContext context, string poolId, int targetDedicated)
        {
            RequestInterceptor interceptor = CreateHttpRecordingInterceptor();
            BatchClientBehavior[] behaviors = new BatchClientBehavior[] { interceptor };
            BatchClient client = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            NewPoolParameters parameters = new NewPoolParameters(context, poolId, behaviors)
            {
                VirtualMachineSize = "small",
                OSFamily = "4",
                TargetOSVersion = "*",
                TargetDedicated = targetDedicated,
            };

            client.CreatePool(parameters);
        }
        public void NewBatchJobScheduleParametersGetPassedToRequestTest()
        {
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            cmdlet.BatchContext = context;

            cmdlet.Id          = "testJobSchedule";
            cmdlet.DisplayName = "display name";
            Models.PSJobSpecification jobSpec = new Models.PSJobSpecification()
            {
                DisplayName = "job display name",
                CommonEnvironmentSettings = new Dictionary <string, string>
                {
                    { "common1", "val1" },
                    { "common2", "val2" }
                },
                JobManagerTask     = new Models.PSJobManagerTask("job manager", "cmd /c echo job manager"),
                JobPreparationTask = new Models.PSJobPreparationTask("cmd /c echo job prep"),
                JobReleaseTask     = new Models.PSJobReleaseTask("cmd /c echo job release"),
                PoolInformation    = new Models.PSPoolInformation()
                {
                    PoolId = "myPool"
                }
            };
            cmdlet.JobSpecification = jobSpec;
            Models.PSSchedule schedule = new Models.PSSchedule()
            {
                DoNotRunAfter      = DateTime.Now.AddYears(1),
                DoNotRunUntil      = DateTime.Now.AddDays(1),
                RecurrenceInterval = TimeSpan.FromDays(1),
                StartWindow        = TimeSpan.FromHours(1)
            };
            cmdlet.Schedule = schedule;
            cmdlet.Metadata = new Dictionary <string, string>();
            cmdlet.Metadata.Add("meta1", "value1");
            cmdlet.Metadata.Add("meta2", "value2");

            JobScheduleAddParameter requestParameters = null;

            // Store the request parameters
            RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                JobScheduleAddParameter,
                JobScheduleAddOptions,
                AzureOperationHeaderResponse <JobScheduleAddHeaders> >(requestAction: (r) =>
            {
                requestParameters = r.Parameters;
            });

            cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor
            };
            cmdlet.ExecuteCmdlet();

            // Verify the request parameters match the cmdlet parameters
            Assert.Equal(cmdlet.DisplayName, requestParameters.DisplayName);
            Assert.Equal(jobSpec.CommonEnvironmentSettings.Count, requestParameters.JobSpecification.CommonEnvironmentSettings.Count);
            Assert.Contains(
                requestParameters.JobSpecification.CommonEnvironmentSettings,
                setting => setting.Name == "common1" && setting.Value == jobSpec.CommonEnvironmentSettings["common1"].ToString());
            Assert.Contains(
                requestParameters.JobSpecification.CommonEnvironmentSettings,
                setting => setting.Name == "common2" && setting.Value == jobSpec.CommonEnvironmentSettings["common2"].ToString());
            Assert.Equal(jobSpec.JobManagerTask.Id, requestParameters.JobSpecification.JobManagerTask.Id);
            Assert.Equal(jobSpec.JobPreparationTask.CommandLine, requestParameters.JobSpecification.JobPreparationTask.CommandLine);
            Assert.Equal(jobSpec.JobReleaseTask.CommandLine, requestParameters.JobSpecification.JobReleaseTask.CommandLine);
            Assert.Equal(jobSpec.PoolInformation.PoolId, requestParameters.JobSpecification.PoolInfo.PoolId);
            Assert.Equal(schedule.DoNotRunAfter, requestParameters.Schedule.DoNotRunAfter);
            Assert.Equal(schedule.DoNotRunUntil, requestParameters.Schedule.DoNotRunUntil);
            Assert.Equal(schedule.RecurrenceInterval, requestParameters.Schedule.RecurrenceInterval);
            Assert.Equal(schedule.StartWindow, requestParameters.Schedule.StartWindow);
            Assert.Equal(cmdlet.Metadata.Count, requestParameters.Metadata.Count);
            Assert.Equal(cmdlet.Metadata[requestParameters.Metadata[0].Name], requestParameters.Metadata[0].Value);
            Assert.Equal(cmdlet.Metadata[requestParameters.Metadata[1].Name], requestParameters.Metadata[1].Value);
        }
        /// <summary>
        /// Deletes the specified job schedule.
        /// </summary>
        /// <param name="context">The account to use.</param>
        /// <param name="jobScheduleId">The id of the job schedule to delete.</param>
        /// <param name="additionBehaviors">Additional client behaviors to perform.</param>
        public void DeleteJobSchedule(BatchAccountContext context, string jobScheduleId, IEnumerable<BatchClientBehavior> additionBehaviors = null)
        {
            if (string.IsNullOrWhiteSpace(jobScheduleId))
            {
                throw new ArgumentNullException("jobScheduleId");
            }

            JobScheduleOperations jobScheduleOperations = context.BatchOMClient.JobScheduleOperations;
            jobScheduleOperations.DeleteJobSchedule(jobScheduleId, additionBehaviors);
        }
Exemplo n.º 53
0
        public void WhenStartBatchComputeNodeServiceLogUploadCommandIsCalledWithComputeNode_ShouldSucceed()
        {
            // First get a fake tvm
            BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys();

            getComputeNodeCommand.BatchContext = context;
            getComputeNodeCommand.PoolId       = "Pool1";
            getComputeNodeCommand.Id           = null;
            getComputeNodeCommand.Filter       = null;

            AzureOperationResponse <IPage <ProxyModels.ComputeNode>, ProxyModels.ComputeNodeListHeaders> response1 =
                BatchTestHelpers.CreateComputeNodeListResponse(new[] { "tvm1" });

            RequestInterceptor interceptor1 = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                ProxyModels.ComputeNodeListOptions,
                AzureOperationResponse <IPage <ProxyModels.ComputeNode>, ProxyModels.ComputeNodeListHeaders> >(response1);

            var computeNodes = new List <PSComputeNode>();

            commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSComputeNode>()))
            .Callback <object>(c => computeNodes.Add((PSComputeNode)c));

            getComputeNodeCommand.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor1
            };

            getComputeNodeCommand.ExecuteCmdlet();

            // test StartBatchComputeNodeServiceLogUploadCommand
            startComputeNodeServiceLogUploadCommand.BatchContext = context;
            startComputeNodeServiceLogUploadCommand.ComputeNode  = computeNodes[0];
            startComputeNodeServiceLogUploadCommand.ContainerUrl = fakeUrl;

            var utcNow = DateTime.UtcNow;

            startComputeNodeServiceLogUploadCommand.StartTime = utcNow.AddDays(-1);
            startComputeNodeServiceLogUploadCommand.EndTime   = utcNow;

            const int    numberOfFilesUploaded = 2;
            const string virtualDirectoryName  = "pool1/tvm";

            AzureOperationResponse <ProxyModels.UploadBatchServiceLogsResult, ProxyModels.ComputeNodeUploadBatchServiceLogsHeaders> response2 =
                BatchTestHelpers.CreateComputeNodeServiceLogsAddResponse(numberOfFilesUploaded, virtualDirectoryName);

            RequestInterceptor interceptor2 = BatchTestHelpers.CreateFakeServiceResponseInterceptor <
                ProxyModels.ComputeNodeUploadBatchServiceLogsOptions,
                AzureOperationResponse <ProxyModels.UploadBatchServiceLogsResult, ProxyModels.ComputeNodeUploadBatchServiceLogsHeaders> >(response2);

            startComputeNodeServiceLogUploadCommand.AdditionalBehaviors = new List <BatchClientBehavior>()
            {
                interceptor2
            };

            // Setup the cmdlet to write pipeline output to a list that can be examined later
            PSStartComputeNodeServiceLogUploadResult result = null;

            commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSStartComputeNodeServiceLogUploadResult>())).Callback <object>(c => result = (PSStartComputeNodeServiceLogUploadResult)c);

            startComputeNodeServiceLogUploadCommand.ExecuteCmdlet();

            Assert.NotNull(result);
            Assert.Equal(result.NumberOfFilesUploaded, numberOfFilesUploaded);
            Assert.Equal(result.VirtualDirectoryName, virtualDirectoryName);
        }
Exemplo n.º 54
0
 public ListJobScheduleOptions(BatchAccountContext context, IEnumerable <BatchClientBehavior> additionalBehaviors = null)
     : base(context, additionalBehaviors)
 {
 }
        /// <summary>
        /// Deletes an application package used in a Scenario test.
        /// </summary>
        public static void DeleteApplicationPackage(BatchController controller, BatchAccountContext context, string applicationName, string version)
        {
            BatchClient client = new BatchClient(controller.BatchManagementClient, controller.ResourceManagementClient);

            client.DeleteApplicationPackage(context.ResourceGroupName, context.AccountName, applicationName, version);
        }