public TestFixture()
            {
                HostSettings = new WebHostSettings
                {
                    IsSelfHost  = true,
                    ScriptPath  = Path.Combine(Environment.CurrentDirectory, @"..\..\..\TestScripts\Proxies"),
                    LogPath     = Path.Combine(Path.GetTempPath(), @"ProxyTests\Logs"),
                    SecretsPath = Path.Combine(Path.GetTempPath(), @"ProxyTests\Secrets")
                };

                _testServer = new TestServer(
                    AspNetCore.WebHost.CreateDefaultBuilder()
                    .UseStartup <Startup>()
                    .ConfigureServices(services =>
                {
                    services.Replace(new ServiceDescriptor(typeof(WebHostSettings), HostSettings));
                    services.Replace(new ServiceDescriptor(typeof(ISecretManager), new TestSecretManager()));
                }));

                var scriptConfig = _testServer.Host.Services.GetService <WebHostResolver>().GetScriptHostConfiguration(HostSettings);

                HttpClient             = _testServer.CreateClient();
                HttpClient.BaseAddress = new Uri("https://localhost/");

                TestHelpers.WaitForWebHost(HttpClient);
            }
Esempio n. 2
0
            public TestFixture()
            {
                HostOptions = new ScriptApplicationHostOptions
                {
                    IsSelfHost  = true,
                    ScriptPath  = Path.Combine(Environment.CurrentDirectory, @"..\..\..\TestScripts\Proxies"),
                    LogPath     = Path.Combine(Path.GetTempPath(), @"ProxyTests\Logs"),
                    SecretsPath = Path.Combine(Path.GetTempPath(), @"ProxyTests\Secrets")
                };

                var factory        = new TestOptionsFactory <ScriptApplicationHostOptions>(HostOptions);
                var optionsMonitor = new OptionsMonitor <ScriptApplicationHostOptions>(factory, Array.Empty <IOptionsChangeTokenSource <ScriptApplicationHostOptions> >(), factory);

                _testServer = new TestServer(
                    AspNetCore.WebHost.CreateDefaultBuilder()
                    .UseStartup <Startup>()
                    .ConfigureServices(services =>
                {
                    services.Replace(new ServiceDescriptor(typeof(IOptions <ScriptApplicationHostOptions>), new OptionsWrapper <ScriptApplicationHostOptions>(HostOptions)));
                    services.Replace(new ServiceDescriptor(typeof(ISecretManager), new TestSecretManager()));
                    services.Replace(new ServiceDescriptor(typeof(IOptionsMonitor <ScriptApplicationHostOptions>), optionsMonitor));
                }));

                var scriptConfig = _testServer.Host.Services.GetService <IOptions <ScriptJobHostOptions> >().Value;

                HttpClient             = _testServer.CreateClient();
                HttpClient.BaseAddress = new Uri("https://localhost/");

                TestHelpers.WaitForWebHost(HttpClient);
            }
        private async Task InitializeTestHostAsync(string testDirName, IEnvironment environment)
        {
            var httpConfig         = new HttpConfiguration();
            var uniqueTestRootPath = Path.Combine(_testRootPath, testDirName, Guid.NewGuid().ToString());

            _loggerProvider = new TestLoggerProvider();

            if (environment.IsAppServiceEnvironment())
            {
                // if the test is mocking App Service environment, we need
                // to also set the HOME and WEBSITE_SITE_NAME variables
                environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteHomePath, uniqueTestRootPath);
                environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteName, "test-host-name");
            }

            var webHostBuilder = Program.CreateWebHostBuilder()
                                 .ConfigureAppConfiguration(c =>
            {
                // This source reads from AzureWebJobsScriptRoot, which does not work
                // with the custom paths that these tests are using.
                var source = c.Sources.OfType <WebScriptHostConfigurationSource>().SingleOrDefault();
                if (source != null)
                {
                    c.Sources.Remove(source);
                }
            })
                                 .ConfigureLogging(c =>
            {
                c.AddProvider(_loggerProvider);
            })
                                 .ConfigureServices(c =>
            {
                c.ConfigureAll <ScriptApplicationHostOptions>(o =>
                {
                    o.IsSelfHost  = true;
                    o.LogPath     = Path.Combine(uniqueTestRootPath, "logs");
                    o.SecretsPath = Path.Combine(uniqueTestRootPath, "secrets");
                    o.ScriptPath  = _expectedScriptPath = Path.Combine(uniqueTestRootPath, "wwwroot");
                });

                c.AddSingleton <IEnvironment>(_ => environment);

                c.AddSingleton <IConfigureBuilder <ILoggingBuilder> >(new DelegatedConfigureBuilder <ILoggingBuilder>(b => b.AddProvider(_loggerProvider)));
            });

            _httpServer             = new TestServer(webHostBuilder);
            _httpClient             = _httpServer.CreateClient();
            _httpClient.BaseAddress = new Uri("https://localhost/");

            TestHelpers.WaitForWebHost(_httpClient);

            var traces = _loggerProvider.GetAllLogMessages().ToArray();

            Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Host is in standby mode")));

            _expectedHostId = await _httpServer.Host.Services.GetService <IHostIdProvider>().GetHostIdAsync(CancellationToken.None);
        }
            public TestFixture()
            {
                // copy test files to temp directory, since accessing the metadata APIs will result
                // in file creations (for test data files)
                var scriptSource = Path.Combine(Environment.CurrentDirectory, "..", "..", "..", "TestScripts", "WarmupFunction");

                _testHome = Path.Combine(Path.GetTempPath(), @"WarmupFunction");
                var scriptRoot = Path.Combine(_testHome, "site", "wwwroot");

                FileUtility.CopyDirectory(scriptSource, scriptRoot);

                HostOptions = new ScriptApplicationHostOptions
                {
                    IsSelfHost   = true,
                    ScriptPath   = scriptRoot,
                    LogPath      = Path.Combine(_testHome, "LogFiles", "Application", "Functions"),
                    SecretsPath  = Path.Combine(_testHome, "data", "Functions", "Secrets"),
                    TestDataPath = Path.Combine(_testHome, "data", "Functions", "SampleData")
                };

                FileUtility.EnsureDirectoryExists(HostOptions.TestDataPath);

                var optionsMonitor = TestHelpers.CreateOptionsMonitor(HostOptions);

                var workerOptions = new LanguageWorkerOptions
                {
                    WorkerConfigs = TestHelpers.GetTestWorkerConfigs()
                };

                var provider = new HostFunctionMetadataProvider(optionsMonitor, NullLogger <HostFunctionMetadataProvider> .Instance, new TestMetricsLogger());

                var builder = AspNetCore.WebHost.CreateDefaultBuilder()
                              .UseStartup <Startup>()
                              .ConfigureServices(services =>
                {
                    services.Replace(new ServiceDescriptor(typeof(IOptions <ScriptApplicationHostOptions>), new OptionsWrapper <ScriptApplicationHostOptions>(HostOptions)));
                    services.Replace(new ServiceDescriptor(typeof(ISecretManagerProvider), new TestSecretManagerProvider(new TestSecretManager())));
                    services.Replace(new ServiceDescriptor(typeof(IOptionsMonitor <ScriptApplicationHostOptions>), optionsMonitor));
                    services.Replace(new ServiceDescriptor(typeof(IFunctionMetadataProvider), provider));

                    services.SkipDependencyValidation();
                });

                // TODO: https://github.com/Azure/azure-functions-host/issues/4876
                _testServer = new TestServer(builder);
                HostOptions.RootServiceProvider = _testServer.Host.Services;
                var scriptConfig = _testServer.Host.Services.GetService <IOptions <ScriptJobHostOptions> >().Value;

                HttpClient             = _testServer.CreateClient();
                HttpClient.BaseAddress = new Uri("https://localhost/");

                TestHelpers.WaitForWebHost(HttpClient);
            }
        private async Task InitializeTestHost(string testDirName)
        {
            var httpConfig   = new HttpConfiguration();
            var testRootPath = Path.Combine(Path.GetTempPath(), testDirName);
            await FileUtility.DeleteDirectoryAsync(testRootPath, true);

            _loggerProvider = new TestLoggerProvider();
            var loggerProviderFactory = new TestLoggerProviderFactory(_loggerProvider);

            _webHostSettings = new WebHostSettings
            {
                IsSelfHost  = true,
                LogPath     = Path.Combine(testRootPath, "Logs"),
                SecretsPath = Path.Combine(testRootPath, "Secrets"),
                ScriptPath  = Path.Combine(testRootPath, "WWWRoot")
            };

            if (_settingsManager.IsAppServiceEnvironment)
            {
                // if the test is mocking App Service environment, we need
                // to also set the HOME variable
                Environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteHomePath, testRootPath);
            }

            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(_loggerProvider);

            var webHostBuilder = Program.CreateWebHostBuilder()
                                 .ConfigureServices(c =>
            {
                c.AddSingleton(_webHostSettings)
                .AddSingleton <ILoggerProviderFactory>(loggerProviderFactory)
                .AddSingleton <ILoggerFactory>(loggerFactory);
            });

            _httpServer             = new TestServer(webHostBuilder);
            _httpClient             = _httpServer.CreateClient();
            _httpClient.BaseAddress = new Uri("https://localhost/");

            TestHelpers.WaitForWebHost(_httpClient);

            var traces = _loggerProvider.GetAllLogMessages().ToArray();

            Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Starting Host (HostId=placeholder-host")));
            Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Host is in standby mode")));

            var hostConfig = WebHostResolver.CreateScriptHostConfiguration(_webHostSettings, true);

            _expectedHostId = hostConfig.HostConfig.HostId;
        }
Esempio n. 6
0
        private void InitializeTestHost(string testDirName)
        {
            var httpConfig         = new HttpConfiguration();
            var uniqueTestRootPath = Path.Combine(_testRootPath, testDirName, Guid.NewGuid().ToString());

            _loggerProvider = new TestLoggerProvider();

            _webHostOptions = new ScriptApplicationHostOptions
            {
                IsSelfHost  = true,
                LogPath     = Path.Combine(uniqueTestRootPath, "Logs"),
                SecretsPath = Path.Combine(uniqueTestRootPath, "Secrets"),
                ScriptPath  = Path.Combine(uniqueTestRootPath, "WWWRoot")
            };

            if (_settingsManager.IsAppServiceEnvironment)
            {
                // if the test is mocking App Service environment, we need
                // to also set the HOME variable
                Environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteHomePath, uniqueTestRootPath);
            }

            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(_loggerProvider);

            var webHostBuilder = Program.CreateWebHostBuilder()
                                 .ConfigureServices(c =>
            {
                c.AddSingleton(_webHostOptions)
                .AddSingleton <ILoggerProvider>(_loggerProvider)
                .AddSingleton <ILoggerFactory>(loggerFactory);
            });

            _httpServer             = new TestServer(webHostBuilder);
            _httpClient             = _httpServer.CreateClient();
            _httpClient.BaseAddress = new Uri("https://localhost/");

            TestHelpers.WaitForWebHost(_httpClient);

            var traces = _loggerProvider.GetAllLogMessages().ToArray();

            Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Starting Host (HostId=placeholder-host")));
            Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Host is in standby mode")));

            var hostConfig = _webHostOptions.ToScriptHostConfiguration(true);
            // TODO: DI (FACAVAL) Review
            // _expectedHostId = hostConfig.HostConfig.HostId;
        }
        protected async Task InitializeTestHostAsync(string testDirName, IEnvironment environment)
        {
            var webHostBuilder = await CreateWebHostBuilderAsync(testDirName, environment);

            _httpServer             = new TestServer(webHostBuilder);
            _httpClient             = _httpServer.CreateClient();
            _httpClient.BaseAddress = new Uri("https://localhost/");

            TestHelpers.WaitForWebHost(_httpClient);

            var traces = _loggerProvider.GetAllLogMessages().ToArray();

            Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Host is in standby mode")));

            _expectedHostId = await _httpServer.Host.Services.GetService <IHostIdProvider>().GetHostIdAsync(CancellationToken.None);
        }
Esempio n. 8
0
            public TestFixture()
            {
                // copy test files to temp directory, since accessing the metadata APIs will result
                // in file creations (for test data files)
                var scriptSource = Path.Combine(Environment.CurrentDirectory, @"..\..\..\TestScripts\Proxies");

                _testHome = Path.Combine(Path.GetTempPath(), @"ProxyTests");
                var scriptRoot = Path.Combine(_testHome, @"site\wwwroot");

                FileUtility.CopyDirectory(scriptSource, scriptRoot);

                HostOptions = new ScriptApplicationHostOptions
                {
                    IsSelfHost   = true,
                    ScriptPath   = scriptRoot,
                    LogPath      = Path.Combine(_testHome, @"LogFiles\Application\Functions"),
                    SecretsPath  = Path.Combine(_testHome, @"data\Functions\Secrets"),
                    TestDataPath = Path.Combine(_testHome, @"data\Functions\SampleData")
                };

                FileUtility.EnsureDirectoryExists(HostOptions.TestDataPath);

                var optionsMonitor = TestHelpers.CreateOptionsMonitor(HostOptions);

                var builder = AspNetCore.WebHost.CreateDefaultBuilder()
                              .UseStartup <Startup>()
                              .ConfigureServices(services =>
                {
                    services.Replace(new ServiceDescriptor(typeof(IOptions <ScriptApplicationHostOptions>), new OptionsWrapper <ScriptApplicationHostOptions>(HostOptions)));
                    services.Replace(new ServiceDescriptor(typeof(ISecretManagerProvider), new TestSecretManagerProvider(new TestSecretManager())));
                    services.Replace(new ServiceDescriptor(typeof(IOptionsMonitor <ScriptApplicationHostOptions>), optionsMonitor));
                });

                _testServer = new TestServer(builder);

                var scriptConfig = _testServer.Host.Services.GetService <IOptions <ScriptJobHostOptions> >().Value;

                HttpClient             = _testServer.CreateClient();
                HttpClient.BaseAddress = new Uri("https://localhost/");

                TestHelpers.WaitForWebHost(HttpClient);
            }
Esempio n. 9
0
        public async Task StandbyMode_EndToEnd()
        {
            var vars = new Dictionary <string, string>
            {
                { EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1" },
                { EnvironmentSettingNames.AzureWebsiteContainerReady, null },
                { EnvironmentSettingNames.AzureWebsiteInstanceId, "87654639876900123453445678890144" },
                { "AzureWebEncryptionKey", "0F75CA46E7EBDD39E4CA6B074D1F9A5972B849A55F91A248" }
            };

            using (var env = new TestScopedEnvironmentVariable(vars))
            {
                var httpConfig = new HttpConfiguration();

                var testRootPath = Path.Combine(Path.GetTempPath(), "StandbyModeTest");
                await FileUtility.DeleteDirectoryAsync(testRootPath, true);

                var loggerProvider        = new TestLoggerProvider();
                var loggerProviderFactory = new TestLoggerProviderFactory(loggerProvider);
                var webHostSettings       = new WebHostSettings
                {
                    IsSelfHost  = true,
                    LogPath     = Path.Combine(testRootPath, "Logs"),
                    SecretsPath = Path.Combine(testRootPath, "Secrets"),
                    ScriptPath  = Path.Combine(testRootPath, "WWWRoot")
                };

                var loggerFactory = new LoggerFactory();
                loggerFactory.AddProvider(loggerProvider);

                var webHostBuilder = Program.CreateWebHostBuilder()
                                     .ConfigureServices(c => {
                    c.AddSingleton(webHostSettings)
                    .AddSingleton <ILoggerProviderFactory>(loggerProviderFactory)
                    .AddSingleton <ILoggerFactory>(loggerFactory);
                });

                var httpServer = new TestServer(webHostBuilder);
                var httpClient = httpServer.CreateClient();
                httpClient.BaseAddress = new Uri("https://localhost/");

                TestHelpers.WaitForWebHost(httpClient);

                var traces = loggerProvider.GetAllLogMessages().ToArray();
                Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Starting Host (HostId=placeholder-host")));
                Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Host is in standby mode")));

                // issue warmup request and verify
                var request  = new HttpRequestMessage(HttpMethod.Get, "api/warmup");
                var response = await httpClient.SendAsync(request);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                string responseBody = await response.Content.ReadAsStringAsync();

                Assert.Equal("WarmUp complete.", responseBody);

                // issue warmup request with restart and verify
                request  = new HttpRequestMessage(HttpMethod.Get, "api/warmup?restart=1");
                response = await httpClient.SendAsync(request);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                responseBody = await response.Content.ReadAsStringAsync();

                Assert.Equal("WarmUp complete.", responseBody);

                // Now specialize the host
                ScriptSettingsManager.Instance.SetSetting(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "0");
                ScriptSettingsManager.Instance.SetSetting(EnvironmentSettingNames.AzureWebsiteContainerReady, "1");

                Assert.False(WebScriptHostManager.InStandbyMode);
                Assert.True(ScriptSettingsManager.Instance.ContainerReady);

                // give time for the specialization to happen
                string[] logLines = null;
                await TestHelpers.Await(() =>
                {
                    // wait for the trace indicating that the host has been specialized
                    logLines = loggerProvider.GetAllLogMessages().Where(p => p.FormattedMessage != null).Select(p => p.FormattedMessage).ToArray();
                    return(logLines.Contains("Generating 0 job function(s)"));
                }, userMessageCallback : () => string.Join(Environment.NewLine, loggerProvider.GetAllLogMessages().Select(p => $"[{p.Timestamp.ToString("HH:mm:ss.fff")}] {p.FormattedMessage}")));

                httpServer.Dispose();
                httpClient.Dispose();

                await Task.Delay(2000);

                var hostConfig     = WebHostResolver.CreateScriptHostConfiguration(webHostSettings, true);
                var expectedHostId = hostConfig.HostConfig.HostId;

                // verify the rest of the expected logs
                string text = string.Join(Environment.NewLine, logLines);
                Assert.True(logLines.Count(p => p.Contains("Stopping Host")) >= 1);
                Assert.Equal(1, logLines.Count(p => p.Contains("Creating StandbyMode placeholder function directory")));
                Assert.Equal(1, logLines.Count(p => p.Contains("StandbyMode placeholder function directory created")));
                Assert.Equal(2, logLines.Count(p => p.Contains("Starting Host (HostId=placeholder-host")));
                Assert.Equal(2, logLines.Count(p => p.Contains("Host is in standby mode")));
                Assert.Equal(2, logLines.Count(p => p.Contains("Executed 'Functions.WarmUp' (Succeeded")));
                Assert.Equal(1, logLines.Count(p => p.Contains("Starting host specialization")));
                Assert.Equal(1, logLines.Count(p => p.Contains($"Starting Host (HostId={expectedHostId}")));
                Assert.Contains("Generating 0 job function(s)", logLines);

                WebScriptHostManager.ResetStandbyMode();
            }
        }
Esempio n. 10
0
        public async Task StandbyMode_EndToEnd_LinuxContainer()
        {
            byte[] bytes         = TestHelpers.GenerateKeyBytes();
            var    encryptionKey = Convert.ToBase64String(bytes);

            var vars = new Dictionary <string, string>
            {
                { EnvironmentSettingNames.ContainerName, "TestContainer" },
                { EnvironmentSettingNames.ContainerEncryptionKey, encryptionKey },
                { EnvironmentSettingNames.AzureWebsiteContainerReady, null },
                { "AzureWebEncryptionKey", "0F75CA46E7EBDD39E4CA6B074D1F9A5972B849A55F91A248" }
            };

            using (var env = new TestScopedEnvironmentVariable(vars))
            {
                var httpConfig = new HttpConfiguration();

                var testRootPath = Path.Combine(Path.GetTempPath(), "StandbyModeTest_Linux");
                await FileUtility.DeleteDirectoryAsync(testRootPath, true);

                var loggerProvider        = new TestLoggerProvider();
                var loggerProviderFactory = new TestLoggerProviderFactory(loggerProvider);
                var webHostSettings       = new WebHostSettings
                {
                    IsSelfHost  = true,
                    LogPath     = Path.Combine(testRootPath, "Logs"),
                    SecretsPath = Path.Combine(testRootPath, "Secrets"),
                    ScriptPath  = Path.Combine(testRootPath, "WWWRoot")
                };

                var loggerFactory = new LoggerFactory();
                loggerFactory.AddProvider(loggerProvider);

                var webHostBuilder = Program.CreateWebHostBuilder()
                                     .ConfigureServices(c =>
                {
                    c.AddSingleton(webHostSettings)
                    .AddSingleton <ILoggerProviderFactory>(loggerProviderFactory)
                    .AddSingleton <ILoggerFactory>(loggerFactory);
                });

                var httpServer = new TestServer(webHostBuilder);
                var httpClient = httpServer.CreateClient();
                httpClient.BaseAddress = new Uri("https://localhost/");

                TestHelpers.WaitForWebHost(httpClient);

                var traces = loggerProvider.GetAllLogMessages().ToArray();
                Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Starting Host (HostId=placeholder-host")));
                Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Host is in standby mode")));

                // issue warmup request and verify
                var request  = new HttpRequestMessage(HttpMethod.Get, "api/warmup");
                var response = await httpClient.SendAsync(request);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                string responseBody = await response.Content.ReadAsStringAsync();

                Assert.Equal("WarmUp complete.", responseBody);

                // issue warmup request with restart and verify
                request  = new HttpRequestMessage(HttpMethod.Get, "api/warmup?restart=1");
                response = await httpClient.SendAsync(request);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                responseBody = await response.Content.ReadAsStringAsync();

                Assert.Equal("WarmUp complete.", responseBody);

                // Now specialize the host by invoking assign
                var    secretManager = httpServer.Host.Services.GetService <ISecretManager>();
                var    masterKey     = (await secretManager.GetHostSecretsAsync()).MasterKey;
                string uri           = "admin/instance/assign";
                request = new HttpRequestMessage(HttpMethod.Post, uri);
                var environment       = new Dictionary <string, string>();
                var assignmentContext = new HostAssignmentContext
                {
                    SiteId      = 1234,
                    SiteName    = "TestSite",
                    Environment = environment
                };
                var    encryptedAssignmentContext = EncryptedHostAssignmentContext.Create(assignmentContext, encryptionKey);
                string json = JsonConvert.SerializeObject(encryptedAssignmentContext);
                request.Content = new StringContent(json, Encoding.UTF8, "application/json");
                request.Headers.Add(AuthenticationLevelHandler.FunctionsKeyHeaderName, masterKey);
                response = await httpClient.SendAsync(request);

                Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);

                // give time for the specialization to happen
                string[] logLines = null;
                await TestHelpers.Await(() =>
                {
                    // wait for the trace indicating that the host has been specialized
                    logLines = loggerProvider.GetAllLogMessages().Where(p => p.FormattedMessage != null).Select(p => p.FormattedMessage).ToArray();
                    return(logLines.Contains("Generating 0 job function(s)"));
                }, userMessageCallback : () => string.Join(Environment.NewLine, loggerProvider.GetAllLogMessages().Select(p => $"[{p.Timestamp.ToString("HH:mm:ss.fff")}] {p.FormattedMessage}")));

                httpServer.Dispose();
                httpClient.Dispose();

                await Task.Delay(2000);

                var hostConfig     = WebHostResolver.CreateScriptHostConfiguration(webHostSettings, true);
                var expectedHostId = hostConfig.HostConfig.HostId;

                // verify the rest of the expected logs
                string text = string.Join(Environment.NewLine, logLines);
                Assert.True(logLines.Count(p => p.Contains("Stopping Host")) >= 1);
                Assert.Equal(1, logLines.Count(p => p.Contains("Creating StandbyMode placeholder function directory")));
                Assert.Equal(1, logLines.Count(p => p.Contains("StandbyMode placeholder function directory created")));
                Assert.Equal(2, logLines.Count(p => p.Contains("Starting Host (HostId=placeholder-host")));
                Assert.Equal(2, logLines.Count(p => p.Contains("Host is in standby mode")));
                Assert.Equal(2, logLines.Count(p => p.Contains("Executed 'Functions.WarmUp' (Succeeded")));
                Assert.Equal(1, logLines.Count(p => p.Contains("Starting host specialization")));
                Assert.Equal(1, logLines.Count(p => p.Contains($"Starting Host (HostId={expectedHostId}")));
                Assert.Contains("Generating 0 job function(s)", logLines);

                WebScriptHostManager.ResetStandbyMode();
            }
        }
Esempio n. 11
0
        public async Task StandbyMode_EndToEnd()
        {
            var vars = new Dictionary <string, string>
            {
                { EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1" },
                { EnvironmentSettingNames.AzureWebsiteInstanceId, "87654639876900123453445678890144" }
            };

            using (var env = new TestScopedEnvironmentVariable(vars))
            {
                var httpConfig = new HttpConfiguration();
                httpConfig.Formatters.Add(new PlaintextMediaTypeFormatter());

                var settingsManager = ScriptSettingsManager.Instance;
                var testRootPath    = Path.Combine(Path.GetTempPath(), "StandbyModeTest");
                if (Directory.Exists(testRootPath))
                {
                    Directory.Delete(testRootPath, true);
                }
                var traceWriter     = new TestTraceWriter(TraceLevel.Info);
                var webHostSettings = new WebHostSettings
                {
                    IsSelfHost  = true,
                    LogPath     = Path.Combine(testRootPath, "Logs"),
                    SecretsPath = Path.Combine(testRootPath, "Secrets"),
                    TraceWriter = traceWriter
                };
                WebApiConfig.Register(httpConfig, _settingsManager, webHostSettings);

                var httpServer = new HttpServer(httpConfig);
                var httpClient = new HttpClient(httpServer);
                httpClient.BaseAddress = new Uri("https://localhost/");

                TestHelpers.WaitForWebHost(httpClient);

                var traces = traceWriter.Traces.ToArray();
                Assert.Equal($"Creating StandbyMode placeholder function directory ({Path.GetTempPath()}Functions\\Standby)", traces[0].Message);
                Assert.Equal("StandbyMode placeholder function directory created", traces[1].Message);

                // issue warmup request and verify
                var request  = new HttpRequestMessage(HttpMethod.Get, "api/warmup");
                var response = await httpClient.SendAsync(request);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                string responseBody = await response.Content.ReadAsStringAsync();

                Assert.Equal("WarmUp complete.", responseBody);

                // issue warmup request with restart and verify
                request  = new HttpRequestMessage(HttpMethod.Get, "api/warmup?restart=1");
                response = await httpClient.SendAsync(request);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                responseBody = await response.Content.ReadAsStringAsync();

                Assert.Equal("WarmUp complete.", responseBody);

                httpServer.Dispose();
                httpClient.Dispose();

                await Task.Delay(2000);

                // verify logs
                string[] logLines = traceWriter.Traces.Select(p => p.Message).ToArray();
                Assert.Equal(2, logLines.Count(p => p.Contains("Host is in standby mode")));
                Assert.Equal(1, logLines.Count(p => p.Contains("Stopping Host")));
                Assert.Equal(2, logLines.Count(p => p.Contains("Executed 'Functions.WarmUp' (Succeeded")));
            }
        }