Exemple #1
0
        public async Task CanDelegateOutOfProcess()
        {
            using var _ = StartLog(out var loggerFactory);

            var logger = loggerFactory.CreateLogger("CanDelegateOutOfProcess");

            // https://github.com/dotnet/aspnetcore/issues/8247
#pragma warning disable 0618
            var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("HttpSysServer"), "test", "testassets",
                                               "DelegationSite");
#pragma warning restore 0618

            var deploymentParameters = new DeploymentParameters(
                applicationPath,
                ServerType.HttpSys,
                RuntimeFlavor.CoreClr,
                RuntimeArchitecture.x64)
            {
                EnvironmentName = "Testing",
                TargetFramework = Tfm.Default,
                ApplicationType = ApplicationType.Portable,
                PublishApplicationBeforeDeployment = true,
                StatusMessagesEnabled = true
            };

            var queueName = Guid.NewGuid().ToString();
            deploymentParameters.EnvironmentVariables["queue"] = queueName;

            using var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory);
            var deploymentResult = await deployer.DeployAsync().DefaultTimeout();

            // Make sure the deployment really worked
            var responseString = await deploymentResult.HttpClient.GetStringAsync("").DefaultTimeout();

            Assert.Equal("Hello from delegatee", responseString);

            DelegationRule destination = default;
            using var delegator = Utilities.CreateHttpServer(out var delegatorAddress, httpContext =>
            {
                var delegateFeature = httpContext.Features.Get <IHttpSysRequestDelegationFeature>();
                delegateFeature.DelegateRequest(destination);
                return(Task.CompletedTask);
            });

            var delegationProperty = delegator.Features.Get <IServerDelegationFeature>();
            using (destination = delegationProperty.CreateDelegationRule(queueName, deploymentResult.ApplicationBaseUri))
            {
                // Send a request to the delegator that gets transfered to the delegatee in the other process.
                using var client = new HttpClient();
                responseString   = await client.GetStringAsync(delegatorAddress).DefaultTimeout();

                Assert.Equal("Hello from delegatee", responseString);
            }
        }
        public async Task ShutdownTestRun()
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(nameof(ShutdownTestRun));

                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test", "TestAssets",
                                                   "Microsoft.AspNetCore.Hosting.TestSites");

                var deploymentParameters = new DeploymentParameters(
                    applicationPath,
                    ServerType.Kestrel,
                    RuntimeFlavor.CoreClr,
                    RuntimeArchitecture.x64)
                {
                    EnvironmentName = "Shutdown",
                    TargetFramework = "netcoreapp2.0",
                    ApplicationType = ApplicationType.Portable,
                    PublishApplicationBeforeDeployment = true
                };

                deploymentParameters.EnvironmentVariables["ASPNETCORE_STARTMECHANIC"] = "Run";

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    await deployer.DeployAsync();

                    string output = string.Empty;
                    deployer.HostProcess.OutputDataReceived += (sender, args) =>
                    {
                        if (!string.Equals(args.Data, ApplicationStartedMessage) &&
                            !string.IsNullOrEmpty(args.Data) &&
                            !NowListeningRegex.Match(args.Data).Success)
                        {
                            output += args.Data + '\n';
                        }
                    };

                    SendSIGINT(deployer.HostProcess.Id);

                    WaitForExitOrKill(deployer.HostProcess);

                    output = output.Trim('\n');

                    Assert.Equal("Application is shutting down...\n" +
                                 "Stopping firing\n" +
                                 "Stopping end\n" +
                                 "Stopped firing\n" +
                                 "Stopped end",
                                 output);
                }
            }
        }
Exemple #3
0
        public async Task InjectedStartup_DefaultApplicationNameIsEntryAssembly(TestVariant variant)
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(nameof(InjectedStartup_DefaultApplicationNameIsEntryAssembly));

                // https://github.com/dotnet/aspnetcore/issues/8247
#pragma warning disable 0618
                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test", "testassets", "IStartupInjectionAssemblyName");
#pragma warning restore 0618

                var deploymentParameters = new DeploymentParameters(variant)
                {
                    ApplicationPath       = applicationPath,
                    StatusMessagesEnabled = false
                };

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    var tcs    = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
                    var output = string.Empty;

                    deployer.ProcessOutputListener = (data) =>
                    {
                        if (!string.IsNullOrWhiteSpace(data))
                        {
                            output += data + '\n';
                            tcs.TrySetResult();
                        }
                    };

                    await deployer.DeployAsync();

                    try
                    {
                        await tcs.Task.TimeoutAfter(TimeSpan.FromMinutes(1));
                    }
                    catch (TimeoutException ex)
                    {
                        throw new InvalidOperationException("Timeout while waiting for output from host process.", ex);
                    }

                    output = output.Trim('\n');

                    Assert.Equal($"IStartupInjectionAssemblyName", output);
                }
            }
        }
Exemple #4
0
    public async Task ApplicationException(TestVariant variant)
    {
        var testName = $"ApplicationException_{variant.Server}_{variant.Tfm}_{variant.Architecture}_{variant.ApplicationType}";

        using (StartLog(out var loggerFactory, LogLevel.Debug, testName))
        {
            var logger = loggerFactory.CreateLogger("ApplicationException");

            var deploymentParameters = new DeploymentParameters(variant)
            {
                ApplicationPath = Helpers.GetApplicationPath()
            };

            var output = string.Empty;
            using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
            {
                deployer.ProcessOutputListener = (data) =>
                {
                    if (!string.IsNullOrWhiteSpace(data))
                    {
                        output += data + '\n';
                    }
                };

                var deploymentResult = await deployer.DeployAsync();

                // Request to base address and check if various parts of the body are rendered & measure the cold startup time.
                using (var response = await RetryHelper.RetryRequest(() =>
                {
                    return(deploymentResult.HttpClient.GetAsync("/throwexception"));
                }, logger, deploymentResult.HostShutdownToken))
                {
                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);

                    var body = await response.Content.ReadAsStringAsync();

                    Assert.Empty(body);
                }
            }
            // Output should contain the ApplicationException and the 500 status code
            Assert.Contains("System.ApplicationException: Application exception", output);
            Assert.Contains("/throwexception - - - 500", output);
        }
    }
        public async Task ShutdownTestWaitForShutdown()
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(nameof(ShutdownTestWaitForShutdown));

                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test",
                                                   "Microsoft.AspNetCore.Hosting.TestSites");

                var deploymentParameters = new DeploymentParameters(
                    applicationPath,
                    ServerType.Kestrel,
                    RuntimeFlavor.CoreClr,
                    RuntimeArchitecture.x64)
                {
                    EnvironmentName = "Shutdown",
                    TargetFramework = "netcoreapp2.0",
                    ApplicationType = ApplicationType.Portable,
                    PublishApplicationBeforeDeployment = true
                };

                deploymentParameters.EnvironmentVariables.Add(new KeyValuePair <string, string>("ASPNETCORE_STARTMECHANIC", "WaitForShutdown"));

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    await deployer.DeployAsync();

                    string output = string.Empty;
                    deployer.HostProcess.OutputDataReceived += (sender, args) => output += args.Data + '\n';

                    SendSIGINT(deployer.HostProcess.Id);

                    WaitForExitOrKill(deployer.HostProcess);

                    output = output.Trim('\n');

                    Assert.Equal(output, "Stopping firing\n" +
                                 "Stopping end\n" +
                                 "Stopped firing\n" +
                                 "Stopped end");
                }
            }
        }
Exemple #6
0
        private async Task InjectedStartup_DefaultApplicationNameIsEntryAssembly(RuntimeFlavor runtimeFlavor)
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(nameof(InjectedStartup_DefaultApplicationNameIsEntryAssembly));

                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test", "TestAssets", "IStartupInjectionAssemblyName");

                var deploymentParameters = new DeploymentParameters(
                    applicationPath,
                    ServerType.Kestrel,
                    runtimeFlavor,
                    RuntimeArchitecture.x64)
                {
                    TargetFramework = runtimeFlavor == RuntimeFlavor.Clr ? "net461" : "netcoreapp2.0",
                    ApplicationType = ApplicationType.Portable
                };

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    await deployer.DeployAsync();

                    string output = string.Empty;
                    var    mre    = new ManualResetEventSlim();
                    deployer.HostProcess.OutputDataReceived += (sender, args) =>
                    {
                        if (!string.Equals(args.Data, ApplicationStartedMessage) &&
                            !string.IsNullOrEmpty(args.Data) &&
                            !NowListeningRegex.Match(args.Data).Success)
                        {
                            output += args.Data + '\n';
                            mre.Set();
                        }
                    };

                    mre.Wait(10000);

                    output = output.Trim('\n');

                    Assert.Equal($"IStartupInjectionAssemblyName", output);
                }
            }
        }
        public async Task LinkedApplicationWorks()
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger("LinkedApplicationWorks");

                // https://github.com/dotnet/aspnetcore/issues/8247
#pragma warning disable 0618
                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test", "testassets",
                                                   "BasicLinkedApp");
#pragma warning restore 0618

                var deploymentParameters = new DeploymentParameters(
                    applicationPath,
                    ServerType.Kestrel,
                    RuntimeFlavor.CoreClr,
                    RuntimeArchitecture.x64)
                {
                    TargetFramework     = Tfm.Net50,
                    RuntimeArchitecture = RuntimeArchitecture.x64,
                    ApplicationType     = ApplicationType.Standalone,
                    PublishApplicationBeforeDeployment = true,
                    RestoreDependencies   = true,
                    PublishTimeout        = TimeSpan.FromMinutes(10), // Machines are slow (these tests restore)
                    StatusMessagesEnabled = false
                };

                using var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory);

                var result = await deployer.DeployAsync();

                // The app should have started up
                Assert.False(deployer.HostProcess.HasExited);

                var response = await RetryHelper.RetryRequest(() => result.HttpClient.GetAsync("/"), logger, retryCount : 10);

                var body = await response.Content.ReadAsStringAsync();

                Assert.Equal("Hello World", body);
            }
        }
Exemple #8
0
        public async Task InjectedStartup_DefaultApplicationNameIsEntryAssembly(TestVariant variant)
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(nameof(InjectedStartup_DefaultApplicationNameIsEntryAssembly));

// https://github.com/dotnet/aspnetcore/issues/8247
#pragma warning disable 0618
                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test", "testassets", "IStartupInjectionAssemblyName");
#pragma warning restore 0618

                var deploymentParameters = new DeploymentParameters(variant)
                {
                    ApplicationPath       = applicationPath,
                    StatusMessagesEnabled = false
                };

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    await deployer.DeployAsync();

                    string output = string.Empty;
                    var    mre    = new ManualResetEventSlim();
                    deployer.HostProcess.OutputDataReceived += (sender, args) =>
                    {
                        if (!string.IsNullOrWhiteSpace(args.Data))
                        {
                            output += args.Data + '\n';
                            mre.Set();
                        }
                    };

                    mre.Wait(50000);

                    output = output.Trim('\n');

                    Assert.Equal($"IStartupInjectionAssemblyName", output);
                }
            }
        }
Exemple #9
0
        private async Task ExecuteShutdownTest(string testName, string shutdownMechanic)
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(testName);

// https://github.com/aspnet/AspNetCore/issues/8247
#pragma warning disable 0618
                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test", "testassets",
                                                   "Microsoft.AspNetCore.Hosting.TestSites");
#pragma warning restore 0618

                var deploymentParameters = new DeploymentParameters(
                    applicationPath,
                    ServerType.Kestrel,
                    RuntimeFlavor.CoreClr,
                    RuntimeArchitecture.x64)
                {
                    EnvironmentName = "Shutdown",
                    TargetFramework = Tfm.NetCoreApp30,
                    ApplicationType = ApplicationType.Portable,
                    PublishApplicationBeforeDeployment = true,
                    StatusMessagesEnabled = false
                };

                deploymentParameters.EnvironmentVariables["ASPNETCORE_STARTMECHANIC"] = shutdownMechanic;

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    await deployer.DeployAsync();

                    var started   = new ManualResetEventSlim();
                    var completed = new ManualResetEventSlim();
                    var output    = string.Empty;
                    deployer.HostProcess.OutputDataReceived += (sender, args) =>
                    {
                        if (!string.IsNullOrEmpty(args.Data) && args.Data.StartsWith(StartedMessage))
                        {
                            started.Set();
                            output += args.Data.Substring(StartedMessage.Length) + '\n';
                        }
                        else
                        {
                            output += args.Data + '\n';
                        }

                        if (output.Contains(CompletionMessage))
                        {
                            completed.Set();
                        }
                    };

                    started.Wait(50000);

                    if (!started.IsSet)
                    {
                        throw new InvalidOperationException("Application did not start successfully");
                    }

                    SendSIGINT(deployer.HostProcess.Id);

                    WaitForExitOrKill(deployer.HostProcess);

                    completed.Wait(50000);

                    if (!started.IsSet)
                    {
                        throw new InvalidOperationException($"Application did not write the expected output. The received output is: {output}");
                    }

                    output = output.Trim('\n');

                    Assert.Equal(CompletionMessage, output);
                }
            }
        }
Exemple #10
0
        private async Task ExecuteShutdownTest(string testName, string shutdownMechanic)
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(testName);

// https://github.com/dotnet/aspnetcore/issues/8247
#pragma warning disable 0618
                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Hosting"), "test", "testassets",
                                                   "Microsoft.AspNetCore.Hosting.TestSites");
#pragma warning restore 0618

                var deploymentParameters = new DeploymentParameters(
                    applicationPath,
                    ServerType.Kestrel,
                    RuntimeFlavor.CoreClr,
                    RuntimeArchitecture.x64)
                {
                    EnvironmentName = "Shutdown",
                    TargetFramework = Tfm.Default,
                    ApplicationType = ApplicationType.Portable,
                    PublishApplicationBeforeDeployment = true,
                    StatusMessagesEnabled = false
                };

                deploymentParameters.EnvironmentVariables["ASPNETCORE_STARTMECHANIC"] = shutdownMechanic;

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    await deployer.DeployAsync();

                    var startedTcs   = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
                    var completedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
                    var output       = string.Empty;
                    deployer.HostProcess.OutputDataReceived += (sender, args) =>
                    {
                        if (!string.IsNullOrEmpty(args.Data) && args.Data.StartsWith(StartedMessage, StringComparison.Ordinal))
                        {
                            startedTcs.TrySetResult();
                            output += args.Data.Substring(StartedMessage.Length) + '\n';
                        }
                        else
                        {
                            output += args.Data + '\n';
                        }

                        if (output.Contains(CompletionMessage))
                        {
                            completedTcs.TrySetResult();
                        }
                    };

                    try
                    {
                        await startedTcs.Task.TimeoutAfter(TimeSpan.FromMinutes(1));
                    }
                    catch (TimeoutException ex)
                    {
                        throw new InvalidOperationException("Timeout while waiting for host process to output started message.", ex);
                    }

                    SendSIGINT(deployer.HostProcess.Id);

                    WaitForExitOrKill(deployer.HostProcess);

                    try
                    {
                        await completedTcs.Task.TimeoutAfter(TimeSpan.FromMinutes(1));
                    }
                    catch (TimeoutException ex)
                    {
                        throw new InvalidOperationException($"Timeout while waiting for host process to output completion message. The received output is: {output}", ex);
                    }

                    output = output.Trim('\n');

                    Assert.Equal(CompletionMessage, output);
                }
            }
        }
Exemple #11
0
        private async Task ExecuteShutdownTest(string testName, string shutdownMechanic)
        {
            using (StartLog(out var loggerFactory))
            {
                var logger = loggerFactory.CreateLogger(testName);

                // TODO refactor deployers to not depend on source code
                // see https://github.com/aspnet/Extensions/issues/1697 and https://github.com/aspnet/AspNetCore/issues/10268
#pragma warning disable 0618
                var applicationPath = Path.Combine(TestPathUtilities.GetSolutionRootDirectory("Extensions"),
                                                   "src", "Hosting", "test", "testassets", "Microsoft.Extensions.Hosting.TestApp");
#pragma warning restore 0618

                var deploymentParameters = new DeploymentParameters(
                    applicationPath,
                    RuntimeFlavor.CoreClr,
                    RuntimeArchitecture.x64)
                {
                    TargetFramework = Tfm.NetCoreApp30,
                    ApplicationType = ApplicationType.Portable,
                    PublishApplicationBeforeDeployment = true,
                    StatusMessagesEnabled = false
                };

                deploymentParameters.EnvironmentVariables["DOTNET_STARTMECHANIC"] = shutdownMechanic;

                using (var deployer = new SelfHostDeployer(deploymentParameters, loggerFactory))
                {
                    var result = await deployer.DeployAsync();

                    var started   = new TaskCompletionSource <int>(TaskCreationOptions.RunContinuationsAsynchronously);
                    var completed = new TaskCompletionSource <int>(TaskCreationOptions.RunContinuationsAsynchronously);
                    var output    = string.Empty;
                    deployer.HostProcess.OutputDataReceived += (sender, args) =>
                    {
                        if (!string.IsNullOrEmpty(args.Data) && args.Data.StartsWith(StartedMessage))
                        {
                            output += args.Data.Substring(StartedMessage.Length) + '\n';
                            started.TrySetResult(0);
                        }
                        else
                        {
                            output += args.Data + '\n';
                        }

                        if (output.Contains(CompletionMessage))
                        {
                            completed.TrySetResult(0);
                        }
                    };

                    await started.Task.TimeoutAfter(TimeSpan.FromSeconds(60));

                    SendShutdownSignal(deployer.HostProcess);

                    await completed.Task.TimeoutAfter(TimeSpan.FromSeconds(60));

                    WaitForExitOrKill(deployer.HostProcess);

                    output = output.Trim('\n');

                    Assert.Equal(CompletionMessage, output);
                }
            }
        }
Exemple #12
0
        private async Task ExecuteShutdownTest(string testName, string shutdownMechanic)
        {
            var xunitTestLoggerFactory = TestLoggerBuilder.Create(builder =>
            {
                builder.SetMinimumLevel(LogLevel.Trace);
                builder.AddXunit(_output);
            });

            // TODO refactor deployers to not depend on source code
            // see https://github.com/dotnet/extensions/issues/1697 and https://github.com/dotnet/aspnetcore/issues/10268
#pragma warning disable 0618
            var applicationPath = string.Empty; // disabled for now
#pragma warning restore 0618

            var deploymentParameters = new DeploymentParameters(
                applicationPath,
                RuntimeFlavor.CoreClr,
                RuntimeArchitecture.x64)
            {
                TargetFramework = Tfm.NetCoreApp50,
                ApplicationType = ApplicationType.Portable,
                PublishApplicationBeforeDeployment = true,
                StatusMessagesEnabled = false
            };

            deploymentParameters.EnvironmentVariables["DOTNET_STARTMECHANIC"] = shutdownMechanic;

            using (var deployer = new SelfHostDeployer(deploymentParameters, xunitTestLoggerFactory))
            {
                var result = await deployer.DeployAsync();

                var started   = new TaskCompletionSource <int>(TaskCreationOptions.RunContinuationsAsynchronously);
                var completed = new TaskCompletionSource <int>(TaskCreationOptions.RunContinuationsAsynchronously);
                var output    = string.Empty;
                deployer.HostProcess.OutputDataReceived += (sender, args) =>
                {
                    if (!string.IsNullOrEmpty(args.Data) && args.Data.StartsWith(StartedMessage))
                    {
                        output += args.Data.Substring(StartedMessage.Length) + '\n';
                        started.TrySetResult(0);
                    }
                    else
                    {
                        output += args.Data + '\n';
                    }

                    if (output.Contains(CompletionMessage))
                    {
                        completed.TrySetResult(0);
                    }
                };

                await started.Task.TimeoutAfter(TimeSpan.FromSeconds(60));

                SendShutdownSignal(deployer.HostProcess);

                await completed.Task.TimeoutAfter(TimeSpan.FromSeconds(60));

                WaitForExitOrKill(deployer.HostProcess);

                output = output.Trim('\n');

                Assert.Equal(CompletionMessage, output);
            }
        }