Ejemplo n.º 1
0
 public FormServer()
 {
     InitializeComponent();
     _syncContextHelper = new SynchronizationContextHelper();
     _accountNames      = new BindingList <string>();
     _isShutdown        = true;
 }
Ejemplo n.º 2
0
 private void OnInkPointerReleasing(CoreInkIndependentInputSource sender, PointerEventArgs args)
 {
     SynchronizationContextHelper.Execute(
         this.InkPointerReleasing,
         this,
         new InkPointerEventArgs(args.CurrentPoint.GetPointerId(), args));
 }
        public void CanCreateJobWithUsesTaskDependencies()
        {
            void test()
            {
                using BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result;
                string jobId = GenerateJobId();

                try
                {
                    CloudJob cloudJob = batchCli.JobOperations.CreateJob(jobId, new PoolInformation());
                    cloudJob.PoolInformation = new PoolInformation()
                    {
                        PoolId = poolFixture.PoolId
                    };
                    cloudJob.UsesTaskDependencies = true;
                    cloudJob.Commit();

                    var boundJob = batchCli.JobOperations.GetJob(jobId);
                    Assert.True(boundJob.UsesTaskDependencies);
                }
                finally
                {
                    TestUtilities.DeleteJobIfExistsAsync(batchCli, jobId).Wait();
                }
            }

            SynchronizationContextHelper.RunTest(test, TestTimeout);
        }
Ejemplo n.º 4
0
        public async Task BatchRequestWithShortClientSideTimeoutAndRetries()
        {
            const int maxRetries         = 5;
            int       actualRequestCount = 0;

            //The ThrowsAnyAsync must be outside the RunTestAsync or it will deadlock
            await Assert.ThrowsAnyAsync <OperationCanceledException>(async() =>
                                                                     await SynchronizationContextHelper.RunTestAsync(async() =>
            {
                using (BatchClient client = await TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment(), addDefaultRetryPolicy: false))
                {
                    client.CustomBehaviors.Add(RetryPolicyProvider.LinearRetryProvider(TimeSpan.FromMilliseconds(250), maxRetries));
                    List <BatchClientBehavior> customBehaviors = new List <BatchClientBehavior>();
                    customBehaviors.Add(new RequestInterceptor((req) =>
                    {
                        //Set the timeout to something small so it is guaranteed to expire before the service has responded
                        req.Timeout = TimeSpan.FromMilliseconds(25);

                        var castRequest = (JobGetBatchRequest)req;
                        Func <CancellationToken, Task <AzureOperationResponse <Microsoft.Azure.Batch.Protocol.Models.CloudJob, Microsoft.Azure.Batch.Protocol.Models.JobGetHeaders> > > oldFunc = castRequest.ServiceRequestFunc;
                        castRequest.ServiceRequestFunc = async(token) =>
                        {
                            actualRequestCount++;                                            //Count the number of calls to the func
                            return(await oldFunc(token).ConfigureAwait(false));
                        };
                    }));

                    await client.JobOperations.GetJobAsync("Foo", additionalBehaviors: customBehaviors).ConfigureAwait(false);
                }
            },
                                                                                                                     TestTimeout));

            Assert.Equal(maxRetries, actualRequestCount - 1); //Ensure that the number of retries is as expected
        }
Ejemplo n.º 5
0
        public async Task Job_CanAddJobWithJobManagerAndAllowLowPriorityTrue()
        {
            Func <Task> test = async() =>
            {
                using (BatchClient batchCli = await TestUtilities.OpenBatchClientFromEnvironmentAsync().ConfigureAwait(false))
                {
                    string jobId = "TestJobWithLowPriJobManager-" + TestUtilities.GetMyName();
                    try
                    {
                        PoolInformation poolInfo = new PoolInformation()
                        {
                            PoolId = "Fake"
                        };

                        CloudJob unboundJob = batchCli.JobOperations.CreateJob(jobId, poolInfo);
                        unboundJob.JobManagerTask = new JobManagerTask("foo", "cmd /c echo hi")
                        {
                            AllowLowPriorityNode = true
                        };
                        await unboundJob.CommitAsync().ConfigureAwait(false);

                        await unboundJob.RefreshAsync().ConfigureAwait(false);

                        Assert.True(unboundJob.JobManagerTask.AllowLowPriorityNode);
                    }
                    finally
                    {
                        await TestUtilities.DeleteJobIfExistsAsync(batchCli, jobId);
                    }
                }
            };

            await SynchronizationContextHelper.RunTestAsync(test, TestTimeout);
        }
Ejemplo n.º 6
0
 public void OnDeviceConnected(object sender, WebsocketEventArgs evt)
 {
     SynchronizationContextHelper.SendMainSyncContext(() =>
     {
         showNotifyIconMenu(evt.ctx);
     });
 }
        public void SyncWithActionCapturesException()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("Some exception text.");

            // Act

            Mock <SynchronizationContext> mockSyncContext = new Mock <SynchronizationContext>();

            mockSyncContext
            .Expect(sc => sc.Send(It.IsAny <SendOrPostCallback>(), null))
            .Callback(
                delegate(SendOrPostCallback d, object state) {
                try {
                    d(state);
                }
                catch {
                    // swallow exceptions, just like AspNetSynchronizationContext
                }
            });

            // Act & assert
            ExceptionHelper.ExpectInvalidOperationException(
                delegate {
                SynchronizationContextHelper.Sync(mockSyncContext.Object, () => { throw exception; });
            },
                @"Some exception text.");
        }
        public void ReadClientRequestIdAndRequestIdFromException()
        {
            void test()
            {
                using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment());
                Guid myClientRequestid = Guid.NewGuid();
                RequestInterceptor clientRequestIdGenerator = new ClientRequestIdProvider(
                    request => myClientRequestid);

                RequestInterceptor setReturnClientRequestId = new RequestInterceptor(
                    request =>
                {
                    request.Options.ReturnClientRequestId = true;
                });

                BatchException batchException = TestUtilities.AssertThrowsAsync <BatchException>(async() =>
                                                                                                 await batchCli.JobOperations.GetJobAsync("this-job-doesnt-exist", additionalBehaviors: new[] { clientRequestIdGenerator, setReturnClientRequestId })).Result;

                Assert.NotNull(batchException.RequestInformation);
                Assert.NotNull(batchException.RequestInformation.BatchError);
                Assert.NotNull(batchException.RequestInformation.BatchError.Message);

                Assert.Equal(BatchErrorCodeStrings.JobNotFound, batchException.RequestInformation.BatchError.Code);
                Assert.Equal(HttpStatusCode.NotFound, batchException.RequestInformation.HttpStatusCode);
                Assert.Contains("The specified job does not exist", batchException.RequestInformation.BatchError.Message.Value);

                Assert.Equal(myClientRequestid, batchException.RequestInformation.ClientRequestId);
                Assert.NotNull(batchException.RequestInformation.ServiceRequestId);
                Assert.Equal("The specified job does not exist.", batchException.RequestInformation.HttpStatusMessage);
            }

            SynchronizationContextHelper.RunTest(test, TestTimeout);
        }
Ejemplo n.º 9
0
        public void Bug1771070_1771072_JobAndPoolLifetimeStats()
        {
            Action test = () =>
            {
                using (BatchClient batchCli = TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment()).Result)
                {
                    JobStatistics  jobStatistics  = batchCli.JobOperations.GetAllJobsLifetimeStatistics();
                    PoolStatistics poolStatistics = batchCli.PoolOperations.GetAllPoolsLifetimeStatistics();

                    Assert.NotNull(jobStatistics);
                    Assert.NotNull(poolStatistics);

                    //Since we cannot really validate that the stats returned by the service are correct, the best we can do is make sure we get some

                    //Dump a few properties from each stats bag to make sure they are populated
                    this.testOutputHelper.WriteLine("JobScheduleStatistics.StartTime: {0}", jobStatistics.StartTime);
                    this.testOutputHelper.WriteLine("JobScheduleStatistics.LastUpdateTime: {0}", jobStatistics.LastUpdateTime);
                    this.testOutputHelper.WriteLine("JobScheduleStatistics.NumSucceededTasks: {0}", jobStatistics.SucceededTaskCount);
                    this.testOutputHelper.WriteLine("JobScheduleStatistics.UserCpuTime: {0}", jobStatistics.UserCpuTime);

                    this.testOutputHelper.WriteLine("PoolStatistics.StartTime: {0}", poolStatistics.StartTime);
                    this.testOutputHelper.WriteLine("PoolStatistics.LastUpdateTime: {0}", poolStatistics.LastUpdateTime);
                    this.testOutputHelper.WriteLine("PoolStatistics.ResourceStatistics.AvgMemory: {0}", poolStatistics.ResourceStatistics.AverageMemoryGiB);
                    this.testOutputHelper.WriteLine("PoolStatistics.UsageStatistics.DedicatedCoreTime: {0}", poolStatistics.UsageStatistics.DedicatedCoreTime);
                }
            };

            SynchronizationContextHelper.RunTest(test, TestTimeout);
        }
Ejemplo n.º 10
0
        public async Task AddTasksFailIfPoisonTaskTooLarge()
        {
            const string        testName      = "AddTasksFailIfPoisonTaskTooLarge";
            List <ResourceFile> resourceFiles = new List <ResourceFile>();
            ResourceFile        resourceFile;

            // If this test fails try increasing the size of the Task in case maximum size increase
            for (int i = 0; i < 10000; i++)
            {
                resourceFile = ResourceFile.FromUrl("https://mystorageaccount.blob.core.windows.net/files/resourceFile" + i, "resourceFile" + i);
                resourceFiles.Add(resourceFile);
            }
            await SynchronizationContextHelper.RunTestAsync(async() =>
            {
                using (BatchClient batchCli = await TestUtilities.OpenBatchClientFromEnvironmentAsync())
                {
                    var exception = await TestUtilities.AssertThrowsAsync <ParallelOperationsException>(
                        async() => await this.AddTasksSimpleTestAsync(batchCli, testName, 1, resourceFiles: resourceFiles).ConfigureAwait(false)).ConfigureAwait(false);
                    var innerException = exception.InnerException;
                    Assert.IsType <BatchException>(innerException);
                    Assert.Equal(((BatchException)innerException).RequestInformation.BatchError.Code, BatchErrorCodeStrings.RequestBodyTooLarge);
                }
            },
                                                            TestTimeout);
        }
Ejemplo n.º 11
0
 public void OnTotalCountUpdated(object sender, WebsocketEventArgs evt)
 {
     SynchronizationContextHelper.SendMainSyncContext(() =>
     {
         updateNotifyIconMenu(evt.ctx);
     });
 }
        public async Task ApplicationPackageReferencesOnCloudTaskAreRoundtripped()
        {
            string jobId  = Constants.DefaultConveniencePrefix + TestUtilities.GetMyName() + "-APROnCloudTaskAreRoundtripped";
            string taskId = "task-id";

            const string applicationId     = "blender";
            const string applicationVerson = "beta";

            Func <Task> test = async() =>
            {
                using (BatchClient client = await TestUtilities.OpenBatchClientFromEnvironmentAsync().ConfigureAwait(false))
                {
                    var poolInfo = new PoolInformation
                    {
                        AutoPoolSpecification = new AutoPoolSpecification
                        {
                            PoolSpecification = new PoolSpecification
                            {
                                CloudServiceConfiguration = new CloudServiceConfiguration(PoolFixture.OSFamily),
                                VirtualMachineSize        = PoolFixture.VMSize,
                            },
                            PoolLifetimeOption = PoolLifetimeOption.Job
                        }
                    };

                    try
                    {
                        CloudJob job = client.JobOperations.CreateJob(jobId, poolInfo);
                        await job.CommitAsync().ConfigureAwait(false);

                        var boundJob = await client.JobOperations.GetJobAsync(jobId).ConfigureAwait(false);

                        CloudTask cloudTask = new CloudTask(taskId, "cmd /c ping 127.0.0.1")
                        {
                            ApplicationPackageReferences = new[]
                            {
                                new ApplicationPackageReference
                                {
                                    ApplicationId = applicationId,
                                    Version       = applicationVerson
                                }
                            }
                        };

                        await boundJob.AddTaskAsync(cloudTask).ConfigureAwait(false);

                        CloudTask boundCloudTask = await boundJob.GetTaskAsync(taskId).ConfigureAwait(false);

                        Assert.Equal(applicationId, boundCloudTask.ApplicationPackageReferences.Single().ApplicationId);
                        Assert.Equal(applicationVerson, boundCloudTask.ApplicationPackageReferences.Single().Version);
                    }
                    finally
                    {
                        TestUtilities.DeleteJobIfExistsAsync(client, jobId).Wait();
                    }
                }
            };

            await SynchronizationContextHelper.RunTestAsync(test, TestTimeout);
        }
Ejemplo n.º 13
0
        public void Bug2338301_CheckStreamPositionAfterFileRead()
        {
            Action test = () =>
            {
                using (BatchClient batchCli = TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment()).Result)
                {
                    JobOperations jobOperations = batchCli.JobOperations;
                    {
                        string jobId = "Bug2338301Job-" + TestUtilities.GetMyName();

                        try
                        {
                            const string taskId = "hiWorld";

                            //
                            // Create the job
                            //
                            CloudJob unboundJob = jobOperations.CreateJob(jobId, new PoolInformation()
                            {
                                PoolId = this.poolFixture.PoolId
                            });
                            unboundJob.Commit();

                            CloudJob  boundJob = jobOperations.GetJob(jobId);
                            CloudTask myTask   = new CloudTask(taskId, "cmd /c echo hello world");

                            boundJob.AddTask(myTask);

                            this.testOutputHelper.WriteLine("Initial job commit()");

                            //
                            // Wait for task to go to completion
                            //
                            Utilities        utilities        = batchCli.Utilities;
                            TaskStateMonitor taskStateMonitor = utilities.CreateTaskStateMonitor();
                            taskStateMonitor.WaitAll(
                                boundJob.ListTasks(),
                                Microsoft.Azure.Batch.Common.TaskState.Completed,
                                TimeSpan.FromMinutes(3));

                            CloudTask boundTask = boundJob.GetTask(taskId);

                            //Get the task file
                            const string fileToGet = "stdout.txt";
                            NodeFile     file      = boundTask.GetNodeFile(fileToGet);

                            //Download the file data
                            string result = file.ReadAsString();
                            Assert.True(result.Length > 0);
                        }
                        finally
                        {
                            jobOperations.DeleteJob(jobId);
                        }
                    }
                }
            };

            SynchronizationContextHelper.RunTest(test, TestTimeout);
        }
Ejemplo n.º 14
0
        public void TestOMJobPrepReleaseRunOnNaiveComputeNode()
        {
            string jobId = "TestOMJobPrepReleaseRunOnNaiveComputeNode-" + TestUtilities.GetMyName();
            Action test  = () =>
            {
                using (BatchClient client = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()))
                {
                    try
                    {
                        // create job with prep/release
                        {
                            CloudJob unboundJob = client.JobOperations.CreateJob(jobId, null);
                            unboundJob.PoolInformation        = new PoolInformation();
                            unboundJob.PoolInformation.PoolId = this.poolFixture.PoolId;

                            // add the jobPrep task to the job
                            {
                                JobPreparationTask prep = new JobPreparationTask("cmd /c echo JobPrep!!");
                                unboundJob.JobPreparationTask = prep;

                                prep.WaitForSuccess = true; // be explicit even though this is the default.  need JP/JP to not run
                            }


                            // add a jobRelease task to the job
                            {
                                JobReleaseTask relTask = new JobReleaseTask(JobReleaseTaskCommandLine);
                                unboundJob.JobReleaseTask = relTask;
                            }

                            // add the job to the service
                            unboundJob.Commit();
                        }

                        // the victim nodes.  pool should have size 1.
                        List <ComputeNode> computeNodes = client.PoolOperations.ListComputeNodes(this.poolFixture.PoolId).ToList();

                        Assert.Single(computeNodes);
                        // now we have a job with zero tasks... lets call get-status methods

                        // call it
                        List <JobPreparationAndReleaseTaskExecutionInformation> jrStatusList =
                            client.JobOperations.ListJobPreparationAndReleaseTaskStatus(jobId).ToList();

                        JobPreparationAndReleaseTaskExecutionInformation prepAndReleaseStatus = jrStatusList.FirstOrDefault();

                        Assert.Null(prepAndReleaseStatus);
                    }
                    finally
                    {
                        // cleanup
                        TestUtilities.DeleteJobIfExistsAsync(client, jobId).Wait();
                    }
                }
            };

            SynchronizationContextHelper.RunTest(test, TestTimeout);
        }
        public async Task ComputeNodeUploadLogs()
        {
            Func <Task> test = async() =>
            {
                using (BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result)
                {
                    const string containerName = "computenodelogscontainer";

                    // Generate a storage container URL
                    StagingStorageAccount storageAccount  = TestUtilities.GetStorageCredentialsFromEnvironment();
                    BlobServiceClient     blobClient      = BlobUtilities.GetBlobServiceClient(storageAccount);
                    BlobContainerClient   containerClient = BlobUtilities.GetBlobContainerClient(containerName, blobClient, storageAccount);

                    try
                    {
                        containerClient.CreateIfNotExists();
                        string sasUri = BlobUtilities.GetWriteableSasUri(containerClient, storageAccount);

                        var blobs = containerClient.GetAllBlobs();

                        // Ensure that there are no items in the container to begin with
                        Assert.Empty(blobs);

                        var startTime = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(5));

                        var node   = batchCli.PoolOperations.ListComputeNodes(this.poolFixture.PoolId).First();
                        var result = batchCli.PoolOperations.UploadComputeNodeBatchServiceLogs(
                            this.poolFixture.PoolId,
                            node.Id,
                            sasUri,
                            startTime);

                        Assert.NotEqual(0, result.NumberOfFilesUploaded);
                        Assert.NotEmpty(result.VirtualDirectoryName);

                        // Allow up to 2m for files to get uploaded
                        DateTime timeoutAt = DateTime.UtcNow.AddMinutes(2);
                        while (DateTime.UtcNow < timeoutAt)
                        {
                            blobs = containerClient.GetAllBlobs();
                            if (blobs.Any())
                            {
                                break;
                            }
                        }

                        Assert.NotEmpty(blobs);
                    }
                    finally
                    {
                        await containerClient.DeleteIfExistsAsync();
                    }
                }
            };

            await SynchronizationContextHelper.RunTestAsync(test, TestTimeout);
        }
        public async Task Bug1360227_AddTasksBatchFailure(bool useJobOperations)
        {
            const string     testName              = "Bug1360227_AddTasksBatchFailure";
            int              count                 = 0;
            const int        countToFailAt         = 102;
            const int        taskCount             = 407;
            HashSet <string> taskIdsExpectedToFail = new HashSet <string>();
            Func <AddTaskResult, CancellationToken, AddTaskResultStatus> resultHandlerFunc = (result, token) =>
            {
                this.testOutputHelper.WriteLine("Task: {0} got status code: {1}", result.TaskId, result.Status);
                ++count;

                if (taskIdsExpectedToFail.Contains(result.TaskId))
                {
                    return(AddTaskResultStatus.Retry);
                }
                else
                {
                    if (count >= countToFailAt)
                    {
                        taskIdsExpectedToFail.Add(result.TaskId);

                        this.testOutputHelper.WriteLine("Forcing a failure");

                        //Throw an exception to cause a failure from the customers result handler -- this is a supported scenario which will
                        //terminate the add task operation
                        throw new HttpRequestException("Test");
                    }
                    else
                    {
                        return(AddTaskResultStatus.Success);
                    }
                }
            };

            await SynchronizationContextHelper.RunTestAsync(async() =>
            {
                using (BatchClient batchCli = await TestUtilities.OpenBatchClientFromEnvironmentAsync())
                {
                    BatchClientParallelOptions parallelOptions = new BatchClientParallelOptions()
                    {
                        MaxDegreeOfParallelism = 2
                    };

                    var exception = await TestUtilities.AssertThrowsAsync <ParallelOperationsException>(
                        async() => await this.AddTasksSimpleTestAsync(
                            batchCli,
                            testName,
                            taskCount,
                            parallelOptions,
                            resultHandlerFunc,
                            useJobOperations: useJobOperations).ConfigureAwait(false)).ConfigureAwait(false);
                    Assert.IsType <HttpRequestException>(exception.InnerException);
                }
            },
                                                            TestTimeout);
        }
        public async Task JobSchedulePatch()
        {
            Func <Task> test = async() =>
            {
                using (BatchClient batchCli = await TestUtilities.OpenBatchClientFromEnvironmentAsync().ConfigureAwait(false))
                {
                    string       jobScheduleId            = "TestPatchJobSchedule-" + TestUtilities.GetMyName();
                    const string newJobManagerCommandLine = "cmd /c dir";
                    const string metadataKey           = "Foo";
                    const string metadataValue         = "Bar";
                    TimeSpan     newRecurrenceInterval = TimeSpan.FromDays(2);
                    try
                    {
                        CloudJobSchedule jobSchedule = batchCli.JobScheduleOperations.CreateJobSchedule(
                            jobScheduleId,
                            new Schedule()
                        {
                            RecurrenceInterval = TimeSpan.FromDays(1)
                        },
                            new JobSpecification(new PoolInformation()
                        {
                            PoolId = "DummyPool"
                        })
                        {
                            JobManagerTask = new JobManagerTask(id: "Foo", commandLine: "Foo")
                        });

                        await jobSchedule.CommitAsync().ConfigureAwait(false);

                        await jobSchedule.RefreshAsync().ConfigureAwait(false);

                        jobSchedule.JobSpecification.JobManagerTask.CommandLine = newJobManagerCommandLine;
                        jobSchedule.Metadata = new List <MetadataItem>()
                        {
                            new MetadataItem(metadataKey, metadataValue)
                        };
                        jobSchedule.Schedule.RecurrenceInterval = newRecurrenceInterval;

                        await jobSchedule.CommitChangesAsync().ConfigureAwait(false);

                        await jobSchedule.RefreshAsync().ConfigureAwait(false);

                        Assert.Equal(newRecurrenceInterval, jobSchedule.Schedule.RecurrenceInterval);
                        Assert.Equal(newJobManagerCommandLine, jobSchedule.JobSpecification.JobManagerTask.CommandLine);
                        Assert.Equal(metadataKey, jobSchedule.Metadata.Single().Name);
                        Assert.Equal(metadataValue, jobSchedule.Metadata.Single().Value);
                    }
                    finally
                    {
                        await TestUtilities.DeleteJobScheduleIfExistsAsync(batchCli, jobScheduleId).ConfigureAwait(false);
                    }
                }
            };

            await SynchronizationContextHelper.RunTestAsync(test, TestTimeout);
        }
        public void HelloWorld()
        {
            void test()
            {
                using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment());
                TestUtilities.HelloWorld(batchCli, testOutputHelper, poolFixture.Pool, out string job, out string task);
            }

            SynchronizationContextHelper.RunTest(test, TestTimeout);
        }
Ejemplo n.º 19
0
        public void TestComputeNodeUserIaas()
        {
            Action test = () =>
            {
                using (BatchClient batchCli = TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment()).Result)
                {
                    CloudPool     sharedPool       = this.poolFixture.Pool;
                    List <string> cnuNamesToDelete = new List <string>();

                    // pick a compute node to victimize with user accounts
                    var nodes = sharedPool.ListComputeNodes().ToList();

                    ComputeNode cn = nodes[0];

                    try
                    {
                        ComputeNodeUser bob = batchCli.PoolOperations.CreateComputeNodeUser(sharedPool.Id, cn.Id);

                        bob.Name         = "bob";
                        bob.ExpiryTime   = DateTime.UtcNow + TimeSpan.FromHours(25);
                        bob.Password     = "******";
                        bob.SshPublicKey = "base64==";

                        cnuNamesToDelete.Add(bob.Name); // remember to clean this up

                        bob.Commit(ComputeNodeUserCommitSemantics.AddUser);

                        bob.SshPublicKey = "base65==";

                        bob.Commit(ComputeNodeUserCommitSemantics.UpdateUser);

                        // TODO:  need to close the loop on this somehow... move to unit/interceptor-based?
                        //        currently the server is timing out.
                    }
                    finally
                    {
                        // clear any old accounts
                        try
                        {
                            foreach (string curCNUName in cnuNamesToDelete)
                            {
                                this.testOutputHelper.WriteLine("TestComputeNodeUserIAAS attempting to delete the following <nodeid,user>: <{0},{1}>", cn.Id, curCNUName);
                                cn.DeleteComputeNodeUser(curCNUName);
                            }
                        }
                        catch (Exception ex)
                        {
                            this.testOutputHelper.WriteLine("TestComputeNodeUserIAAS: exception deleting user account.  ex: " + ex.ToString());
                        }
                    }
                }
            };

            SynchronizationContextHelper.RunTest(test, TestTimeout);
        }
Ejemplo n.º 20
0
        public async Task End2EndApplicationPackageScenario()
        {
            string accountName = TestCommon.Configuration.BatchAccountName;

            Func <Task> test = async() =>
            {
                var poolId = "app-ref-test" + Guid.NewGuid();
                using (BatchClient client = await TestUtilities.OpenBatchClientFromEnvironmentAsync())
                {
                    using (var mgmtClient = IntegrationTestCommon.OpenBatchManagementClient())
                    {
                        // Give the application a display name
                        await mgmtClient.Application.UpdateAsync(TestCommon.Configuration.BatchAccountResourceGroup, accountName, ApplicationId, new UpdateApplicationParameters
                        {
                            AllowUpdates   = true,
                            DefaultVersion = ApplicationIntegrationCommon.Version,
                            DisplayName    = DisplayName
                        }).ConfigureAwait(false);

                        List <ApplicationSummary> applicationSummaries = await client.ApplicationOperations.ListApplicationSummaries().ToListAsync().ConfigureAwait(false);

                        ApplicationSummary applicationSummary = applicationSummaries.First();
                        Assert.Equal(ApplicationIntegrationCommon.Version, applicationSummary.Versions.First());
                        Assert.Equal(ApplicationId, applicationSummary.Id);
                        Assert.Equal(DisplayName, applicationSummary.DisplayName);


                        ApplicationSummary getApplicationSummary = await client.ApplicationOperations.GetApplicationSummaryAsync(applicationSummary.Id).ConfigureAwait(false);

                        Assert.Equal(getApplicationSummary.Id, applicationSummary.Id);
                        Assert.Equal(getApplicationSummary.Versions.Count(), applicationSummary.Versions.Count());
                        Assert.Equal(getApplicationSummary.DisplayName, applicationSummary.DisplayName);

                        var appPackage = await mgmtClient.ApplicationPackage.GetAsync(
                            TestCommon.Configuration.BatchAccountResourceGroup,
                            accountName,
                            ApplicationId,
                            ApplicationIntegrationCommon.Version).ConfigureAwait(false);

                        Assert.Equal(PackageState.Active, appPackage.State);
                        Assert.Equal(ApplicationIntegrationCommon.Version, appPackage.Version);
                        Assert.Equal(ApplicationId, appPackage.Id);

                        var application = await mgmtClient.Application.GetAsync(TestCommon.Configuration.BatchAccountResourceGroup, accountName, ApplicationId).ConfigureAwait(false);

                        Assert.Equal(ApplicationIntegrationCommon.Version, application.DefaultVersion);
                        Assert.Equal(ApplicationId, application.Id);

                        await AssertPoolWasCreatedWithApplicationReferences(client, poolId, ApplicationId).ConfigureAwait(false);
                    }
                }
            };

            await SynchronizationContextHelper.RunTestAsync(test, LongRunningTestTimeout);
        }
Ejemplo n.º 21
0
        public void SetUpdateJobConditionalHeader()
        {
            Action test = () =>
            {
                using (BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result)
                {
                    string jobId = "JobConditionalHeaders-" + TestUtilities.GetMyName();
                    try
                    {
                        PoolInformation poolInfo = new PoolInformation()
                        {
                            PoolId = "Fake"
                        };

                        CloudJob unboundJob = batchCli.JobOperations.CreateJob(jobId, poolInfo);
                        unboundJob.Commit();

                        CloudJob boundJob = batchCli.JobOperations.GetJob(jobId);

                        string capturedEtag1 = boundJob.ETag;
                        this.testOutputHelper.WriteLine("Etag is: {0}", capturedEtag1);
                        Assert.NotNull(capturedEtag1);

                        boundJob.Constraints = new JobConstraints(TimeSpan.FromMinutes(60), 0);

                        BatchClientBehavior updateInterceptor = new Protocol.RequestInterceptor(
                            (req) =>
                        {
                            var typedParams = req.Options as Protocol.Models.JobUpdateOptions;
                            if (typedParams != null)
                            {
                                typedParams.IfMatch = capturedEtag1;
                            }
                        });

                        //Update bound job with if-match header, it should succeed
                        boundJob.Commit(additionalBehaviors: new[] { updateInterceptor });

                        boundJob = batchCli.JobOperations.GetJob(jobId);

                        boundJob.Constraints = new JobConstraints(TimeSpan.FromMinutes(30), 1);

                        //Update bound job with if-match header, it should fail
                        Exception e = TestUtilities.AssertThrows <BatchException>(() => boundJob.Commit(additionalBehaviors: new[] { updateInterceptor }));
                        TestUtilities.AssertIsBatchExceptionAndHasCorrectAzureErrorCode(e, BatchErrorCodeStrings.ConditionNotMet, this.testOutputHelper);
                    }
                    finally
                    {
                        TestUtilities.DeleteJobIfExistsAsync(batchCli, jobId).Wait();
                    }
                }
            };

            SynchronizationContextHelper.RunTest(test, LongTestTimeout);
        }
Ejemplo n.º 22
0
        public void OnFileEnding(object sender, WebsocketEventArgs args)
        {
            var file_id   = args.ctx.fileCtx.file_id;
            var file_name = args.ctx.fileCtx.file_name;
            var file_type = args.ctx.fileCtx.type;

            SynchronizationContextHelper.SendMainSyncContext(() =>
            {
                showFile(file_id, file_name, file_type, args.ctx.device_name, args.ctx.device_id);
            });
        }
Ejemplo n.º 23
0
 public void Open(SynchronizationContext synchronizationContext)
 {
     if (synchronizationContext != null)
     {
         this.synchronizationContext = synchronizationContext;
     }
     else
     {
         this.synchronizationContext = SynchronizationContextHelper.GetDefaultSynchronizationContext();
     }
 }
        public void TestListJobsByJobSchedule()
        {
            Action test = () =>
            {
                using (BatchClient batchCli = TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment()).Result)
                {
                    string jobScheduleId = Microsoft.Azure.Batch.Constants.DefaultConveniencePrefix + TestUtilities.GetMyName() + "-TestListJobsByJobSchedule";

                    try
                    {
                        Schedule schedule = new Schedule()
                        {
                            DoNotRunAfter      = DateTime.UtcNow.Add(TimeSpan.FromDays(1)),
                            RecurrenceInterval = TimeSpan.FromMinutes(1)
                        };

                        JobSpecification jobSpecification = new JobSpecification(new PoolInformation()
                        {
                            PoolId = "DummyPool"
                        });

                        CloudJobSchedule unboundJobSchedule = batchCli.JobScheduleOperations.CreateJobSchedule(jobScheduleId, schedule, jobSpecification);
                        unboundJobSchedule.Commit();

                        //List the jobs under this JobSchedule
                        for (int i = 1; i <= 3; i++)
                        {
                            string           expectedJobId    = string.Format("{0}:job-{1}", jobScheduleId, i);
                            CloudJobSchedule boundJobSchedule = TestUtilities.WaitForJobOnJobSchedule(
                                batchCli.JobScheduleOperations,
                                jobScheduleId,
                                expectedJobId: expectedJobId,
                                timeout: TimeSpan.FromSeconds(70));

                            List <CloudJob> jobs = boundJobSchedule.ListJobs().ToList();
                            Assert.Equal(i, jobs.Count);

                            jobs = batchCli.JobScheduleOperations.ListJobs(jobScheduleId).ToList();
                            Assert.Equal(i, jobs.Count);

                            //Terminate the current job to force a new job to be created
                            batchCli.JobOperations.TerminateJob(expectedJobId);
                        }
                    }
                    finally
                    {
                        // clean up
                        TestUtilities.DeleteJobScheduleIfExistsAsync(batchCli, jobScheduleId).Wait();
                    }
                }
            };

            SynchronizationContextHelper.RunTest(test, LongTestTimeout);
        }
Ejemplo n.º 25
0
 public void Open(SynchronizationContext synchronizationContext)
 {
     Fx.Assert(this.synchronizationContext == null, "can only open when in the created state");
     if (synchronizationContext != null)
     {
         this.synchronizationContext = synchronizationContext;
     }
     else
     {
         this.synchronizationContext = SynchronizationContextHelper.GetDefaultSynchronizationContext();
     }
 }
        public async Task Bug1360227_AddTasksBatchRequestFailure(bool useJobOperations)
        {
            const string testName = "Bug1360227_AddTasksBatchRequestFailure";

            Random rand     = new Random();
            object randLock = new object();

            BatchClientBehavior customBehavior = new Protocol.RequestInterceptor(request =>
            {
                var typedRequest = request as Protocol.BatchRequests.TaskAddCollectionBatchRequest;

                if (typedRequest != null)
                {
                    var originalServiceRequestFunction = typedRequest.ServiceRequestFunc;

                    typedRequest.ServiceRequestFunc = token =>
                    {
                        lock (randLock)
                        {
                            double d = rand.NextDouble();
                            if (d > 0.3)
                            {
                                throw new HttpRequestException("Simulating a network problem");
                            }
                            else
                            {
                                return(originalServiceRequestFunction(token));
                            }
                        }
                    };
                }
            });

            await SynchronizationContextHelper.RunTestAsync(async() =>
            {
                using (BatchClient batchCli = await TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment(), addDefaultRetryPolicy: false))
                {
                    batchCli.JobOperations.CustomBehaviors.Add(customBehavior);

                    BatchClientParallelOptions parallelOptions = new BatchClientParallelOptions()
                    {
                        MaxDegreeOfParallelism = 2
                    };

                    var exception = await TestUtilities.AssertThrowsAsync <ParallelOperationsException>(async() =>
                                                                                                        await this.AddTasksSimpleTestAsync(batchCli, testName, 397, parallelOptions, useJobOperations: useJobOperations).ConfigureAwait(false)
                                                                                                        ).ConfigureAwait(false);

                    Assert.IsType <HttpRequestException>(exception.InnerException);
                }
            },
                                                            TestTimeout);
        }
Ejemplo n.º 27
0
        public void Bug1965363_2384616_Wat7OSVersionFeatures()
        {
            Action test = () =>
            {
                using (BatchClient batchCli = TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment()).Result)
                {
                    PoolOperations poolOperations = batchCli.PoolOperations;
                    try
                    {
                        this.testOutputHelper.WriteLine("Listing OS Versions:");

                        // create pool tests

                        // forget to set CloudServiceConfiguration on Create, get error
                        {
                            CloudPool noArgs = poolOperations.CreatePool("Bug1965363ButNoOSFamily-" + TestUtilities.GetMyName(), PoolFixture.VMSize, default(CloudServiceConfiguration), targetDedicatedComputeNodes: 0);

                            BatchException ex    = TestUtilities.AssertThrows <BatchException>(() => noArgs.Commit());
                            string         exStr = ex.ToString();

                            // we are expecting an exception, assert if the exception is not the correct one.
                            Assert.Contains("cloudServiceConfiguration", exStr);
                        }

                        // create a pool WITH an osFamily
                        {
                            string poolIdHOSF = "Bug1965363HasOSF-" + TestUtilities.GetMyName();
                            try
                            {
                                CloudPool hasOSF = poolOperations.CreatePool(poolIdHOSF, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: 0);

                                hasOSF.Commit();
                            }
                            finally
                            {
                                poolOperations.DeletePool(poolIdHOSF);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // special case os version beacuse it is a common failure and requires human intervention/editing
                        // test for expired os version
                        Assert.DoesNotContain("The specified OS Version does not exists", ex.ToString());

                        throw;
                    }
                }
            };

            SynchronizationContextHelper.RunTest(test, TestTimeout);
        }
        public async Task TestPoolCertificateReferencesWithUpdate()
        {
            Func <Task> test = async() =>
            {
                using (BatchClient batchCli = await TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment()))
                {
                    //Generate the certificates
                    const string certificatePrefix = "poolwithcertificatereferences";

                    string cerFilePath = IntegrationTestCommon.GetTemporaryCertificateFilePath(string.Format("{0}.cer", certificatePrefix));
                    string pfxFilePath = IntegrationTestCommon.GetTemporaryCertificateFilePath(string.Format("{0}.pfx", certificatePrefix));

                    IEnumerable <Certificate> certificates = GenerateCertificates(batchCli, cerFilePath, pfxFilePath);

                    try
                    {
                        foreach (Certificate certificate in certificates)
                        {
                            this.testOutputHelper.WriteLine("Adding certificate with thumbprint: {0}", certificate.Thumbprint);
                            await certificate.CommitAsync().ConfigureAwait(false);
                        }

                        List <CertificateReference> certificateReferences = certificates.Select(cer => new CertificateReference(cer)
                        {
                            StoreLocation = CertStoreLocation.LocalMachine,
                            StoreName     = "My",
                            Visibility    = CertificateVisibility.RemoteUser
                        }).ToList();

                        await TestPoolCreateAndUpdateWithCertificateReferencesAsync(batchCli, certificateReferences).ConfigureAwait(false);
                        await TestAutoPoolCreateAndUpdateWithCertificateReferencesAsync(batchCli, certificateReferences).ConfigureAwait(false);
                    }
                    finally
                    {
                        File.Delete(pfxFilePath);
                        File.Delete(cerFilePath);

                        foreach (Certificate certificate in certificates)
                        {
                            TestUtilities.DeleteCertificateIfExistsAsync(batchCli, certificate.ThumbprintAlgorithm, certificate.Thumbprint).Wait();
                        }

                        foreach (Certificate certificate in certificates)
                        {
                            TestUtilities.DeleteCertMonitor(batchCli.CertificateOperations, this.testOutputHelper, certificate.ThumbprintAlgorithm, certificate.Thumbprint);
                        }
                    }
                }
            };

            await SynchronizationContextHelper.RunTestAsync(test, TestTimeout);
        }
        public async Task CanCreateJobAndAutoPoolWithAppPackageReferences()
        {
            var          jobId         = Guid.NewGuid().ToString();
            const string applicationId = "blender";

            Func <Task> test = async() =>
            {
                using (BatchClient client = await TestUtilities.OpenBatchClientFromEnvironmentAsync().ConfigureAwait(false))
                {
                    var poolInfo = new PoolInformation
                    {
                        AutoPoolSpecification = new AutoPoolSpecification
                        {
                            PoolSpecification = new PoolSpecification
                            {
                                ApplicationPackageReferences = new[]
                                {
                                    new ApplicationPackageReference
                                    {
                                        ApplicationId = applicationId,
                                        Version       = PoolFixture.VMSize,
                                    }
                                },
                                CloudServiceConfiguration = new CloudServiceConfiguration(PoolFixture.OSFamily),
                                VirtualMachineSize        = PoolFixture.VMSize,
                            },
                            PoolLifetimeOption = PoolLifetimeOption.Job
                        }
                    };

                    CloudJob response = null;
                    try
                    {
                        CloudJob job = client.JobOperations.CreateJob(jobId, poolInfo);
                        await job.CommitAsync().ConfigureAwait(false);

                        response = await client.JobOperations.GetJobAsync(jobId).ConfigureAwait(false);

                        Assert.Equal(response.PoolInformation.AutoPoolSpecification.PoolSpecification.ApplicationPackageReferences.First().ApplicationId, applicationId);
                    }
                    finally
                    {
                        if (response != null)
                        {
                            TestUtilities.DeleteJobIfExistsAsync(client, jobId).Wait();
                        }
                    }
                }
            };

            await SynchronizationContextHelper.RunTestAsync(test, TestTimeout);
        }
        public async Task Bug1360227_AddTasksBatchMultipleBatches(bool useJobOperations)
        {
            const string testName = "Bug1360227_AddTasksBatchMultipleBatches";

            await SynchronizationContextHelper.RunTestAsync(async() =>
            {
                using (BatchClient batchCli = await TestUtilities.OpenBatchClientFromEnvironmentAsync())
                {
                    await this.AddTasksSimpleTestAsync(batchCli, testName, 550, useJobOperations: useJobOperations).ConfigureAwait(false);
                }
            },
                                                            TestTimeout);
        }