Inheritance: ScriptHostManager
Ejemplo n.º 1
0
        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(ScriptConstants.AzureFunctionsHttpRouteDataKey));
        }
Ejemplo n.º 2
0
        // TODO: FACAVAL (WEBHOOKS)
        //public WebHookReceiverManager GetWebHookReceiverManager(WebHostSettings settings)
        //{
        //    if (_activeReceiverManager != null)
        //    {
        //        return _activeReceiverManager;
        //    }

        //    lock (_syncLock)
        //    {
        //        EnsureInitialized(settings);

        //        return _activeReceiverManager ?? _standbyReceiverManager;
        //    }
        //}

        internal void EnsureInitialized(WebHostSettings settings)
        {
            if (!WebScriptHostManager.InStandbyMode)
            {
                // standby mode can only change from true to false
                // when standby mode changes, we reset all instances
                if (_activeHostManager == null)
                {
                    _settingsManager.Reset();

                    _activeScriptHostConfig = CreateScriptHostConfiguration(settings);
                    _activeHostManager      = new WebScriptHostManager(_activeScriptHostConfig, _secretManagerFactory, _eventManager, _settingsManager, settings, _router, _loggerFactoryBuilder);
                    //_activeReceiverManager = new WebHookReceiverManager(_activeHostManager.SecretManager);
                    InitializeFileSystem();

                    if (_standbyHostManager != null)
                    {
                        // we're starting the one and only one
                        // standby mode specialization
                        _activeScriptHostConfig.TraceWriter.Info(Resources.HostSpecializationTrace);

                        // After specialization, we need to ensure that custom timezone
                        // settings configured by the user (WEBSITE_TIME_ZONE) are honored.
                        // DateTime caches timezone information, so we need to clear the cache.
                        TimeZoneInfo.ClearCachedData();
                    }

                    if (_standbyHostManager != null)
                    {
                        _standbyHostManager.Stop();
                        _standbyHostManager.Dispose();
                    }
                    //_standbyReceiverManager?.Dispose();
                    _standbyScriptHostConfig = null;
                    _standbyHostManager      = null;
                    //_standbyReceiverManager = null;
                }
            }
            else
            {
                if (_standbyHostManager == null)
                {
                    var standbySettings = CreateStandbySettings(settings);
                    _standbyScriptHostConfig = CreateScriptHostConfiguration(standbySettings, true);
                    _standbyHostManager      = new WebScriptHostManager(_standbyScriptHostConfig, _secretManagerFactory, _eventManager, _settingsManager, standbySettings, _router, _loggerFactoryBuilder);
                    // _standbyReceiverManager = new WebHookReceiverManager(_standbyHostManager.SecretManager);

                    InitializeFileSystem();
                    StandbyManager.Initialize(_standbyScriptHostConfig);
                }
            }
        }
        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();
            }

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

            WebScriptHostManager scriptHostManager = new WebScriptHostManager(scriptHostConfig, secretManager);

            builder.RegisterInstance <WebScriptHostManager>(scriptHostManager);

            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));
        }
            public Fixture()
            {
                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.Create(Path.Combine(SecretsPath, ScriptConstants.HostMetadataFileName));
                File.Create(Path.Combine(SecretsPath, "WebHookTrigger.json"));
                File.Create(Path.Combine(SecretsPath, "QueueTriggerToBlob.json"));
                File.Create(Path.Combine(SecretsPath, "Foo.json"));
                File.Create(Path.Combine(SecretsPath, "Bar.json"));
                File.Create(Path.Combine(SecretsPath, "Invalid.json"));

                // 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,
                    FileLoggingEnabled = true
                };

                SecretManager   secretManager   = new SecretManager(SecretsPath);
                WebHostSettings webHostSettings = new WebHostSettings();

                HostManager = new WebScriptHostManager(config, secretManager, webHostSettings);
                Task task = Task.Run(() => { HostManager.RunAndBlock(); });

                TestHelpers.Await(() =>
                {
                    return(HostManager.IsRunning);
                }).GetAwaiter().GetResult();
            }
            public Fixture()
            {
                string testRoot = Path.Combine(Path.GetTempPath(), "FunctionTests");

                if (Directory.Exists(testRoot))
                {
                    Directory.Delete(testRoot, recursive: true);
                }

                SecretsPath = Path.Combine(testRoot, "TestSecrets");
                Directory.CreateDirectory(SecretsPath);
                string logRoot = Path.Combine(testRoot, @"Functions");

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

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

                // 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,
                    FileLoggingEnabled = true
                };

                SecretManager secretManager = new SecretManager(SecretsPath);

                HostManager = new WebScriptHostManager(config, secretManager);
                Task task = Task.Run(() => { HostManager.RunAndBlock(); });

                TestHelpers.Await(() =>
                {
                    return(HostManager.IsRunning);
                }).GetAwaiter().GetResult();
            }
        public async Task EmptyHost_StartsSuccessfully()
        {
            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
            };
            ISecretManager    secretManager   = new SecretManager(secretsDir);
            WebHostSettings   webHostSettings = new WebHostSettings();
            ScriptHostManager hostManager     = new WebScriptHostManager(config, secretManager, webHostSettings);

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

            await TestHelpers.Await(() => hostManager.IsRunning, timeout : 10000);

            hostManager.Stop();
            Assert.False(hostManager.IsRunning);

            await Task.Delay(FileTraceWriter.LogFlushIntervalMs);

            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);
        }
        private void EnsureInitialized(WebHostSettings settings)
        {
            // standby mode can only change from true to false
            // When standby mode changes, we reset all instances
            var standbyMode = WebScriptHostManager.InStandbyMode;

            if (!standbyMode)
            {
                if (_activeHostManager == null)
                {
                    if (_standbyHostManager != null)
                    {
                        // reintialize app settings if we were in standby
                        ReinitializeAppSettings();
                    }

                    _activeScriptHostConfig = GetScriptHostConfiguration(settings.ScriptPath, settings.LogPath);
                    _activeSecretManager    = GetSecretManager(_settingsManager, settings.SecretsPath);
                    _activeReceiverManager  = new WebHookReceiverManager(_activeSecretManager);
                    _activeHostManager      = new WebScriptHostManager(_activeScriptHostConfig, _activeSecretManager, _settingsManager, settings);

                    (_standbySecretManager as IDisposable)?.Dispose();
                    _standbyHostManager?.Dispose();
                    _standbyReceiverManager?.Dispose();

                    _standbyScriptHostConfig = null;
                    _standbySecretManager    = null;
                    _standbyHostManager      = null;
                    _standbyReceiverManager  = null;
                    _settingsManager.Reset();
                }
            }
            else
            {
                if (_standbyHostManager == null)
                {
                    _standbyScriptHostConfig = GetScriptHostConfiguration(settings.ScriptPath, settings.LogPath);
                    _standbySecretManager    = GetSecretManager(_settingsManager, settings.SecretsPath);
                    _standbyReceiverManager  = new WebHookReceiverManager(_standbySecretManager);
                    _standbyHostManager      = new WebScriptHostManager(_standbyScriptHostConfig, _standbySecretManager, _settingsManager, settings);
                }
            }
        }
        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,
                RestartInterval = TimeSpan.FromMilliseconds(500)
            };
            SecretManager   secretManager   = new SecretManager(secretsDir);
            WebHostSettings webHostSettings = new WebHostSettings();
            var             factoryMock     = new Mock <IScriptHostFactory>();
            int             count           = 0;

            factoryMock.Setup(p => p.Create(config)).Callback(() =>
            {
                count++;
            }).Throws(new Exception("Kaboom!"));

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

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

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

            hostManager.Stop();
            Assert.False(hostManager.IsRunning);

            // 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());
        }
Ejemplo n.º 10
0
        public static void Reset()
        {
            _standbySecretManager?.Dispose();
            _standbyHostManager?.Dispose();
            _standbyReceiverManager?.Dispose();

            _standbyScriptHostConfig = null;
            _standbySecretManager    = null;
            _standbyHostManager      = null;
            _standbyReceiverManager  = null;

            _activeSecretManager?.Dispose();
            _activeHostManager?.Dispose();
            _activeReceiverManager?.Dispose();

            _activeScriptHostConfig = null;
            _activeSecretManager    = null;
            _activeHostManager      = null;
            _activeReceiverManager  = null;
        }
        internal void EnsureInitialized(WebHostSettings settings)
        {
            if (!WebScriptHostManager.InStandbyMode)
            {
                // standby mode can only change from true to false
                // When standby mode changes, we reset all instances
                if (_activeHostManager == null)
                {
                    _activeScriptHostConfig = CreateScriptHostConfiguration(settings);
                    _activeHostManager      = new WebScriptHostManager(_activeScriptHostConfig, _secretManagerFactory, _eventManager, _settingsManager, settings);
                    _activeReceiverManager  = new WebHookReceiverManager(_activeHostManager.SecretManager);
                    InitializeFileSystem();

                    if (_standbyHostManager != null)
                    {
                        // we're undergoing the one and only one
                        // standby mode specialization
                        _activeScriptHostConfig.TraceWriter.Info(Resources.HostSpecializationTrace);
                    }

                    _standbyHostManager?.Dispose();
                    _standbyReceiverManager?.Dispose();
                    _standbyScriptHostConfig = null;
                    _standbyHostManager      = null;
                    _standbyReceiverManager  = null;
                    _settingsManager.Reset();
                }
            }
            else
            {
                if (_standbyHostManager == null)
                {
                    _standbyScriptHostConfig = CreateScriptHostConfiguration(settings, true);
                    _standbyHostManager      = new WebScriptHostManager(_standbyScriptHostConfig, _secretManagerFactory, _eventManager, _settingsManager, settings);
                    _standbyReceiverManager  = new WebHookReceiverManager(_standbyHostManager.SecretManager);

                    InitializeFileSystem();
                    StandbyManager.Initialize(_standbyScriptHostConfig);
                }
            }
        }
        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 SecretManager(), new WebHostSettings());
            Task task    = Task.Run(() => { manager.RunAndBlock(); });
            await TestHelpers.Await(() => manager.IsRunning);

            return(manager);
        }
        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[ScriptConstants.AzureFunctionsHttpRouteDataKey];

            Assert.Equal(result["p1"], "abc");
            Assert.Equal(result["p2"], 123);
            Assert.Equal(result["p3"], null);
            Assert.Equal(result["p4"], null);
        }
        /// <summary>
        /// This method ensures that all services managed by this class are initialized
        /// correctly taking into account specialization state transitions.
        /// </summary>
        internal void EnsureInitialized(WebHostSettings settings)
        {
            // Create a logger that we can use when the host isn't yet initialized.
            ILogger logger = _loggerFactory.CreateLogger(LogCategories.Startup);

            lock (_syncLock)
            {
                // Determine whether we should do normal or standby initialization
                if (!WebScriptHostManager.InStandbyMode)
                {
                    // We're not in standby mode. There are two cases to consider:
                    // 1) We _were_ in standby mode and now we're ready to specialize
                    // 2) We're doing non-specialization normal initialization
                    if (_activeHostManager == null &&
                        (_standbyHostManager == null || _settingsManager.ContainerReady))
                    {
                        _settingsManager.Reset();
                        _specializationTimer?.Dispose();
                        _specializationTimer = null;

                        _activeScriptHostConfig = CreateScriptHostConfiguration(settings);
                        _activeHostManager      = new WebScriptHostManager(_activeScriptHostConfig, _secretManagerFactory, _eventManager, _settingsManager, settings,
                                                                           _router, loggerProviderFactory: _loggerProviderFactory, loggerFactory: _loggerFactory);
                        //_activeReceiverManager = new WebHookReceiverManager(_activeHostManager.SecretManager);
                        InitializeFileSystem(settings, _settingsManager.FileSystemIsReadOnly);

                        if (_standbyHostManager != null)
                        {
                            // we're starting the one and only one
                            // standby mode specialization
                            logger.LogInformation(Resources.HostSpecializationTrace);

                            // After specialization, we need to ensure that custom timezone
                            // settings configured by the user (WEBSITE_TIME_ZONE) are honored.
                            // DateTime caches timezone information, so we need to clear the cache.
                            TimeZoneInfo.ClearCachedData();
                        }

                        if (_standbyHostManager != null)
                        {
                            _standbyHostManager.Stop();
                            _standbyHostManager.Dispose();
                        }
                        //_standbyReceiverManager?.Dispose();
                        _standbyScriptHostConfig = null;
                        _standbyHostManager      = null;
                        //_standbyReceiverManager = null;
                    }
                }
                else
                {
                    // We're in standby (placeholder) mode. Initialize the standby services.
                    if (_standbyHostManager == null)
                    {
                        var standbySettings = CreateStandbySettings(settings);
                        _standbyScriptHostConfig = CreateScriptHostConfiguration(standbySettings, true);
                        _standbyHostManager      = new WebScriptHostManager(_standbyScriptHostConfig, _secretManagerFactory, _eventManager, _settingsManager, standbySettings,
                                                                            _router, loggerProviderFactory: _loggerProviderFactory, loggerFactory: _loggerFactory);
                        // _standbyReceiverManager = new WebHookReceiverManager(_standbyHostManager.SecretManager);

                        InitializeFileSystem(settings, _settingsManager.FileSystemIsReadOnly);
                        StandbyManager.Initialize(_standbyScriptHostConfig, logger);

                        // start a background timer to identify when specialization happens
                        // specialization usually happens via an http request (e.g. scale controller
                        // ping) but this timer is started as well to handle cases where we
                        // might not receive a request
                        _specializationTimer = new Timer(OnSpecializationTimerTick, settings, 1000, 1000);
                    }
                }
            }
        }
            public Fixture()
            {
                EventGenerator = new TestSystemEventGenerator();

                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
                };

                ISecretManager  secretManager   = new SecretManager(SecretsPath);
                WebHostSettings webHostSettings = new WebHostSettings();

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

                hostConfig.AddService <IEventGenerator>(EventGenerator);
                var mockHostManager = new WebScriptHostManager(config, secretManager, webHostSettings);

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

                TestHelpers.Await(() =>
                {
                    return(HostManager.IsRunning);
                }).GetAwaiter().GetResult();

                // verify startup system trace logs
                string[] expectedPatterns = new string[]
                {
                    "Info Reading host configuration file",
                    "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\)",
                    "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.");
                }
            }
        internal async Task GeneratedMethods_WithOutParams_DoNotCauseDeadlocks(string fixture)
        {
            var traceWriter = new TestTraceWriter(TraceLevel.Verbose);

            ScriptHostConfiguration config = new ScriptHostConfiguration()
            {
                RootScriptPath = @"TestScripts\FunctionGeneration",
                TraceWriter = traceWriter
            };

            string secretsPath = Path.Combine(Path.GetTempPath(), @"FunctionTests\Secrets");
            WebHostSettings webHostSettings = new WebHostSettings();
            var secretManager = new SecretManager(SettingsManager, secretsPath, NullTraceWriter.Instance);

            using (var manager = new WebScriptHostManager(config, new TestSecretManagerFactory(secretManager), SettingsManager, webHostSettings))
            {
                Thread runLoopThread = new Thread(_ =>
                {
                    manager.RunAndBlock(CancellationToken.None);
                });
                runLoopThread.IsBackground = true;
                runLoopThread.Start();

                await TestHelpers.Await(() =>
                {
                    return manager.State == ScriptHostState.Running;
                });

                var request = new HttpRequestMessage(HttpMethod.Get, String.Format("http://localhost/api/httptrigger-{0}", fixture));
                FunctionDescriptor function = manager.GetHttpFunctionOrNull(request);

                SynchronizationContext currentContext = SynchronizationContext.Current;
                var resetEvent = new ManualResetEventSlim();

                try
                {
                    var requestThread = new Thread(() =>
                    {
                        var context = new SingleThreadSynchronizationContext();
                        SynchronizationContext.SetSynchronizationContext(context);

                        manager.HandleRequestAsync(function, request, CancellationToken.None)
                        .ContinueWith(task => resetEvent.Set());

                        Thread.Sleep(500);
                        context.Run();
                    });

                    requestThread.IsBackground = true;
                    requestThread.Start();

                    bool threadSignaled = resetEvent.Wait(TimeSpan.FromSeconds(10));

                    requestThread.Abort();

                    Assert.True(threadSignaled, "Thread execution did not complete");
                }
                finally
                {
                    SynchronizationContext.SetSynchronizationContext(currentContext);
                    manager.Stop();
                }
            }
        }
Ejemplo n.º 17
0
        public static async Task <HttpResponseMessage> WarmUp(HttpRequestMessage request, WebScriptHostManager scriptHostManager)
        {
            var    queryParams = request.GetQueryParameterDictionary();
            string value       = null;

            if (queryParams.TryGetValue("restart", out value) && string.Compare("1", value) == 0)
            {
                scriptHostManager.RestartHost();
                await scriptHostManager.DelayUntilHostReady();
            }

            await StandbyManager.WarmUp(scriptHostManager.Instance);

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
        private void EnsureInitialized(WebHostSettings settings)
        {
            // standby mode can only change from true to false
            // When standby mode changes, we reset all instances
            var standbyMode = WebScriptHostManager.InStandbyMode;
            if (!standbyMode)
            {
                if (_activeHostManager == null)
                {
                    if (_standbyHostManager != null)
                    {
                        // reintialize app settings if we were in standby
                        ReinitializeAppSettings();
                    }

                    _activeScriptHostConfig = GetScriptHostConfiguration(settings.ScriptPath, settings.LogPath);

                    _activeHostManager = new WebScriptHostManager(_activeScriptHostConfig, _secretManagerFactory, _settingsManager, settings);
                    _activeReceiverManager = new WebHookReceiverManager(_activeHostManager.SecretManager);

                    _standbyHostManager?.Dispose();
                    _standbyReceiverManager?.Dispose();

                    _standbyScriptHostConfig = null;
                    _standbyHostManager = null;
                    _standbyReceiverManager = null;
                    _settingsManager.Reset();
                }
            }
            else
            {
                if (_standbyHostManager == null)
                {
                    _standbyScriptHostConfig = GetScriptHostConfiguration(settings.ScriptPath, settings.LogPath);

                    _standbyHostManager = new WebScriptHostManager(_standbyScriptHostConfig, _secretManagerFactory, _settingsManager, settings);
                    _standbyReceiverManager = new WebHookReceiverManager(_standbyHostManager.SecretManager);
                }
            }
        }