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