public EnsureHostRunningHandler(HttpConfiguration config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            _scriptHostManager = (WebScriptHostManager)config.DependencyResolver.GetService(typeof(WebScriptHostManager));
        }
        public void IsWarmUpRequest_ReturnsExpectedValue()
        {
            var request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/warmup");

            Assert.False(StandbyManager.IsWarmUpRequest(request));

            var vars = new Dictionary <string, string>
            {
                { EnvironmentSettingNames.AzureWebsitePlaceholderMode, "0" },
                { EnvironmentSettingNames.AzureWebsiteInstanceId, null }
            };

            using (var env = new TestScopedEnvironmentVariable(vars))
            {
                // in this test we're forcing a transition from non-placeholder mode to placeholder mode
                // which can't happen in the wild, so we force a reset here
                WebScriptHostManager.ResetStandbyMode();

                _settingsManager.SetSetting(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1");
                Assert.False(StandbyManager.IsWarmUpRequest(request));

                _settingsManager.SetSetting(EnvironmentSettingNames.AzureWebsiteInstanceId, "12345");
                Assert.True(StandbyManager.IsWarmUpRequest(request));

                request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/csharphttpwarmup");
                Assert.True(StandbyManager.IsWarmUpRequest(request));

                request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/warmup");
                request.Headers.Add(ScriptConstants.AntaresLogIdHeaderName, "xyz123");
                Assert.False(StandbyManager.IsWarmUpRequest(request));

                request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/foo");
                Assert.False(StandbyManager.IsWarmUpRequest(request));
            }

            vars = new Dictionary <string, string>
            {
                { EnvironmentSettingNames.AzureWebsitePlaceholderMode, "0" },
                { EnvironmentSettingNames.AzureWebsiteInstanceId, null }
            };
            using (var env = new TestScopedEnvironmentVariable(vars))
            {
                WebScriptHostManager.ResetStandbyMode();

                _settingsManager.SetSetting(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1");
                Assert.False(StandbyManager.IsWarmUpRequest(request));

                request = HttpTestHelpers.CreateHttpRequest("POST", "http://azure.com/api/warmup");
                _settingsManager.SetSetting(EnvironmentSettingNames.ContainerName, "TestContainer");
                Assert.True(_settingsManager.IsLinuxContainerEnvironment);
                Assert.True(StandbyManager.IsWarmUpRequest(request));
            }
        }
        public void AddRouteDataToRequest_DoesNotAddRequestProperty_WhenRouteDataNull()
        {
            var mockRouteData = new Mock <IHttpRouteData>(MockBehavior.Strict);
            IDictionary <string, object> values = null;

            mockRouteData.Setup(p => p.Values).Returns(values);
            HttpRequestMessage request = new HttpRequestMessage();

            WebScriptHostManager.AddRouteDataToRequest(mockRouteData.Object, request);

            Assert.False(request.Properties.ContainsKey(HttpExtensionConstants.AzureWebJobsHttpRouteDataKey));
        }
Beispiel #4
0
        public async Task EmptyHost_StartsSuccessfully()
        {
            await _fixture.InitializationTask;

            string functionTestDir = Path.Combine(_fixture.TestFunctionRoot, Guid.NewGuid().ToString());

            Directory.CreateDirectory(functionTestDir);

            // important for the repro that these directories no not exist
            string logDir     = Path.Combine(_fixture.TestLogsRoot, Guid.NewGuid().ToString());
            string secretsDir = Path.Combine(_fixture.TestSecretsRoot, Guid.NewGuid().ToString());

            JObject hostConfig = new JObject
            {
                { "id", "123456" }
            };

            File.WriteAllText(Path.Combine(functionTestDir, ScriptConstants.HostMetadataFileName), hostConfig.ToString());

            ScriptHostConfiguration config = new ScriptHostConfiguration
            {
                RootScriptPath  = functionTestDir,
                RootLogPath     = logDir,
                FileLoggingMode = FileLoggingMode.Always
            };
            string             connectionString = AmbientConnectionStringProvider.Instance.GetConnectionString(ConnectionStringNames.Storage);
            ISecretsRepository repository       = new BlobStorageSecretsRepository(secretsDir, connectionString, "EmptyHost_StartsSuccessfully");
            ISecretManager     secretManager    = new SecretManager(_settingsManager, repository, null);
            WebHostSettings    webHostSettings  = new WebHostSettings();

            webHostSettings.SecretsPath = _secretsDirectory.Path;
            var               mockEventManager = new Mock <IScriptEventManager>();
            IWebJobsRouter    router           = _fixture.CreateRouter();
            ScriptHostManager hostManager      = new WebScriptHostManager(config, new TestSecretManagerFactory(secretManager), mockEventManager.Object, _settingsManager, webHostSettings, router, NullLoggerFactory.Instance);

            Task runTask = Task.Run(() => hostManager.RunAndBlock());

            await TestHelpers.Await(() => hostManager.State == ScriptHostState.Running, timeout : 10000);

            hostManager.Stop();
            Assert.Equal(ScriptHostState.Default, hostManager.State);

            // give some time for the logs to be flushed fullly
            await Task.Delay(FileWriter.LogFlushIntervalMs * 3);

            string hostLogFilePath = Directory.EnumerateFiles(Path.Combine(logDir, "Host")).Single();
            string hostLogs        = File.ReadAllText(hostLogFilePath);

            Assert.Contains("Generating 0 job function(s)", hostLogs);
            Assert.Contains("No job functions found.", hostLogs);
            Assert.Contains("Job host started", hostLogs);
            Assert.Contains("Job host stopped", hostLogs);
        }
        public async Task StandbyMode_EndToEnd()
        {
            var vars = new Dictionary <string, string>
            {
                { EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1" },
                { EnvironmentSettingNames.AzureWebsiteContainerReady, null },
                { EnvironmentSettingNames.AzureWebsiteSku, "Dynamic" },
                { EnvironmentSettingNames.AzureWebsiteHomePath, null },
                { EnvironmentSettingNames.AzureWebsiteInstanceId, "87654639876900123453445678890144" },
                { "AzureWebEncryptionKey", "0F75CA46E7EBDD39E4CA6B074D1F9A5972B849A55F91A248" }
            };

            using (var env = new TestScopedEnvironmentVariable(vars))
            {
                InitializeTestHost("Windows");

                await VerifyWarmupSucceeds();
                await VerifyWarmupSucceeds(restart : true);

                // 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);

                _httpServer.Dispose();
                _httpClient.Dispose();

                // 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}")));

                // verify the rest of the expected logs
                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();
            }
        }
        internal static void Initialize(ContainerBuilder builder, WebHostSettings settings)
        {
            ScriptHostConfiguration scriptHostConfig = new ScriptHostConfiguration()
            {
                RootScriptPath     = settings.ScriptPath,
                RootLogPath        = settings.LogPath,
                FileLoggingEnabled = true
            };

            // If running on Azure Web App, derive the host ID from the site name
            string hostId = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME");

            if (!String.IsNullOrEmpty(hostId))
            {
                // Truncate to the max host name length if needed
                const int MaximumHostIdLength = 32;
                if (hostId.Length > MaximumHostIdLength)
                {
                    hostId = hostId.Substring(0, MaximumHostIdLength);
                }

                // Trim any trailing - as they can cause problems with queue names
                hostId = hostId.TrimEnd('-');

                scriptHostConfig.HostConfig.HostId = hostId.ToLowerInvariant();
            }

            WebScriptHostManager scriptHostManager = new WebScriptHostManager(scriptHostConfig);

            builder.RegisterInstance <WebScriptHostManager>(scriptHostManager);

            SecretManager secretManager = new SecretManager(settings.SecretsPath);

            // Make sure that host secrets get created on startup if they don't exist
            secretManager.GetHostSecrets();
            builder.RegisterInstance <SecretManager>(secretManager);

            WebHookReceiverManager webHookReceiverManager = new WebHookReceiverManager(secretManager);

            builder.RegisterInstance <WebHookReceiverManager>(webHookReceiverManager);

            if (!settings.IsSelfHost)
            {
                HostingEnvironment.QueueBackgroundWorkItem((ct) => scriptHostManager.RunAndBlock(ct));
            }
            else
            {
                Task.Run(() => scriptHostManager.RunAndBlock());
            }
        }
        private async Task RunTimeoutExceptionTest(TraceWriter trace, bool handleCancellation)
        {
            TimeSpan gracePeriod = TimeSpan.FromMilliseconds(5000);

            _manager = await CreateAndStartWebScriptHostManager(trace);

            string scenarioName = handleCancellation ? "useToken" : "ignoreToken";

            var args = new Dictionary <string, object>
            {
                { "input", scenarioName }
            };

            await Assert.ThrowsAsync <FunctionTimeoutException>(() => _manager.Instance.CallAsync("TimeoutToken", args));
        }
Beispiel #8
0
        public void Warmup_Succeeds()
        {
            using (new TestEnvironment())
            {
                var settings = GetWebHostSettings();
                WebScriptHostManager.WarmUp(settings);

                var hostLogPath = Path.Combine(settings.LogPath, @"host");
                var hostLogFile = Directory.GetFiles(hostLogPath).First();
                var content     = File.ReadAllText(hostLogFile);

                Assert.Contains("Warm up started", content);
                Assert.Contains("Warm up succeeded", content);
            }
        }
        public async Task MultipleHostRestarts()
        {
            string functionTestDir = Path.Combine(_fixture.TestFunctionRoot, Guid.NewGuid().ToString());

            Directory.CreateDirectory(functionTestDir);
            string logDir     = Path.Combine(_fixture.TestLogsRoot, Guid.NewGuid().ToString());
            string secretsDir = Path.Combine(_fixture.TestSecretsRoot, Guid.NewGuid().ToString());

            ScriptHostConfiguration config = new ScriptHostConfiguration
            {
                RootLogPath     = logDir,
                RootScriptPath  = functionTestDir,
                FileLoggingMode = FileLoggingMode.Always,
            };

            ISecretsRepository repository      = new FileSystemSecretsRepository(_secretsDirectory.Path);
            SecretManager      secretManager   = new SecretManager(_settingsManager, repository, NullTraceWriter.Instance, null);
            WebHostSettings    webHostSettings = new WebHostSettings();

            webHostSettings.SecretsPath = _secretsDirectory.Path;

            var mockEventManager = new Mock <IScriptEventManager>();
            var factoryMock      = new Mock <IScriptHostFactory>();
            int count            = 0;

            factoryMock.Setup(p => p.Create(It.IsAny <IScriptHostEnvironment>(), It.IsAny <IScriptEventManager>(), _settingsManager, config)).Callback(() =>
            {
                count++;
            }).Throws(new Exception("Kaboom!"));

            ScriptHostManager hostManager = new WebScriptHostManager(config, new TestSecretManagerFactory(secretManager), mockEventManager.Object,
                                                                     _settingsManager, webHostSettings, factoryMock.Object);

            Task runTask = Task.Run(() => hostManager.RunAndBlock());

            await TestHelpers.Await(() =>
            {
                return(count > 3);
            });

            hostManager.Stop();
            Assert.Equal(ScriptHostState.Default, hostManager.State);

            // regression test: previously on multiple restarts we were recomposing
            // the writer on each restart, resulting in a nested chain of writers
            // increasing on each restart
            Assert.Equal(typeof(SystemTraceWriter), config.TraceWriter.GetType());
        }
Beispiel #10
0
        public StandbyModeTests()
        {
            _settingsManager = ScriptSettingsManager.Instance;
            var eventManagerMock = new Mock <IScriptEventManager>();
            var routerMock       = new Mock <IWebJobsRouter>();

            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(_loggerProvider);

            _webHostResolver = new WebHostResolver(_settingsManager, new TestSecretManagerFactory(false), eventManagerMock.Object,
                                                   new WebHostSettings(), routerMock.Object, new TestLoggerProviderFactory(_loggerProvider),
                                                   loggerFactory);

            WebScriptHostManager.ResetStandbyMode();
        }
        public async Task StartAssignment_AppliesAssignmentContext()
        {
            var envValue = new
            {
                Name  = Path.GetTempFileName().Replace(".", string.Empty),
                Value = Guid.NewGuid().ToString()
            };

            _settingsManager.SetSetting(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1");
            WebScriptHostManager.ResetStandbyMode();
            var context = new HostAssignmentContext
            {
                Environment = new Dictionary <string, string>
                {
                    { envValue.Name, envValue.Value }
                }
            };
            bool result = _instanceManager.StartAssignment(context);

            Assert.True(result);
            Assert.True(WebScriptHostManager.InStandbyMode);

            // specialization is done in the background
            await Task.Delay(500);

            var value = Environment.GetEnvironmentVariable(envValue.Name);

            Assert.Equal(value, envValue.Value);

            // verify logs
            var logs = _loggerProvider.GetAllLogMessages().Select(p => p.FormattedMessage).ToArray();

            Assert.Collection(logs,
                              p => Assert.StartsWith("Starting Assignment", p),
                              p => Assert.StartsWith("Applying 1 app setting(s)", p),
                              p => Assert.StartsWith("Triggering specialization", p));

            // calling again should return false, since we're no longer
            // in placeholder mode
            _loggerProvider.ClearAllLogMessages();
            result = _instanceManager.StartAssignment(context);
            Assert.False(result);

            logs = _loggerProvider.GetAllLogMessages().Select(p => p.FormattedMessage).ToArray();
            Assert.Collection(logs,
                              p => Assert.StartsWith("Assign called while host is not in placeholder mode", p));
        }
        internal static void Initialize(ContainerBuilder builder, WebHostSettings settings)
        {
            ScriptHostConfiguration scriptHostConfig = new ScriptHostConfiguration()
            {
                RootScriptPath = settings.ScriptPath,
                RootLogPath = settings.LogPath,
                FileLoggingEnabled = true
            };

            // If running on Azure Web App, derive the host ID from the site name
            string hostId = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME");
            if (!String.IsNullOrEmpty(hostId))
            {
                // Truncate to the max host name length if needed
                const int MaximumHostIdLength = 32;
                if (hostId.Length > MaximumHostIdLength)
                {
                    hostId = hostId.Substring(0, MaximumHostIdLength);
                }

                // Trim any trailing - as they can cause problems with queue names
                hostId = hostId.TrimEnd('-');

                scriptHostConfig.HostConfig.HostId = hostId.ToLowerInvariant();
            }

            WebScriptHostManager scriptHostManager = new WebScriptHostManager(scriptHostConfig);
            builder.RegisterInstance<WebScriptHostManager>(scriptHostManager);

            SecretManager secretManager = new SecretManager(settings.SecretsPath);
            // Make sure that host secrets get created on startup if they don't exist
            secretManager.GetHostSecrets();
            builder.RegisterInstance<SecretManager>(secretManager);

            WebHookReceiverManager webHookReceiverManager = new WebHookReceiverManager(secretManager);
            builder.RegisterInstance<WebHookReceiverManager>(webHookReceiverManager);

            if (!settings.IsSelfHost)
            {
                HostingEnvironment.QueueBackgroundWorkItem((ct) => scriptHostManager.RunAndBlock(ct));
            }
            else
            {
                Task.Run(() => scriptHostManager.RunAndBlock());
            }
        }
Beispiel #13
0
        public async Task DelayUntilHostReady_HostNotRunning_Returns503()
        {
            var settingsManager = ScriptSettingsManager.Instance;
            var eventManager    = new Mock <IScriptEventManager>();
            var managerMock     = new Mock <WebScriptHostManager>(MockBehavior.Strict, new ScriptHostConfiguration(),
                                                                  new TestSecretManagerFactory(), eventManager.Object, settingsManager, new WebHostSettings {
                SecretsPath = _secretsDirectory.Path
            },
                                                                  null, NullLoggerFactory.Instance, null, null, null, null, null, 1, 50);

            managerMock.SetupGet(p => p.State).Returns(ScriptHostState.Default);
            managerMock.SetupGet(p => p.LastError).Returns((Exception)null);

            var ex = await Assert.ThrowsAsync <HttpException>(async() => await WebScriptHostManager.DelayUntilHostReady(managerMock.Object, 1, 50));

            Assert.Equal(HttpStatusCode.ServiceUnavailable, (HttpStatusCode)ex.StatusCode);
        }
Beispiel #14
0
        public async Task Warmup_Succeeds()
        {
            using (new TestEnvironment())
            {
                var settings         = GetWebHostSettings();
                var eventManagerMock = new Mock <IScriptEventManager>();
                await WebScriptHostManager.WarmUp(settings, eventManagerMock.Object);

                var hostLogPath = Path.Combine(settings.LogPath, @"host");
                var hostLogFile = Directory.GetFiles(hostLogPath).First();
                var content     = File.ReadAllText(hostLogFile);

                Assert.Contains("Warm up started", content);
                Assert.Contains("Executed 'Functions.Test-CSharp' (Succeeded, Id=", content);
                Assert.Contains("Warm up succeeded", content);
            }
        }
Beispiel #15
0
        private void DisplayHttpFunctionsInfo(HttpSelfHostConfiguration config)
        {
            WebScriptHostManager hostManager = config.DependencyResolver.GetService <WebScriptHostManager>();

            if (hostManager != null)
            {
                foreach (var function in hostManager.Instance.Functions.Where(f => f.Metadata.IsHttpFunction()))
                {
                    var httpRoute = function.Metadata.Bindings.FirstOrDefault(b => b.Type == "httpTrigger").Raw["route"]?.ToString();
                    httpRoute = httpRoute ?? function.Name;
                    var hostRoutePrefix = hostManager.Instance.ScriptConfig.HttpRoutePrefix ?? "api/";
                    hostRoutePrefix = string.IsNullOrEmpty(hostRoutePrefix) || hostRoutePrefix.EndsWith("/")
                        ? hostRoutePrefix
                        : $"{hostRoutePrefix}/";
                    ColoredConsole.WriteLine($"{TitleColor($"Http Function {function.Name}:")} {config.BaseAddress.ToString()}{hostRoutePrefix}{httpRoute}");
                }
            }
        }
        internal static void Initialize(ContainerBuilder builder)
        {
            string logFilePath;
            string scriptRootPath;
            string secretsPath;
            string home    = Environment.GetEnvironmentVariable("HOME");
            bool   isLocal = string.IsNullOrEmpty(home);

            if (isLocal)
            {
                // we're running locally
                scriptRootPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, @"..\..\sample");
                logFilePath    = Path.Combine(Path.GetTempPath(), @"Functions");
                secretsPath    = HttpContext.Current.Server.MapPath("~/App_Data/Secrets");
            }
            else
            {
                // we're running in Azure
                scriptRootPath = Path.Combine(home, @"site\wwwroot");
                logFilePath    = Path.Combine(home, @"LogFiles\Application\Functions");
                secretsPath    = Path.Combine(home, @"data\Functions\secrets");
            }

            ScriptHostConfiguration scriptHostConfig = new ScriptHostConfiguration()
            {
                RootScriptPath     = scriptRootPath,
                RootLogPath        = logFilePath,
                FileLoggingEnabled = true
            };
            WebScriptHostManager scriptHostManager = new WebScriptHostManager(scriptHostConfig);

            builder.RegisterInstance <WebScriptHostManager>(scriptHostManager);

            SecretManager secretManager = new SecretManager(secretsPath);

            builder.RegisterInstance <SecretManager>(secretManager);

            WebHookReceiverManager webHookRecieverManager = new WebHookReceiverManager(secretManager);

            builder.RegisterInstance <WebHookReceiverManager>(webHookRecieverManager);

            Task.Run(() => scriptHostManager.RunAndBlock(CancellationToken.None));
        }
        private async Task <WebScriptHostManager> CreateAndStartWebScriptHostManager(TraceWriter traceWriter)
        {
            var functions = new Collection <string> {
                "TimeoutToken"
            };

            ScriptHostConfiguration config = new ScriptHostConfiguration()
            {
                RootScriptPath  = $@"TestScripts\CSharp",
                TraceWriter     = traceWriter,
                FileLoggingMode = FileLoggingMode.Always,
                Functions       = functions,
                FunctionTimeout = TimeSpan.FromSeconds(3)
            };

            var  manager = new WebScriptHostManager(config, new TestSecretManagerFactory(), _settingsManager, new WebHostSettings());
            Task task    = Task.Run(() => { manager.RunAndBlock(); });
            await TestHelpers.Await(() => manager.State == ScriptHostState.Running);

            return(manager);
        }
        internal static void Initialize(ContainerBuilder builder)
        {
            string logFilePath;
            string scriptRootPath;
            string secretsPath;
            string home = Environment.GetEnvironmentVariable("HOME");
            bool isLocal = string.IsNullOrEmpty(home);
            if (isLocal)
            {
                // we're running locally
                scriptRootPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, @"..\..\sample");
                logFilePath = Path.Combine(Path.GetTempPath(), @"Functions");
                secretsPath = HttpContext.Current.Server.MapPath("~/App_Data/Secrets");
            }
            else
            {
                // we're running in Azure
                scriptRootPath = Path.Combine(home, @"site\wwwroot");
                logFilePath = Path.Combine(home, @"LogFiles\Application\Functions");
                secretsPath = Path.Combine(home, @"data\Functions\secrets");
            }

            ScriptHostConfiguration scriptHostConfig = new ScriptHostConfiguration()
            {
                RootScriptPath = scriptRootPath,
                RootLogPath = logFilePath,
                FileLoggingEnabled = true
            };
            WebScriptHostManager scriptHostManager = new WebScriptHostManager(scriptHostConfig);
            builder.RegisterInstance<WebScriptHostManager>(scriptHostManager);

            SecretManager secretManager = new SecretManager(secretsPath);
            builder.RegisterInstance<SecretManager>(secretManager);

            WebHookReceiverManager webHookRecieverManager = new WebHookReceiverManager(secretManager);
            builder.RegisterInstance<WebHookReceiverManager>(webHookRecieverManager);

            Task.Run(() => scriptHostManager.RunAndBlock(CancellationToken.None));
        }
        public async Task Invoke(HttpContext context, WebScriptHostManager manager)
        {
            // flow required context through the request pipeline
            // downstream middleware and filters rely on this
            context.Items.Add(ScriptConstants.AzureFunctionsHostManagerKey, manager);
            SetRequestId(context.Request);
            await _next(context);

            IFunctionExecutionFeature functionExecution = context.Features.Get <IFunctionExecutionFeature>();

            if (functionExecution != null && !context.Response.HasStarted)
            {
                IActionResult result = await GetResultAsync(context, functionExecution);

                var actionContext = new ActionContext
                {
                    HttpContext = context
                };

                await result.ExecuteResultAsync(actionContext);
            }
        }
        public async Task Invoke(HttpContext httpContext, WebScriptHostManager manager)
        {
            using (Logger.VerifyingHostAvailabilityScope(_logger, httpContext.TraceIdentifier))
            {
                Logger.InitiatingHostAvailabilityCheck(_logger);

                bool hostReady = await manager.DelayUntilHostReady(throwOnFailure : false);

                if (!hostReady)
                {
                    Logger.HostUnavailableAfterCheck(_logger);

                    httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
                    await httpContext.Response.WriteAsync("Function host is not running.");

                    return;
                }

                Logger.HostAvailabilityCheckSucceeded(_logger);

                await _next.Invoke(httpContext);
            }
        }
        public void AddRouteDataToRequest_AddsRequestProperty_WhenRouteDataNotNull()
        {
            var mockRouteData = new Mock <IHttpRouteData>(MockBehavior.Strict);
            IDictionary <string, object> values = new Dictionary <string, object>
            {
                { "p1", "abc" },
                { "p2", 123 },
                { "p3", null },
                { "p4", RouteParameter.Optional }
            };

            mockRouteData.Setup(p => p.Values).Returns(values);
            HttpRequestMessage request = new HttpRequestMessage();

            WebScriptHostManager.AddRouteDataToRequest(mockRouteData.Object, request);

            var result = (IDictionary <string, object>)request.Properties[HttpExtensionConstants.AzureWebJobsHttpRouteDataKey];

            Assert.Equal(result["p1"], "abc");
            Assert.Equal(result["p2"], 123);
            Assert.Equal(result["p3"], null);
            Assert.Equal(result["p4"], null);
        }
Beispiel #22
0
        public async Task Invoke(HttpContext context, WebScriptHostManager manager)
        {
            // flow required context through the request pipeline
            // downstream middleware and filters rely on this
            context.Items.Add(ScriptConstants.AzureFunctionsHostManagerKey, manager);
            SetRequestId(context.Request);
            if (_next != null)
            {
                await _next(context);
            }

            IFunctionExecutionFeature functionExecution = context.Features.Get <IFunctionExecutionFeature>();

            int nestedProxiesCount = GetNestedProxiesCount(context, functionExecution);

            IActionResult result = null;

            if (functionExecution != null && !context.Response.HasStarted)
            {
                result = await GetResultAsync(context, functionExecution);

                if (nestedProxiesCount > 0)
                {
                    // if Proxy, the rest of the pipleline will be processed bt Proxies in case there are response overrides and what not.
                    SetProxyResult(context, nestedProxiesCount, result);
                    return;
                }

                var actionContext = new ActionContext
                {
                    HttpContext = context
                };

                await result.ExecuteResultAsync(actionContext);
            }
        }
        private void DisplayHttpFunctionsInfo(WebScriptHostManager hostManager, Uri baseUri)
        {
            if (hostManager != null)
            {
                var httpFunctions = hostManager.Instance.Functions.Where(f => f.Metadata.IsHttpFunction());
                if (httpFunctions.Any())
                {
                    ColoredConsole
                    .WriteLine()
                    .WriteLine(Yellow("Http Functions:"))
                    .WriteLine();
                }

                foreach (var function in httpFunctions)
                {
                    var binding   = function.Metadata.Bindings.FirstOrDefault(b => b.Type != null && b.Type.Equals("httpTrigger", StringComparison.OrdinalIgnoreCase));
                    var httpRoute = binding?.Raw?.GetValue("route", StringComparison.OrdinalIgnoreCase)?.ToString();
                    httpRoute = httpRoute ?? function.Name;
                    var extensions = hostManager.Instance.ScriptConfig.HostConfig.GetService <IExtensionRegistry>();
                    var httpConfig = extensions.GetExtensions <IExtensionConfigProvider>().OfType <HttpExtensionConfiguration>().Single();

                    string hostRoutePrefix = "";
                    if (!function.Metadata.IsProxy)
                    {
                        hostRoutePrefix = httpConfig.RoutePrefix ?? "api/";
                        hostRoutePrefix = string.IsNullOrEmpty(hostRoutePrefix) || hostRoutePrefix.EndsWith("/")
                            ? hostRoutePrefix
                            : $"{hostRoutePrefix}/";
                    }
                    var url = $"{baseUri.ToString().Replace("0.0.0.0", "localhost")}{hostRoutePrefix}{httpRoute}";
                    ColoredConsole
                    .WriteLine($"\t{Yellow($"{function.Name}:")} {Green(url)}")
                    .WriteLine();
                }
            }
        }
        public async Task StartAssignment_AppliesAssignmentContext()
        {
            var loggerFactory   = MockNullLogerFactory.CreateLoggerFactory();
            var settingsManager = new ScriptSettingsManager();
            var instanceManager = new InstanceManager(settingsManager, null, loggerFactory, null);
            var envValue        = new
            {
                Name  = Path.GetTempFileName().Replace(".", string.Empty),
                Value = Guid.NewGuid().ToString()
            };

            settingsManager.SetSetting(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1");
            WebScriptHostManager.ResetStandbyMode();
            var context = new HostAssignmentContext
            {
                Environment = new Dictionary <string, string>
                {
                    { envValue.Name, envValue.Value }
                }
            };
            bool result = instanceManager.StartAssignment(context);

            Assert.True(result);

            // specialization is done in the background
            await Task.Delay(500);

            var value = Environment.GetEnvironmentVariable(envValue.Name);

            Assert.Equal(value, envValue.Value);

            // calling again should return false, since we're no longer
            // in placeholder mode
            result = instanceManager.StartAssignment(context);
            Assert.False(result);
        }
        public async Task Invoke(HttpContext context, WebScriptHostManager manager)
        {
            await _next(context);

            IFunctionExecutionFeature functionExecution = context.Features.Get <IFunctionExecutionFeature>();

            if (functionExecution == null &&
                context.Request.Path.Value == "/")
            {
                IActionResult result = null;

                if (IsHomepageDisabled || context.Request.IsAntaresInternalRequest())
                {
                    result = new NoContentResult();
                }
                else
                {
                    result = new ContentResult()
                    {
                        Content     = GetHomepage(),
                        ContentType = "text/html",
                        StatusCode  = 200
                    };
                }

                if (!context.Response.HasStarted)
                {
                    var actionContext = new ActionContext
                    {
                        HttpContext = context
                    };

                    await result.ExecuteResultAsync(actionContext);
                }
            }
        }
Beispiel #26
0
 public SwaggerController(ISwaggerDocumentManager swaggerDocumentManager, WebScriptHostManager scriptHostManager, TraceWriter traceWriter)
 {
     _swaggerDocumentManager = swaggerDocumentManager;
     _scriptHostManager      = scriptHostManager;
     _traceWriter            = traceWriter.WithSource($"{ScriptConstants.TraceSourceSwagger}.Api");
 }
 public KeysController(WebScriptHostManager scriptHostManager, ISecretManager secretManager, TraceWriter traceWriter)
 {
     _scriptHostManager = scriptHostManager;
     _secretManager = secretManager;
     _traceWriter = traceWriter.WithSource($"{ScriptConstants.TraceSourceSecretManagement}.Api");
 }
Beispiel #28
0
 public AdminController(WebScriptHostManager scriptHostManager, WebHostSettings webHostSettings, TraceWriter traceWriter)
 {
     _scriptHostManager = scriptHostManager;
     _webHostSettings   = webHostSettings;
     _traceWriter       = traceWriter.WithSource($"{ScriptConstants.TraceSourceHostAdmin}.Api");
 }
 public FunctionsController(WebScriptHostManager scriptHostManager, WebHookReceiverManager webHookReceiverManager)
 {
     _scriptHostManager = scriptHostManager;
     _webHookReceiverManager = webHookReceiverManager;
 }
            public Fixture()
            {
                EventGenerator   = new TestSystemEventGenerator();
                _settingsManager = ScriptSettingsManager.Instance;

                TestFunctionRoot = Path.Combine(TestHelpers.FunctionsTestDirectory, "Functions");
                TestLogsRoot     = Path.Combine(TestHelpers.FunctionsTestDirectory, "Logs");
                TestSecretsRoot  = Path.Combine(TestHelpers.FunctionsTestDirectory, "Secrets");

                string testRoot = Path.Combine(TestFunctionRoot, Guid.NewGuid().ToString());

                SecretsPath = Path.Combine(TestSecretsRoot, Guid.NewGuid().ToString());
                Directory.CreateDirectory(SecretsPath);
                string logRoot = Path.Combine(TestLogsRoot, Guid.NewGuid().ToString(), @"Functions");

                Directory.CreateDirectory(logRoot);
                FunctionsLogDir = Path.Combine(logRoot, @"Function");
                Directory.CreateDirectory(FunctionsLogDir);

                // Add some secret files (both old and valid)
                File.WriteAllText(Path.Combine(SecretsPath, ScriptConstants.HostMetadataFileName), string.Empty);
                File.WriteAllText(Path.Combine(SecretsPath, "WebHookTrigger.json"), string.Empty);
                File.WriteAllText(Path.Combine(SecretsPath, "QueueTriggerToBlob.json"), string.Empty);
                File.WriteAllText(Path.Combine(SecretsPath, "Foo.json"), string.Empty);
                File.WriteAllText(Path.Combine(SecretsPath, "Bar.json"), string.Empty);
                File.WriteAllText(Path.Combine(SecretsPath, "Invalid.json"), string.Empty);

                // Add some old file directories
                CreateTestFunctionLogs(FunctionsLogDir, "Foo");
                CreateTestFunctionLogs(FunctionsLogDir, "Bar");
                CreateTestFunctionLogs(FunctionsLogDir, "Baz");
                CreateTestFunctionLogs(FunctionsLogDir, "Invalid");

                ScriptHostConfiguration config = new ScriptHostConfiguration
                {
                    RootScriptPath  = @"TestScripts\Node",
                    RootLogPath     = logRoot,
                    FileLoggingMode = FileLoggingMode.Always
                };

                ISecretsRepository repository      = new FileSystemSecretsRepository(SecretsPath);
                ISecretManager     secretManager   = new SecretManager(_settingsManager, repository, NullTraceWriter.Instance, null);
                WebHostSettings    webHostSettings = new WebHostSettings();

                webHostSettings.SecretsPath = SecretsPath;

                var hostConfig         = config.HostConfig;
                var testEventGenerator = new TestSystemEventGenerator();

                hostConfig.AddService <IEventGenerator>(EventGenerator);
                var mockEventManager = new Mock <IScriptEventManager>();
                var mockHostManager  = new WebScriptHostManager(config, new TestSecretManagerFactory(secretManager), mockEventManager.Object, _settingsManager, webHostSettings);

                HostManager = mockHostManager;
                Task task = Task.Run(() => { HostManager.RunAndBlock(); });

                TestHelpers.Await(() =>
                {
                    return(HostManager.State == ScriptHostState.Running);
                }).GetAwaiter().GetResult();

                // verify startup system trace logs
                string[] expectedPatterns = new string[]
                {
                    "Info Reading host configuration file",
                    "Info Host configuration file read",
                    "Info Host lock lease acquired by instance ID '(.+)'",
                    "Info Function 'Excluded' is marked as excluded",
                    @"Info Generating ([0-9]+) job function\(s\)",
                    @"Info Starting Host \(HostId=function-tests-node, Version=(.+), ProcessId=[0-9]+, Debug=False, Attempt=0\)",
                    "Info WebJobs.Indexing Found the following functions:",
                    "Info The next 5 occurrences of the schedule will be:",
                    "Info WebJobs.Host Job host started",
                    "Error The following 1 functions are in error:"
                };
                foreach (string pattern in expectedPatterns)
                {
                    Assert.True(EventGenerator.Events.Any(p => Regex.IsMatch(p, pattern)), $"Expected trace event {pattern} not found.");
                }
            }
 public EnsureHostRunningHandler()
 {
     _scriptHostManager = (WebScriptHostManager)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(WebScriptHostManager));
 }
 public FunctionsController(WebScriptHostManager scriptHostManager, WebHookReceiverManager webHookReceiverManager)
 {
     _scriptHostManager      = scriptHostManager;
     _webHookReceiverManager = webHookReceiverManager;
 }
 public AdminController(WebScriptHostManager scriptHostManager)
 {
     _scriptHostManager = scriptHostManager;
 }
Beispiel #34
0
 private void Reset()
 {
     WebScriptHostManager.ResetStandbyMode();
     _settingsManager.SetSetting(EnvironmentSettingNames.AzureWebsitePlaceholderMode, null);
 }
 public FunctionsController(IWebFunctionsManager functionsManager, WebScriptHostManager scriptHostManager, ILoggerFactory loggerFactory)
 {
     _functionsManager  = functionsManager;
     _scriptHostManager = scriptHostManager;
     _logger            = loggerFactory?.CreateLogger(ScriptConstants.LogCategoryFunctionsController);
 }
Beispiel #36
0
 public KeysController(WebScriptHostManager scriptHostManager, ISecretManager secretManager)
 {
     _scriptHostManager = scriptHostManager;
     _secretManager     = secretManager;
 }
Beispiel #37
0
 public AdminController(WebScriptHostManager scriptHostManager)
 {
     _scriptHostManager = scriptHostManager;
 }