public WebFunctionsManager(IOptions <ScriptApplicationHostOptions> applicationHostOptions, IOptions <LanguageWorkerOptions> languageWorkerOptions, ILoggerFactory loggerFactory, HttpClient client) { _hostOptions = applicationHostOptions.Value.ToHostOptions(); _logger = loggerFactory?.CreateLogger(ScriptConstants.LogCategoryHostGeneral); _client = client; _workerConfigs = languageWorkerOptions.Value.WorkerConfigs; }
private static IFunctionDispatcher GetTestFunctionDispatcherWithMockLanguageWorkerChannelManager(string maxProcessCountValue = null, bool addWebhostChannel = false) { var eventManager = new ScriptEventManager(); var scriptJobHostEnvironment = new Mock <IScriptJobHostEnvironment>(); var metricsLogger = new Mock <IMetricsLogger>(); var testEnv = new TestEnvironment(); if (!string.IsNullOrEmpty(maxProcessCountValue)) { testEnv.SetEnvironmentVariable(LanguageWorkerConstants.FunctionsWorkerProcessCountSettingName, maxProcessCountValue); } var loggerFactory = MockNullLoggerFactory.CreateLoggerFactory(); var testLogger = new TestLogger("FunctionDispatcherTests"); var options = new ScriptJobHostOptions { RootLogPath = Path.GetTempPath() }; IOptions <ScriptJobHostOptions> scriptOptions = new OptionsManager <ScriptJobHostOptions>(new TestOptionsFactory <ScriptJobHostOptions>(options)); var workerConfigOptions = new LanguageWorkerOptions { WorkerConfigs = TestHelpers.GetTestWorkerConfigs() }; var languageWorkerChannelManager = new Mock <ILanguageWorkerChannelManager>(); var mockFunctionDispatcherLoadBalancer = new Mock <IFunctionDispatcherLoadBalancer>(); return(new FunctionDispatcher(scriptOptions, metricsLogger.Object, testEnv, scriptJobHostEnvironment.Object, eventManager, loggerFactory, new OptionsWrapper <LanguageWorkerOptions>(workerConfigOptions), languageWorkerChannelManager.Object, null, mockFunctionDispatcherLoadBalancer.Object)); }
public WorkerFunctionDescriptorProvider(ScriptHost host, ScriptJobHostOptions config, ICollection <IScriptBindingProvider> bindingProviders, IFunctionInvocationDispatcher dispatcher, ILoggerFactory loggerFactory) : base(host, config, bindingProviders) { _dispatcher = dispatcher; _loggerFactory = loggerFactory; }
public void Configure_FileWatching() { var settings = new Dictionary <string, string> { { ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "fileWatchingEnabled"), "true" } }; ScriptHostOptionsSetup setup = CreateSetupWithConfiguration(settings); var options = new ScriptJobHostOptions(); // Validate default (this should be in another test - migrated here for now) Assert.True(options.FileWatchingEnabled); setup.Configure(options); Assert.True(options.FileWatchingEnabled); Assert.Equal(1, options.WatchDirectories.Count); Assert.Equal("node_modules", options.WatchDirectories.ElementAt(0)); Assert.Equal(3, options.WatchFiles.Count); Assert.Contains("host.json", options.WatchFiles); Assert.Contains("function.json", options.WatchFiles); Assert.Contains("proxies.json", options.WatchFiles); // File watching disabled settings[ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "fileWatchingEnabled")] = bool.FalseString; setup = CreateSetupWithConfiguration(settings); options = new ScriptJobHostOptions(); setup.Configure(options); Assert.False(options.FileWatchingEnabled); // File watching enabled, watch directories settings[ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "fileWatchingEnabled")] = bool.TrueString; settings[ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "watchDirectories", "0")] = "Shared"; settings[ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "watchDirectories", "1")] = "Tools"; settings[ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "watchFiles", "0")] = "myFirstFile.ext"; settings[ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "watchFiles", "1")] = "mySecondFile.ext"; setup = CreateSetupWithConfiguration(settings); options = new ScriptJobHostOptions(); setup.Configure(options); Assert.True(options.FileWatchingEnabled); Assert.Equal(3, options.WatchDirectories.Count); Assert.Equal("node_modules", options.WatchDirectories.ElementAt(0)); Assert.Equal("Shared", options.WatchDirectories.ElementAt(1)); Assert.Equal("Tools", options.WatchDirectories.ElementAt(2)); Assert.Equal(5, options.WatchFiles.Count); Assert.Contains("host.json", options.WatchFiles); Assert.Contains("function.json", options.WatchFiles); Assert.Contains("proxies.json", options.WatchFiles); Assert.Contains("myFirstFile.ext", options.WatchFiles); Assert.Contains("mySecondFile.ext", options.WatchFiles); }
public void CreateLogger_UsesSameFileWriter_ForSameFile() { var options = new ScriptJobHostOptions { RootLogPath = Path.GetTempPath() }; var fileStatus = new Mock <IFileLoggingStatusManager>(); var primaryStatus = new Mock <IPrimaryHostStateProvider>(); using (var provider = new FunctionFileLoggerProvider(new OptionsWrapper <ScriptJobHostOptions>(options), fileStatus.Object, primaryStatus.Object)) { provider.CreateLogger(LogCategories.CreateFunctionCategory("Test1")); provider.CreateLogger(LogCategories.CreateFunctionUserCategory("Test1")); provider.CreateLogger(LogCategories.CreateFunctionCategory("Test1")); Assert.Single(provider.FileWriterCache); // This creates a new entry. provider.CreateLogger(LogCategories.CreateFunctionCategory("Test2")); Assert.Equal(2, provider.FileWriterCache.Count); Assert.NotSame( provider.FileWriterCache[Path.Combine("Function", "Test1")], provider.FileWriterCache[Path.Combine("Function", "Test2")]); } }
public ProxyFunctionDescriptorProvider(ScriptHost host, ScriptJobHostOptions config, ICollection <IScriptBindingProvider> bindingProviders, ProxyClientExecutor proxyClient, ILoggerFactory loggerFactory) : base(host, config, bindingProviders) { _proxyClient = proxyClient; _loggerFactory = loggerFactory; }
public FileMonitoringService(IOptions <ScriptJobHostOptions> scriptOptions, ILoggerFactory loggerFactory, IScriptEventManager eventManager, IApplicationLifetime applicationLifetime, IScriptHostManager scriptHostManager, IEnvironment environment) { _scriptOptions = scriptOptions.Value; _eventManager = eventManager; _applicationLifetime = applicationLifetime; _scriptHostManager = scriptHostManager; _hostLogPath = Path.Combine(_scriptOptions.RootLogPath, "Host"); _logger = loggerFactory.CreateLogger(LogCategories.Startup); _environment = environment; // Use this for newer logs as we can't change existing categories of log messages _typedLogger = loggerFactory.CreateLogger <FileMonitoringService>(); // If a file change should result in a restart, we debounce the event to // ensure that only a single restart is triggered within a specific time window. // This allows us to deal with a large set of file change events that might // result from a bulk copy/unzip operation. In such cases, we only want to // restart after ALL the operations are complete and there is a quiet period. _restart = RestartAsync; _restart = _restart.Debounce(500); _shutdown = Shutdown; _shutdown = _shutdown.Debounce(milliseconds: 500); _rootDirectorySnapshot = GetDirectorySnapshot(); }
internal static Collection <FunctionBinding> GetBindings(ScriptJobHostOptions config, IEnumerable <IScriptBindingProvider> bindingProviders, IEnumerable <BindingMetadata> bindingMetadataCollection, FileAccess fileAccess) { Collection <FunctionBinding> bindings = new Collection <FunctionBinding>(); if (bindings != null) { foreach (var bindingMetadata in bindingMetadataCollection) { string type = bindingMetadata.Type.ToLowerInvariant(); switch (type) { case "http": if (fileAccess != FileAccess.Write) { throw new InvalidOperationException("Http binding can only be used for output."); } bindings.Add(new HttpBinding(config, bindingMetadata, FileAccess.Write)); break; default: FunctionBinding binding = null; if (TryParseFunctionBinding(config, bindingProviders, bindingMetadata.Raw, out binding)) { bindings.Add(binding); } break; } } } return(bindings); }
public static FunctionMetadata GetFunctionMetadata(string functionName) { var functionErrors = new Dictionary <string, Collection <string> >(); var scriptHostOptions = new ScriptJobHostOptions { RootScriptPath = Environment.CurrentDirectory }; var loggerFactory = new LoggerFactory(); var languageWorkerOptions = new LanguageWorkerOptions { }; loggerFactory.AddProvider(new ColoredConsoleLoggerProvider((cat, level) => level >= LogLevel.Information)); var metadataManager = new FunctionMetadataManager(new OptionsWrapper <ScriptJobHostOptions>(scriptHostOptions), new OptionsWrapper <LanguageWorkerOptions>(languageWorkerOptions), loggerFactory); var function = metadataManager.Functions.FirstOrDefault(f => f.Name.Equals(functionName, StringComparison.OrdinalIgnoreCase)); if (function == null) { var error = metadataManager.Errors .FirstOrDefault(f => f.Key.Equals(functionName, StringComparison.OrdinalIgnoreCase)) .Value .Aggregate(string.Empty, (a, b) => string.Join(Environment.NewLine, a, b)); throw new FunctionNotFoundException($"Unable to get metadata for function {functionName}. Error: {error}"); } else { return(function); } }
private static bool TryParseFunctionBinding(ScriptJobHostOptions config, IEnumerable <IScriptBindingProvider> bindingProviders, JObject metadata, out FunctionBinding functionBinding) { functionBinding = null; ScriptBindingContext bindingContext = new ScriptBindingContext(metadata); ScriptBinding scriptBinding = null; foreach (var provider in bindingProviders) { if (provider.TryCreate(bindingContext, out scriptBinding)) { break; } } if (scriptBinding == null) { return(false); } BindingMetadata bindingMetadata = BindingMetadata.Create(metadata); functionBinding = new ExtensionBinding(config, scriptBinding, bindingMetadata); return(true); }
public HttpWorkerOptionsSetup(IOptions <ScriptJobHostOptions> scriptJobHostOptions, IConfiguration configuration, ILoggerFactory loggerFactory, IMetricsLogger metricsLogger) { _scriptJobHostOptions = scriptJobHostOptions.Value; _configuration = configuration; _metricsLogger = metricsLogger; _logger = loggerFactory.CreateLogger <HttpWorkerOptionsSetup>(); }
public HttpWorkerOptionsSetupTests() { _testLoggerProvider = new TestLoggerProvider(); _testLoggerFactory = new LoggerFactory(); _testLoggerFactory.AddProvider(_testLoggerProvider); _scriptJobHostOptions = new ScriptJobHostOptions() { RootScriptPath = $@"TestScripts\CSharp", FileLoggingMode = FileLoggingMode.Always, FunctionTimeout = TimeSpan.FromSeconds(3) }; _rootPath = Path.Combine(Environment.CurrentDirectory, "HttpWorkerOptionsSetupTests"); if (!Directory.Exists(_rootPath)) { Directory.CreateDirectory(_rootPath); } _options = new ScriptApplicationHostOptions { ScriptPath = _rootPath }; _hostJsonFile = Path.Combine(_rootPath, "host.json"); if (File.Exists(_hostJsonFile)) { File.Delete(_hostJsonFile); } }
public async Task ToFunctionTrigger_Codeless_ReturnsExpected() { var functionMetadata = new FunctionMetadata { Name = "TestFunction1" }; var options = new ScriptJobHostOptions { RootScriptPath = _testRootScriptPath }; functionMetadata.SetIsCodeless(true); JObject functionConfig = JObject.Parse(_sampleBindingsJson); JArray bindingArray = (JArray)functionConfig["bindings"]; foreach (JObject binding in bindingArray) { BindingMetadata bindingMetadata = BindingMetadata.Create(binding); functionMetadata.Bindings.Add(bindingMetadata); } var result = await functionMetadata.ToFunctionTrigger(options); Assert.Equal("TestFunction1", result["functionName"].Value <string>()); Assert.Equal("httpTrigger", result["type"].Value <string>()); // make sure original binding did not change Assert.Null(functionMetadata.Bindings[0].Raw["functionName"]?.Value <string>()); Assert.Equal("httpTrigger", functionMetadata.Bindings[0].Raw["type"].Value <string>()); }
public WebFunctionsManager(IOptions <ScriptApplicationHostOptions> webSettings, IOptions <LanguageWorkerOptions> workerConfigOptions, ILoggerFactory loggerFactory, HttpClient client) { _config = webSettings.Value.ToScriptHostConfiguration(); _logger = loggerFactory?.CreateLogger(ScriptConstants.LogCategoryKeysController); _client = client; _workerConfigs = workerConfigOptions.Value.WorkerConfigs; }
public WebFunctionsManager(IOptions <ScriptApplicationHostOptions> applicationHostOptions, IOptions <LanguageWorkerOptions> languageWorkerOptions, ILoggerFactory loggerFactory, HttpClient client, IProxyMetadataManager proxyMetadataManager) { _hostOptions = applicationHostOptions.Value.ToHostOptions(); _logger = loggerFactory?.CreateLogger(ScriptConstants.LogCategoryKeysController); _client = client; _workerConfigs = languageWorkerOptions.Value.WorkerConfigs; _proxyMetadataManager = proxyMetadataManager; }
public DotNetFunctionDescriptorProvider(ScriptHost host, ScriptJobHostOptions config, ICollection <IScriptBindingProvider> bindingProviders, ICompilationServiceFactory <ICompilationService <IDotNetCompilation>, IFunctionMetadataResolver> compilationServiceFactory, IMetricsLogger metricsLogger, ILoggerFactory loggerFactory) : base(host, config, bindingProviders) { _metricsLogger = metricsLogger; _loggerFactory = loggerFactory; _compilationServiceFactory = compilationServiceFactory; }
private static async Task <string> GetTestData(string testDataPath, ScriptJobHostOptions config) { if (!File.Exists(testDataPath)) { await FileUtility.WriteAsync(testDataPath, string.Empty); } return(await FileUtility.ReadAsync(testDataPath)); }
public SystemLoggerProviderTests() { var scriptOptions = new ScriptJobHostOptions { RootLogPath = Path.GetTempPath() }; _options = new OptionsWrapper <ScriptJobHostOptions>(scriptOptions); }
public async Task Initialize_LogsWarningForExplicitlySetHostId() { var loggerProvider = new TestLoggerProvider(); var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(loggerProvider); string rootPath = Path.Combine(Environment.CurrentDirectory, "ScriptHostTests_Initialize_LogsWarningForExplicitlySetHostId"); if (!Directory.Exists(rootPath)) { Directory.CreateDirectory(rootPath); } // Set id in the host.json string hostJsonContent = @" { 'version': '2.0', 'id': 'foobar' }"; File.WriteAllText(Path.Combine(rootPath, "host.json"), hostJsonContent); var config = new ScriptJobHostOptions() { RootScriptPath = rootPath }; var host = new HostBuilder() .ConfigureDefaultTestWebScriptHost(_ => { }, options => { options.ScriptPath = rootPath; options.LogPath = Path.GetTempPath(); }, false, rootServices => { rootServices.AddSingleton <ILoggerFactory>(loggerFactory); }) .Build(); await host.StartAsync(); var idProvider = host.Services.GetService <IHostIdProvider>(); string hostId = await idProvider.GetHostIdAsync(CancellationToken.None); await host.StopAsync(); host.Dispose(); Assert.Matches("foobar", hostId); // We should have a warning for host id in the start up logger var logger = loggerProvider.CreatedLoggers.First(x => x.Category == "Host.Startup"); Assert.Single(logger.GetLogMessages(), x => x.FormattedMessage.Contains("Host id explicitly set in the host.json.")); }
public WorkerFunctionDescriptorProvider(ScriptHost host, ScriptJobHostOptions config, ICollection <IScriptBindingProvider> bindingProviders, IFunctionInvocationDispatcher dispatcher, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime, TimeSpan workerInitializationTimeout) : base(host, config, bindingProviders) { _dispatcher = dispatcher; _loggerFactory = loggerFactory; _applicationLifetime = applicationLifetime; _workerInitializationTimeout = workerInitializationTimeout; }
private ScriptJobHostOptions GetConfiguredOptions(Dictionary <string, string> settings, IEnvironment environment = null) { ScriptHostOptionsSetup setup = CreateSetupWithConfiguration(settings, environment); var options = new ScriptJobHostOptions(); setup.Configure(options); return(options); }
private static RpcFunctionInvocationDispatcher GetTestFunctionDispatcher(string maxProcessCountValue = null, bool addWebhostChannel = false, Mock <IWebHostRpcWorkerChannelManager> mockwebHostLanguageWorkerChannelManager = null, bool throwOnProcessStartUp = false) { var eventManager = new ScriptEventManager(); var metricsLogger = new Mock <IMetricsLogger>(); var mockApplicationLifetime = new Mock <IApplicationLifetime>(); var testEnv = new TestEnvironment(); if (!string.IsNullOrEmpty(maxProcessCountValue)) { testEnv.SetEnvironmentVariable(RpcWorkerConstants.FunctionsWorkerProcessCountSettingName, maxProcessCountValue); } var loggerFactory = MockNullLoggerFactory.CreateLoggerFactory(); var options = new ScriptJobHostOptions { RootLogPath = Path.GetTempPath() }; IOptions <ScriptJobHostOptions> scriptOptions = new OptionsManager <ScriptJobHostOptions>(new TestOptionsFactory <ScriptJobHostOptions>(options)); var workerConfigOptions = new LanguageWorkerOptions { WorkerConfigs = TestHelpers.GetTestWorkerConfigs() }; IRpcWorkerChannelFactory testLanguageWorkerChannelFactory = new TestRpcWorkerChannelFactory(eventManager, _testLogger, scriptOptions.Value.RootScriptPath, throwOnProcessStartUp); IWebHostRpcWorkerChannelManager testWebHostLanguageWorkerChannelManager = new TestRpcWorkerChannelManager(eventManager, _testLogger, scriptOptions.Value.RootScriptPath, testLanguageWorkerChannelFactory); IJobHostRpcWorkerChannelManager jobHostLanguageWorkerChannelManager = new JobHostRpcWorkerChannelManager(loggerFactory); if (addWebhostChannel) { testWebHostLanguageWorkerChannelManager.InitializeChannelAsync("java"); } if (mockwebHostLanguageWorkerChannelManager != null) { testWebHostLanguageWorkerChannelManager = mockwebHostLanguageWorkerChannelManager.Object; } var mockFunctionDispatcherLoadBalancer = new Mock <IRpcFunctionInvocationDispatcherLoadBalancer>(); _javaTestChannel = new TestRpcWorkerChannel(Guid.NewGuid().ToString(), "java", eventManager, _testLogger, false); var optionsMonitor = TestHelpers.CreateOptionsMonitor(workerConfigOptions); return(new RpcFunctionInvocationDispatcher(scriptOptions, metricsLogger.Object, testEnv, mockApplicationLifetime.Object, eventManager, loggerFactory, testLanguageWorkerChannelFactory, optionsMonitor, testWebHostLanguageWorkerChannelManager, jobHostLanguageWorkerChannelManager, new OptionsWrapper <ManagedDependencyOptions>(new ManagedDependencyOptions()), mockFunctionDispatcherLoadBalancer.Object)); }
public static async Task TestAppOfflineDebounceTime(string fileName, int delayInMs, bool expectShutdown, bool expectRestart) { using (var directory = new TempDirectory()) { // Setup string tempDir = directory.Path; Directory.CreateDirectory(Path.Combine(tempDir, "Host")); File.Create(Path.Combine(tempDir, fileName)); var jobHostOptions = new ScriptJobHostOptions { RootLogPath = tempDir, RootScriptPath = tempDir, FileWatchingEnabled = true }; var loggerFactory = new LoggerFactory(); var mockWebHostEnvironment = new Mock <IScriptJobHostEnvironment>(MockBehavior.Loose); var mockEventManager = new ScriptEventManager(); // Act FileMonitoringService fileMonitoringService = new FileMonitoringService(new OptionsWrapper <ScriptJobHostOptions>(jobHostOptions), loggerFactory, mockEventManager, mockWebHostEnvironment.Object); await fileMonitoringService.StartAsync(new CancellationToken(canceled : false)); var offlineEventArgs = new FileSystemEventArgs(WatcherChangeTypes.Created, tempDir, fileName); FileEvent offlinefileEvent = new FileEvent("ScriptFiles", offlineEventArgs); var randomFileEventArgs = new FileSystemEventArgs(WatcherChangeTypes.Created, tempDir, "random.txt"); FileEvent randomFileEvent = new FileEvent("ScriptFiles", randomFileEventArgs); mockEventManager.Publish(offlinefileEvent); await Task.Delay(delayInMs); mockEventManager.Publish(randomFileEvent); // Test if (expectShutdown) { mockWebHostEnvironment.Verify(m => m.Shutdown()); } else { mockWebHostEnvironment.Verify(m => m.Shutdown(), Times.Never); } if (expectRestart) { mockWebHostEnvironment.Verify(m => m.RestartHost()); } else { mockWebHostEnvironment.Verify(m => m.RestartHost(), Times.Never); } } }
public static FunctionBinding CreateTestBinding(JObject json) { ScriptBindingContext context = new ScriptBindingContext(json); WebJobsCoreScriptBindingProvider provider = new WebJobsCoreScriptBindingProvider(NullLogger <WebJobsCoreScriptBindingProvider> .Instance); ScriptBinding scriptBinding = null; provider.TryCreate(context, out scriptBinding); BindingMetadata bindingMetadata = BindingMetadata.Create(json); var config = new ScriptJobHostOptions(); return(new ExtensionBinding(config, scriptBinding, bindingMetadata)); }
public static Uri FilePathToVfsUri(string filePath, string baseUrl, ScriptJobHostOptions config, bool isDirectory = false) { var home = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ScriptSettingsManager.Instance.GetSetting(EnvironmentSettingNames.AzureWebsiteHomePath) ?? config.RootScriptPath : Path.DirectorySeparatorChar.ToString(); filePath = filePath .Substring(home.Length) .Trim('\\', '/') .Replace("\\", "/"); return(new Uri($"{baseUrl}/admin/vfs/{filePath}{(isDirectory ? "/" : string.Empty)}")); }
public void Generate_WithMultipleOutParameters() { string functionName = "FunctionWithOuts"; Collection <ParameterDescriptor> parameters = new Collection <ParameterDescriptor>(); parameters.Add(new ParameterDescriptor("param1", typeof(string))); parameters.Add(new ParameterDescriptor("param2", typeof(string).MakeByRefType()) { Attributes = ParameterAttributes.Out }); parameters.Add(new ParameterDescriptor("param3", typeof(string).MakeByRefType()) { Attributes = ParameterAttributes.Out }); FunctionMetadata metadata = new FunctionMetadata(); TestInvoker invoker = new TestInvoker(); FunctionDescriptor function = new FunctionDescriptor(functionName, invoker, metadata, parameters, null, null, null); Collection <FunctionDescriptor> functions = new Collection <FunctionDescriptor>(); functions.Add(function); // Make sure we don't generate a TimeoutAttribute if FunctionTimeout is null. var scriptConfig = new ScriptJobHostOptions(); scriptConfig.FunctionTimeout = null; Collection <CustomAttributeBuilder> typeAttributes = new Collection <CustomAttributeBuilder>(); // generate the Type Type functionType = FunctionGenerator.Generate("TestScriptHost", "TestFunctions", typeAttributes, functions); // verify the generated function MethodInfo method = functionType.GetMethod(functionName); IEnumerable <Attribute> attributes = functionType.GetCustomAttributes(); Assert.Empty(attributes); ParameterInfo[] functionParams = method.GetParameters(); // Verify that we have the correct number of parameters Assert.Equal(parameters.Count, functionParams.Length); // Verify that out parameters were correctly generated Assert.True(functionParams[1].IsOut); Assert.True(functionParams[2].IsOut); // Verify that the method is invocable method.Invoke(null, new object[] { "test", null, null }); // verify our custom invoker was called Assert.Equal(1, invoker.InvokeCount); }
public ScriptTelemetryInitializer(IOptions <ScriptJobHostOptions> hostOptions) { if (hostOptions == null) { throw new ArgumentNullException(nameof(hostOptions)); } if (hostOptions.Value == null) { throw new ArgumentNullException(nameof(hostOptions.Value)); } _hostOptions = hostOptions.Value; }
public LanguageWorkerChannel( ScriptJobHostOptions scriptConfig, IScriptEventManager eventManager, IWorkerProcessFactory processFactory, IProcessRegistry processRegistry, IObservable <FunctionRegistrationContext> functionRegistrations, WorkerConfig workerConfig, Uri serverUri, ILoggerFactory loggerFactory, IMetricsLogger metricsLogger, int attemptCount) { _workerId = Guid.NewGuid().ToString(); _scriptConfig = scriptConfig; _eventManager = eventManager; _processFactory = processFactory; _processRegistry = processRegistry; _functionRegistrations = functionRegistrations; _workerConfig = workerConfig; _serverUri = serverUri; _workerChannelLogger = loggerFactory.CreateLogger($"Worker.{workerConfig.Language}.{_workerId}"); _userLogsConsoleLogger = loggerFactory.CreateLogger(LanguageWorkerConstants.FunctionConsoleLogCategoryName); _inboundWorkerEvents = _eventManager.OfType <InboundEvent>() .Where(msg => msg.WorkerId == _workerId); _eventSubscriptions.Add(_inboundWorkerEvents .Where(msg => msg.MessageType == MsgType.RpcLog) .Subscribe(Log)); _eventSubscriptions.Add(_eventManager.OfType <RpcEvent>() .Where(msg => msg.WorkerId == _workerId) .Subscribe(msg => { var jsonMsg = JsonConvert.SerializeObject(msg, _verboseSerializerSettings); _userLogsConsoleLogger.LogTrace(jsonMsg); })); _eventSubscriptions.Add(_eventManager.OfType <FileEvent>() .Where(msg => Config.Extensions.Contains(Path.GetExtension(msg.FileChangeArguments.FullPath))) .Throttle(TimeSpan.FromMilliseconds(300)) // debounce .Subscribe(msg => _eventManager.Publish(new HostRestartEvent()))); _startLatencyMetric = metricsLogger.LatencyEvent(string.Format(MetricEventNames.WorkerInitializeLatency, workerConfig.Language, attemptCount)); StartWorker(); }
public SystemLoggerProviderTests() { var scriptOptions = new ScriptJobHostOptions { RootLogPath = Path.GetTempPath() }; _options = new OptionsWrapper <ScriptJobHostOptions>(scriptOptions); var debugStateProvider = new Mock <IDebugStateProvider>(MockBehavior.Strict); debugStateProvider.Setup(p => p.InDiagnosticMode).Returns(() => _inDiagnosticMode); _provider = new SystemLoggerProvider(_options, null, _environment, debugStateProvider.Object, null); }
public void InitializesEmptyOrMissingDirectorySnapshot(string rootScriptPath) { var scriptConfig = new ScriptJobHostOptions() { RootScriptPath = rootScriptPath }; IOptions <ScriptJobHostOptions> scriptOptions = new OptionsManager <ScriptJobHostOptions>(new TestOptionsFactory <ScriptJobHostOptions>(scriptConfig)); IOptions <LanguageWorkerOptions> languageWorkerOptions = new OptionsManager <LanguageWorkerOptions>(new TestOptionsFactory <LanguageWorkerOptions>(new LanguageWorkerOptions())); var functionMetadataManager = new FunctionMetadataManager(scriptOptions, languageWorkerOptions, NullLoggerFactory.Instance); Assert.False(functionMetadataManager.Functions.IsDefault); Assert.True(functionMetadataManager.Functions.IsEmpty); }