Пример #1
0
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var jobOptions = new JobRunnerOptions(args);

            Console.Title = jobOptions.JobName != null ? $"Exceptionless {jobOptions.JobName} Job" : "Exceptionless Jobs";

            string environment = Environment.GetEnvironmentVariable("EX_AppMode");

            if (String.IsNullOrWhiteSpace(environment))
            {
                environment = "Production";
            }

            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddYamlFile("appsettings.yml", optional: true, reloadOnChange: true)
                         .AddYamlFile($"appsettings.{environment}.yml", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables("EX_")
                         .AddEnvironmentVariables("ASPNETCORE_")
                         .AddCommandLine(args)
                         .Build();

            var options = AppOptions.ReadFromConfiguration(config);

            var loggerConfig = new LoggerConfiguration().ReadFrom.Configuration(config);

            if (!String.IsNullOrEmpty(options.ExceptionlessApiKey))
            {
                loggerConfig.WriteTo.Sink(new ExceptionlessSink(), LogEventLevel.Verbose);
            }

            Log.Logger = loggerConfig.CreateLogger();
            var configDictionary = config.ToDictionary("Serilog");

            Log.Information("Bootstrapping Exceptionless {JobName} job(s) in {AppMode} mode ({InformationalVersion}) on {MachineName} with settings {@Settings}", jobOptions.JobName ?? "All", environment, options.InformationalVersion, Environment.MachineName, configDictionary);

            bool useApplicationInsights = !String.IsNullOrEmpty(options.ApplicationInsightsKey);

            var builder = Host.CreateDefaultBuilder()
                          .UseEnvironment(environment)
                          .UseSerilog()
                          .ConfigureWebHostDefaults(webBuilder => {
                webBuilder
                .UseConfiguration(config)
                .Configure(app => {
                    app.UseSerilogRequestLogging(o => o.GetLevel = (context, duration, ex) => {
                        if (ex != null || context.Response.StatusCode > 499)
                        {
                            return(LogEventLevel.Error);
                        }

                        return(duration < 1000 && context.Response.StatusCode < 400 ? LogEventLevel.Debug : LogEventLevel.Information);
                    });
                })
                .Configure(app => {
                    Bootstrapper.LogConfiguration(app.ApplicationServices, options, app.ApplicationServices.GetService <ILogger <Program> >());

                    if (!String.IsNullOrEmpty(options.ExceptionlessApiKey) && !String.IsNullOrEmpty(options.ExceptionlessServerUrl))
                    {
                        app.UseExceptionless(ExceptionlessClient.Default);
                    }

                    app.UseHealthChecks("/health", new HealthCheckOptions {
                        Predicate = hcr => !String.IsNullOrEmpty(jobOptions.JobName) ? hcr.Tags.Contains(jobOptions.JobName) : hcr.Tags.Contains("AllJobs")
                    });

                    app.UseHealthChecks("/ready", new HealthCheckOptions {
                        Predicate = hcr => hcr.Tags.Contains("Critical")
                    });

                    app.UseWaitForStartupActionsBeforeServingRequests();
                    app.Use((context, func) => context.Response.WriteAsync($"Running Job: {jobOptions.JobName}"));
                });

                var metricOptions = MetricOptions.ReadFromConfiguration(config);
                if (!String.IsNullOrEmpty(metricOptions.Provider))
                {
                    ConfigureMetricsReporting(webBuilder, metricOptions);
                }
            })
                          .ConfigureServices((ctx, services) => {
                AddJobs(services, jobOptions);
                services.AddAppOptions(options);

                if (useApplicationInsights)
                {
                    services.AddApplicationInsightsTelemetry(options.ApplicationInsightsKey);
                }

                Bootstrapper.RegisterServices(services);
                Insulation.Bootstrapper.RegisterServices(services, options, true);
            });

            return(builder);
        }
Пример #2
0
        private static void AddJobs(IServiceCollection services, JobRunnerOptions options)
        {
            services.AddJobLifetimeService();

            if (options.CleanupSnapshot)
            {
                services.AddJob <CleanupSnapshotJob>(true);
            }
            if (options.CloseInactiveSessions)
            {
                services.AddJob <CloseInactiveSessionsJob>(true);
            }
            if (options.DailySummary)
            {
                services.AddJob <DailySummaryJob>(true);
            }
            if (options.DataMigration)
            {
                services.AddJob <DataMigrationJob>(true);
            }
            if (options.DownloadGeoipDatabase)
            {
                services.AddJob <DownloadGeoIPDatabaseJob>(true);
            }
            if (options.EventNotifications)
            {
                services.AddJob <EventNotificationsJob>(true);
            }
            if (options.EventPosts)
            {
                services.AddJob <EventPostsJob>(true);
            }
            if (options.EventSnapshot)
            {
                services.AddJob <EventSnapshotJob>(true);
            }
            if (options.EventUserDescriptions)
            {
                services.AddJob <EventUserDescriptionsJob>(true);
            }
            if (options.MailMessage)
            {
                services.AddJob <MailMessageJob>(true);
            }
            if (options.MaintainIndexes)
            {
                services.AddCronJob <MaintainIndexesJob>("10 */2 * * *");
            }
            if (options.Migration)
            {
                services.AddJob <MigrationJob>(true);
            }
            if (options.OrganizationSnapshot)
            {
                services.AddJob <OrganizationSnapshotJob>(true);
            }
            if (options.RetentionLimits)
            {
                services.AddJob <RetentionLimitsJob>(true);
            }
            if (options.StackEventCount)
            {
                services.AddJob <StackEventCountJob>(true);
            }
            if (options.StackSnapshot)
            {
                services.AddJob <StackSnapshotJob>(true);
            }
            if (options.WebHooks)
            {
                services.AddJob <WebHooksJob>(true);
            }
            if (options.WorkItem)
            {
                services.AddJob <WorkItemJob>(true);
            }
        }
Пример #3
0
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            var    jobOptions  = new JobRunnerOptions(args);
            string environment = Environment.GetEnvironmentVariable("EX_AppMode");

            if (String.IsNullOrWhiteSpace(environment))
            {
                environment = "Production";
            }

            Console.Title = jobOptions.JobName != null ? $"Exceptionless {jobOptions.JobName} Job" : "Exceptionless Jobs";

            string currentDirectory = Directory.GetCurrentDirectory();
            var    config           = new ConfigurationBuilder()
                                      .SetBasePath(currentDirectory)
                                      .AddYamlFile("appsettings.yml", optional: true, reloadOnChange: true)
                                      .AddYamlFile($"appsettings.{environment}.yml", optional: true, reloadOnChange: true)
                                      .AddEnvironmentVariables("EX_")
                                      .AddCommandLine(args)
                                      .Build();

            var services = new ServiceCollection();

            services.AddSingleton <IConfiguration>(config);
            services.ConfigureOptions <ConfigureAppOptions>();
            services.ConfigureOptions <ConfigureMetricOptions>();
            var container = services.BuildServiceProvider();
            var options   = container.GetRequiredService <IOptions <AppOptions> >().Value;

            var loggerConfig = new LoggerConfiguration().ReadFrom.Configuration(config);

            if (!String.IsNullOrEmpty(options.ExceptionlessApiKey))
            {
                loggerConfig.WriteTo.Sink(new ExceptionlessSink(), LogEventLevel.Verbose);
            }

            var loggerFactory = new SerilogLoggerFactory(loggerConfig.CreateLogger());

            _logger = loggerFactory.CreateLogger <Program>();

            var configDictionary = config.ToDictionary("Serilog");

            _logger.LogInformation("Bootstrapping Exceptionless {JobName} job(s) in {AppMode} mode ({InformationalVersion}) on {MachineName} with settings {@Settings}", jobOptions.JobName ?? "All", environment, options.InformationalVersion, Environment.MachineName, configDictionary);

            bool useApplicationInsights = !String.IsNullOrEmpty(options.ApplicationInsightsKey);

            var builder = WebHost.CreateDefaultBuilder(args)
                          .UseEnvironment(environment)
                          .ConfigureKestrel(c => {
                c.AddServerHeader = false;
                //c.AllowSynchronousIO = false; // TODO: Investigate issue with JSON Serialization.
            })
                          .UseConfiguration(config)
                          .ConfigureServices(s => {
                s.AddSingleton <ILoggerFactory>(loggerFactory);
                s.AddHttpContextAccessor();

                AddJobs(s, jobOptions);

                if (useApplicationInsights)
                {
                    s.AddApplicationInsightsTelemetry();
                }

                Bootstrapper.RegisterServices(s);
                var serviceProvider = s.BuildServiceProvider();
                Insulation.Bootstrapper.RegisterServices(serviceProvider, s, options, true);
            })
                          .Configure(app => {
                Bootstrapper.LogConfiguration(app.ApplicationServices, options, loggerFactory);

                if (!String.IsNullOrEmpty(options.ExceptionlessApiKey) && !String.IsNullOrEmpty(options.ExceptionlessServerUrl))
                {
                    app.UseExceptionless(ExceptionlessClient.Default);
                }

                app.UseHealthChecks("/health", new HealthCheckOptions {
                    Predicate = hcr => !String.IsNullOrEmpty(jobOptions.JobName) ? hcr.Tags.Contains(jobOptions.JobName) : hcr.Tags.Contains("AllJobs")
                });

                app.UseHealthChecks("/ready", new HealthCheckOptions {
                    Predicate = hcr => hcr.Tags.Contains("Critical")
                });

                app.UseWaitForStartupActionsBeforeServingRequests();
                app.Use((context, func) => context.Response.WriteAsync($"Running Job: {jobOptions.JobName}"));
            });

            if (useApplicationInsights)
            {
                builder.UseApplicationInsights(options.ApplicationInsightsKey);
            }

            var metricOptions = container.GetRequiredService <IOptions <MetricOptions> >().Value;

            if (!String.IsNullOrEmpty(metricOptions.Provider))
            {
                ConfigureMetricsReporting(builder, metricOptions);
            }

            return(builder);
        }
Пример #4
0
        private static void AddJobs(IServiceCollection services, JobRunnerOptions options)
        {
            services.AddJobLifetimeService();

            if (options.CleanupData)
            {
                services.AddJob <CleanupDataJob>();
            }
            if (options.CleanupOrphanedData)
            {
                services.AddJob <CleanupOrphanedDataJob>();
            }
            if (options.CloseInactiveSessions)
            {
                services.AddJob <CloseInactiveSessionsJob>(true);
            }
            if (options.DailySummary)
            {
                services.AddJob <DailySummaryJob>(true);
            }
            if (options.DataMigration)
            {
                services.AddJob <DataMigrationJob>(true);
            }
            if (options.DownloadGeoIPDatabase)
            {
                services.AddJob <DownloadGeoIPDatabaseJob>(true);
            }
            if (options.EventNotifications)
            {
                services.AddJob <EventNotificationsJob>(true);
            }
            if (options.EventPosts)
            {
                services.AddJob <EventPostsJob>(true);
            }
            if (options.EventUserDescriptions)
            {
                services.AddJob <EventUserDescriptionsJob>(true);
            }
            if (options.MailMessage)
            {
                services.AddJob <MailMessageJob>(true);
            }
            if (options.MaintainIndexes)
            {
                services.AddJob <MaintainIndexesJob>();
            }
            if (options.Migration)
            {
                services.AddJob <MigrationJob>(true);
            }
            if (options.StackStatus)
            {
                services.AddJob <StackStatusJob>(true);
            }
            if (options.StackEventCount)
            {
                services.AddJob <StackEventCountJob>(true);
            }
            if (options.WebHooks)
            {
                services.AddJob <WebHooksJob>(true);
            }
            if (options.WorkItem)
            {
                services.AddJob <WorkItemJob>(true);
            }
        }
        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            var jobOptions = new JobRunnerOptions(args);

            Console.Title = jobOptions.JobName != null ? $"Exceptionless {jobOptions.JobName} Job" : "Exceptionless Jobs";

            string environment = Environment.GetEnvironmentVariable("EX_AppMode");

            if (String.IsNullOrWhiteSpace(environment))
            {
                environment = "Production";
            }

            string currentDirectory = Directory.GetCurrentDirectory();
            var    config           = new ConfigurationBuilder()
                                      .SetBasePath(currentDirectory)
                                      .AddYamlFile("appsettings.yml", optional: true, reloadOnChange: true)
                                      .AddYamlFile($"appsettings.{environment}.yml", optional: true, reloadOnChange: true)
                                      .AddEnvironmentVariables("EX_")
                                      .AddCommandLine(args)
                                      .Build();

            var options = AppOptions.ReadFromConfiguration(config);

            var loggerConfig = new LoggerConfiguration().ReadFrom.Configuration(config);

            if (!String.IsNullOrEmpty(options.ExceptionlessApiKey))
            {
                loggerConfig.WriteTo.Sink(new ExceptionlessSink(), LogEventLevel.Verbose);
            }

            var serilogLogger = loggerConfig.CreateLogger();

            _logger = new SerilogLoggerFactory(serilogLogger).CreateLogger <Program>();

            var configDictionary = config.ToDictionary("Serilog");

            _logger.LogInformation("Bootstrapping Exceptionless {JobName} job(s) in {AppMode} mode ({InformationalVersion}) on {MachineName} with settings {@Settings}", jobOptions.JobName ?? "All", environment, options.InformationalVersion, Environment.MachineName, configDictionary);

            bool useApplicationInsights = !String.IsNullOrEmpty(options.ApplicationInsightsKey);

            var builder = WebHost.CreateDefaultBuilder(args)
                          .UseEnvironment(environment)
                          .UseConfiguration(config)
                          .UseDefaultServiceProvider((ctx, o) => {
                o.ValidateScopes = ctx.HostingEnvironment.IsDevelopment();
            })
                          .ConfigureKestrel(c => {
                c.AddServerHeader = false;
                //c.AllowSynchronousIO = false; // TODO: Investigate issue with JSON Serialization.
            })
                          .UseSerilog(serilogLogger, true)
                          .ConfigureServices((ctx, services) => {
                services.AddHttpContextAccessor();

                AddJobs(services, jobOptions);

                if (useApplicationInsights)
                {
                    services.AddApplicationInsightsTelemetry();
                }

                Bootstrapper.RegisterServices(services);
                var serviceProvider = services.BuildServiceProvider();
                Insulation.Bootstrapper.RegisterServices(serviceProvider, services, options, true);

                services.PostConfigure <HostFilteringOptions>(o => {
                    if (o.AllowedHosts == null || o.AllowedHosts.Count == 0)
                    {
                        // "AllowedHosts": "localhost;127.0.0.1;[::1]"
                        var hosts = ctx.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        // Fall back to "*" to disable.
                        o.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
                    }
                });

                services.AddSingleton <IOptionsChangeTokenSource <HostFilteringOptions> >(new ConfigurationChangeTokenSource <HostFilteringOptions>(ctx.Configuration));
                services.AddTransient <IStartupFilter, HostFilteringStartupFilter>();
            })
                          .Configure(app => {
                Bootstrapper.LogConfiguration(app.ApplicationServices, options, _logger);

                if (!String.IsNullOrEmpty(options.ExceptionlessApiKey) && !String.IsNullOrEmpty(options.ExceptionlessServerUrl))
                {
                    app.UseExceptionless(ExceptionlessClient.Default);
                }

                app.UseHealthChecks("/health", new HealthCheckOptions {
                    Predicate = hcr => !String.IsNullOrEmpty(jobOptions.JobName) ? hcr.Tags.Contains(jobOptions.JobName) : hcr.Tags.Contains("AllJobs")
                });

                app.UseHealthChecks("/ready", new HealthCheckOptions {
                    Predicate = hcr => hcr.Tags.Contains("Critical")
                });

                app.UseWaitForStartupActionsBeforeServingRequests();
                app.Use((context, func) => context.Response.WriteAsync($"Running Job: {jobOptions.JobName}"));
            });

            if (String.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
            {
                builder.UseContentRoot(Directory.GetCurrentDirectory());
            }

            if (useApplicationInsights)
            {
                builder.UseApplicationInsights(options.ApplicationInsightsKey);
            }

            var metricOptions = MetricOptions.ReadFromConfiguration(config);

            if (!String.IsNullOrEmpty(metricOptions.Provider))
            {
                ConfigureMetricsReporting(builder, metricOptions);
            }

            return(builder);
        }