Example #1
0
        public WebJobsScriptHostService(IOptionsMonitor <ScriptApplicationHostOptions> applicationHostOptions, IScriptHostBuilder scriptHostBuilder, ILoggerFactory loggerFactory,
                                        IScriptWebHostEnvironment scriptWebHostEnvironment, IEnvironment environment,
                                        HostPerformanceManager hostPerformanceManager, IOptions <HostHealthMonitorOptions> healthMonitorOptions,
                                        IMetricsLogger metricsLogger, IApplicationLifetime applicationLifetime, IConfiguration config, IScriptEventManager eventManager)
        {
            ArgumentNullException.ThrowIfNull(loggerFactory);

            // This will no-op if already initialized.
            InitializeApplicationInsightsRequestTracking();

            _applicationLifetime = applicationLifetime;
            RegisterApplicationLifetimeEvents();

            _metricsLogger            = metricsLogger;
            _applicationHostOptions   = applicationHostOptions ?? throw new ArgumentNullException(nameof(applicationHostOptions));
            _scriptWebHostEnvironment = scriptWebHostEnvironment ?? throw new ArgumentNullException(nameof(scriptWebHostEnvironment));
            _scriptHostBuilder        = scriptHostBuilder ?? throw new ArgumentNullException(nameof(scriptHostBuilder));
            _environment          = environment ?? throw new ArgumentNullException(nameof(environment));
            _performanceManager   = hostPerformanceManager ?? throw new ArgumentNullException(nameof(hostPerformanceManager));
            _healthMonitorOptions = healthMonitorOptions ?? throw new ArgumentNullException(nameof(healthMonitorOptions));
            _logger       = loggerFactory.CreateLogger(ScriptConstants.LogCategoryHostGeneral);
            _config       = config ?? throw new ArgumentNullException(nameof(config));
            _eventManager = eventManager;

            _hostStarted = _hostStartedSource.Task;

            State = ScriptHostState.Default;

            if (ShouldMonitorHostHealth)
            {
                _healthCheckWindow    = new SlidingWindow <bool>(_healthMonitorOptions.Value.HealthCheckWindow);
                _hostHealthCheckTimer = new Timer(OnHostHealthCheckTimer, null, TimeSpan.Zero, _healthMonitorOptions.Value.HealthCheckInterval);
            }
        }
Example #2
0
        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();
        }
Example #3
0
 public UpdateCenterController(IGitHubClient client, ITaskFactory taskFactory, IFlubuSession flubuSession, IHostEnvironment hostEnvironment, IHostApplicationLifetime applicationLifetime)
 {
     _client              = client;
     _taskFactory         = taskFactory;
     _flubuSession        = flubuSession;
     _hostEnvironment     = hostEnvironment;
     _applicationLifetime = applicationLifetime;
 }
 public HostIdValidator(IEnvironment environment, IAzureBlobStorageProvider azureBlobStorageProvider, IApplicationLifetime applicationLifetime,
                        HostNameProvider hostNameProvider, ILogger <HostIdValidator> logger)
 {
     _environment = environment;
     _azureBlobStorageProvider = azureBlobStorageProvider;
     _applicationLifetime      = applicationLifetime;
     _hostNameProvider         = hostNameProvider;
     _logger = logger;
 }
Example #5
0
 public StartCheckDecorator(
     IHostedService service,
     IApplicationLifetime applicationLifetime,
     ILogger <StartCheckDecorator> logger)
 {
     _service             = service;
     _applicationLifetime = applicationLifetime;
     _logger = logger;
 }
Example #6
0
 public virtual void Configure(IApplicationBuilder app, IHostingEnvironment env,
                               IApplicationLifetime appLifetime, IApiVersionDescriptionProvider provider)
 {
     app.UseForwardedHeaders(new ForwardedHeadersOptions {
         ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
     });
     appLifetime.ApplicationStopping.Register(ProgramBase <TStart> .ConsulConfigCancellationTokenSource.Cancel);
     app.UseCoreFunctionality(provider, ConfigureSwagger);
 }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
        {
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseDeveloperExceptionPage();

            app.UseMvc();

            app.UseStaticFiles();

            appLifetime.ApplicationStopped.Register(() => _aspNetScope.Dispose());
        }
Example #8
0
 public WorkerConcurrencyManager(
     IFunctionInvocationDispatcherFactory functionInvocationDispatcherFactory,
     IEnvironment environment,
     IOptions <WorkerConcurrencyOptions> workerConcurrencyOptions,
     IFunctionsHostingConfiguration functionsHostingConfigurations,
     IApplicationLifetime applicationLifetime,
     ILoggerFactory loggerFactory)
 {
     _functionInvocationDispatcherFactory = functionInvocationDispatcherFactory ?? throw new ArgumentNullException(nameof(functionInvocationDispatcherFactory));
     _environment = environment ?? throw new ArgumentNullException(nameof(environment));
     _workerConcurrencyOptions       = workerConcurrencyOptions;
     _functionsHostingConfigurations = functionsHostingConfigurations;
     _applicationLifetime            = applicationLifetime;
     _logger = loggerFactory?.CreateLogger(LogCategories.Concurrency);
 }
        public void Configure(IApplicationBuilder app, IHostEnvironment env, IApplicationLifetime appLifetime)
        {
            try
            {
                ApplicationContainer = app.ApplicationServices.GetAutofacRoot();

                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseHsts();
                }

                app.UseCorrelation();
#if DEBUG
                app.UseLykkeMiddleware(ServiceName, ex => ex.ToString());
#else
                app.UseLykkeMiddleware(ServiceName, ex => new ErrorResponse {
                    ErrorMessage = ex.Message
                });
#endif

                app.UseRouting();
                app.UseAuthentication();
                app.UseAuthorization();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
                app.UseSwagger();
                app.UseSwaggerUI(a => a.SwaggerEndpoint("/swagger/v1/swagger.json", "Main Swagger"));

                appLifetime.ApplicationStarted.Register(() => StartApplication().Wait());
                appLifetime.ApplicationStopping.Register(() => StopApplication().Wait());
                appLifetime.ApplicationStopped.Register(() => CleanUp().Wait());

                var provider = new AnnotationsBasedMetamodelProvider();

                EntityMetamodel.Configure(provider);
            }
            catch (Exception ex)
            {
                Log?.WriteFatalErrorAsync(nameof(Startup), nameof(ConfigureServices), "", ex).Wait();
                throw;
            }
        }
Example #10
0
        public void Configure(
            IServiceProvider serviceProvider,
            IApplicationBuilder app,
            IHostingEnvironment env,
            IApplicationLifetime appLifetime,
            ILoggerFactory loggerFactory,
            IApiVersionDescriptionProvider apiVersionProvider,
            ApiDataDogToggle datadogToggle,
            ApiDebugDataDogToggle debugDataDogToggle,
            HealthCheckService healthCheckService)
        {
            StartupHelpers.CheckDatabases(healthCheckService, DatabaseTag).GetAwaiter().GetResult();

            app
            .UseDatadog <Startup>(
                serviceProvider,
                loggerFactory,
                datadogToggle,
                debugDataDogToggle,
                _configuration["DataDog:ServiceName"])

            .UseDefaultForApi(new StartupUseOptions
            {
                Common =
                {
                    ApplicationContainer = _applicationContainer,
                    ServiceProvider      = serviceProvider,
                    HostingEnvironment   = env,
                    ApplicationLifetime  = appLifetime,
                    LoggerFactory        = loggerFactory
                },
                Api =
                {
                    VersionProvider = apiVersionProvider,
                    Info            = groupName => $"Basisregisters Vlaanderen - Public Service Registry API {groupName}"
                },
                MiddlewareHooks =
                {
                    AfterMiddleware = x => x.UseMiddleware <AddNoCacheHeadersMiddleware>(),
                }
            });

            var projectionsManager = serviceProvider.GetRequiredService <IConnectedProjectionsManager>();

            projectionsManager.Start();
        }
Example #11
0
        public WorkerConcurrencyManagerTest()
        {
            _loggerProvider = new TestLoggerProvider();
            _loggerFactory  = new LoggerFactory();
            _loggerFactory.AddProvider(_loggerProvider);
            _testEnvironment = new TestEnvironment();
            _testEnvironment.SetEnvironmentVariable(RpcWorkerConstants.FunctionsWorkerDynamicConcurrencyEnabled, "true");
            _testEnvironment.SetEnvironmentVariable(RpcWorkerConstants.FunctionWorkerRuntimeSettingName, RpcWorkerConstants.PythonLanguageWorkerName);
            _testEnvironment.SetEnvironmentVariable(EnvironmentSettingNames.FunctionWorkerRuntime, RpcWorkerConstants.NodeLanguageWorkerName);
            Mock <IFunctionsHostingConfiguration> conf = new Mock <IFunctionsHostingConfiguration>();

            conf.Setup(x => x.FunctionsWorkerDynamicConcurrencyEnabled).Returns(false);
            _functionsHostingConfigurations = conf.Object;
            Mock <IApplicationLifetime> applicationLifetime = new Mock <IApplicationLifetime>();

            applicationLifetime.Setup(x => x.StopApplication()).Verifiable();
            _applicationLifetime = applicationLifetime.Object;
        }
Example #12
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
        {
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseDeveloperExceptionPage();

            app.UseAuthentication();

            app.UseSignalR(builder => builder.MapHub <DeploymentLoggingHub>(DeploymentLogConstants.HubRoute));

            app.UseMvc();

            app.UseStaticFiles();

            appLifetime.ApplicationStopped.Register(() => _aspNetScope.Dispose());
        }
Example #13
0
        public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, ILoggerFactory loggerFactory, Microsoft.AspNetCore.Hosting.IApplicationLifetime lifetime)
        {
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();

            // Add new mappings
            provider.Mappings[".ps1"]  = "text/plain";
            provider.Mappings[".psm1"] = "text/plain";
            provider.Mappings[".psd1"] = "text/plain";
            provider.Mappings[".log"]  = "text/plain";
            provider.Mappings[".yml"]  = "text/plain";

            loggerFactory.AddNLog();
            app.UseResponseCompression();
            app.UseStatusCodePages(async context => {
                if (context.HttpContext.Response.StatusCode == 404 && !context.HttpContext.Request.Path.StartsWithSegments("/api"))
                {
                    var fileName = context.HttpContext.Request.Path.ToString().Split('/').Last();
                    var asset    = AssetService.Instance.FindAsset(fileName);
                    if (asset != null)
                    {
                        var response        = context.HttpContext.Response;
                        response.StatusCode = 200;
                        var file            = File.ReadAllBytes(asset);
                        await response.Body.WriteAsync(file, 0, file.Length);
                    }
                    else
                    {
                        var response         = context.HttpContext.Response;
                        response.StatusCode  = 200;
                        var filePath         = env.ContentRootPath + "/index.html";
                        response.ContentType = "text/html; charset=utf-8";
                        var file             = File.ReadAllText(filePath);
                        await response.WriteAsync(file);
                    }
                }
                else
                {
                    await context.Next(context.HttpContext);
                }
            });

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider          = new PhysicalFileProvider(env.ContentRootPath),
                RequestPath           = new PathString(""),
                ServeUnknownFileTypes = true,
                ContentTypeProvider   = provider
            });

            var dashboardService = app.ApplicationServices.GetService(typeof(IDashboardService)) as IDashboardService;

            if (dashboardService?.DashboardOptions?.Certificate != null || dashboardService?.DashboardOptions?.CertificateFile != null)
            {
                if (dashboardService.DashboardOptions.Port == dashboardService.DashboardOptions.HttpsPort)
                {
                    Logger.Warn("Port and HTTPS port are the same. HTTPS Redirection will not work. Select two different ports.");
                }
                else
                {
                    app.UseHttpsRedirection();
                }
            }

            if (dashboardService?.DashboardOptions?.PublishedFolders != null)
            {
                foreach (var publishedFolder in dashboardService.DashboardOptions.PublishedFolders)
                {
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        RequestPath           = publishedFolder.RequestPath,
                        FileProvider          = new PhysicalFileProvider(publishedFolder.Path),
                        ServeUnknownFileTypes = true,
                        ContentTypeProvider   = provider
                    });
                }
            }

            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());

            app.UseSignalR(routes =>
            {
                routes.MapHub <DashboardHub>("/dashboardhub");
            });

            app.UseWebSockets();

            app.UseSession();

            app.UseMvc();
        }
Example #14
0
        /// <inheritdoc />
        public override void Configure(IApplicationBuilder applicationBuilder, IHostingEnvironment hostingEnvironment, IApplicationLifetime applicationLifetime)
        {
            if (applicationBuilder == null)
            {
                throw new ArgumentNullException(nameof(applicationBuilder));
            }

            if (hostingEnvironment == null)
            {
                throw new ArgumentNullException(nameof(hostingEnvironment));
            }

            if (applicationLifetime == null)
            {
                throw new ArgumentNullException(nameof(applicationLifetime));
            }
        }
 public ApplicationLifetimeHostedService(Microsoft.AspNetCore.Hosting.IApplicationLifetime appLifetime)
 {
     this.appLifetime = appLifetime;
 }