private static void AddMQTTChatHealthChecks(this IHealthChecksBuilder builder)
 {
     builder.AddPrivateMemoryHealthCheck(1024 * 1024 * 1024, "privatememory")
     .AddDiskStorageHealthCheck(setup =>
     {
         DriveInfo.GetDrives().ToList().ForEach(di =>
         {
             setup.AddDrive(di.Name, 1024);
         });
     });
 }
Beispiel #2
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddMvc(options =>
            {
                options.Filters.Add <DomainNotificationFilter>();
                options.EnableEndpointRouting = false;
            }).AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.IgnoreNullValues = true;
            });

            //Work with Multi-Tenants
            services.AddMultiTenancy()
            .WithResolutionStrategy <HostTenantResolutionStrategy>()
            // .WithResolutionStrategy<HeaderTenantResolutionStrategy>()
            .WithStore(Module.Base.Bootstrap.GetTenantStoreType());

            services.Configure <GzipCompressionProviderOptions>(x => x.Level = CompressionLevel.Optimal);
            services.AddResponseCompression(x =>
            {
                x.Providers.Add <GzipCompressionProvider>();
            });

            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            services.Configure <IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            if (PlatformServices.Default.Application.ApplicationName != "testhost")
            {
                IHealthChecksBuilder healthCheckBuilder = services.AddHealthChecks();

                //500 mb
                healthCheckBuilder.AddProcessAllocatedMemoryHealthCheck(500 * 1024 * 1024, "Process Memory", tags: new[] { "self" });
                //500 mb
                healthCheckBuilder.AddPrivateMemoryHealthCheck(1500 * 1024 * 1024, "Private memory", tags: new[] { "self" });

                healthCheckBuilder.AddSqlServer(Configuration["ConnectionStrings:CustomerDB"], tags: new[] { "services" });

                //dotnet add <Project> package AspNetCore.HealthChecks.Redis
                //healthCheckBuilder.AddRedis(Configuration["Data:ConnectionStrings:Redis"], tags: new[] {"services"});

                //dotnet add <Project> package AspNetCore.HealthChecks.OpenIdConnectServer
                //healthCheckBuilder.AddIdentityServer(new Uri(Configuration["WizID:Authority"]), "SSO Wiz", tags: new[] { "services" });

                //if (WebHostEnvironment.IsProduction())
                //{
                //dotnet add <Project> package AspNetCore.HealthChecks.AzureKeyVault
                //healthCheckBuilder.AddAzureKeyVault(options =>
                //{
                //    options.UseKeyVaultUrl($"{Configuration["Azure:KeyVaultUrl"]}");
                //}, name: "azure-key-vault",tags: new[] {"services"});
                //}

                healthCheckBuilder.AddApplicationInsightsPublisher();

                HealthChecksUIBuilder healthCheck = services.AddHealthChecksUI(setupSettings: setup =>
                {
                    setup.AddWebhookNotification("Teams", Configuration["Webhook:Teams"],
                                                 payload: File.ReadAllText(Path.Combine(".", "MessageCard", "ServiceDown.json")),
                                                 restorePayload: File.ReadAllText(Path.Combine(".", "MessageCard", "ServiceRestore.json")),
                                                 customMessageFunc: report =>
                    {
                        var failing = report.Entries.Where(e => e.Value.Status == HealthChecks.UI.Core.UIHealthStatus.Unhealthy);
                        return($"{AppDomain.CurrentDomain.FriendlyName}: {failing.Count()} healthchecks are failing");
                    }
                                                 );
                }).AddInMemoryStorage();
            }

            if (!WebHostEnvironment.IsProduction())
            {
                services.AddOpenApiDocument(document =>
                {
                    document.DocumentName = "v1";
                    document.Version      = "v1";
                    document.Title        = "Whitelabel API";
                    document.Description  = "API de Whitelabel";
                    document.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT"));
                    document.AddSecurity("JWT", Enumerable.Empty <string>(), new OpenApiSecurityScheme
                    {
                        Type        = OpenApiSecuritySchemeType.ApiKey,
                        Name        = HeaderNames.Authorization,
                        Description = "Token de autenticação via SSO",
                        In          = OpenApiSecurityApiKeyLocation.Header
                    });
                });
            }

            services.AddAutoMapper(typeof(Startup));
            services.AddHttpContextAccessor();
            services.AddApplicationInsightsTelemetry();

            RegisterServices(services);
        }
        /// <summary>
        /// 建立HealthChecks服务
        /// </summary>
        /// <param name="builder">HealthChecks服务创建者</param>
        /// <param name="configuration">应用程序配置</param>
        /// <returns></returns>
        protected virtual IHealthChecksBuilder BuildHealthChecks(IHealthChecksBuilder builder, IConfiguration configuration)
        {
            //system
            long providerMemory    = configuration["OSharp:HealthChecks:PrivateMemory"].CastTo(1000_000_000L);
            long virtualMemorySize = configuration["OSharp:HealthChecks:VirtualMemorySize"].CastTo(1000_000_000L);
            long workingSet        = configuration["OSharp:HealthChecks:WorkingSet"].CastTo(1000_000_000L);

            builder.AddPrivateMemoryHealthCheck(providerMemory);        //最大私有内存
            builder.AddVirtualMemorySizeHealthCheck(virtualMemorySize); //最大虚拟内存
            builder.AddWorkingSetHealthCheck(workingSet);               //最大工作内存

            OsharpOptions options = configuration.GetOsharpOptions();

            //数据库
            foreach (var pair in options.DbContexts.OrderBy(m => m.Value.DatabaseType))
            {
                string connectionString = pair.Value.ConnectionString;
                switch (pair.Value.DatabaseType)
                {
                case DatabaseType.SqlServer:
                    builder.AddSqlServer(connectionString, null, pair.Key);
                    break;

                case DatabaseType.Sqlite:
                    builder.AddSqlite(connectionString, name: pair.Key);
                    break;

                case DatabaseType.MySql:
                    builder.AddMySql(connectionString, pair.Key);
                    break;

                case DatabaseType.PostgreSql:
                    builder.AddNpgSql(connectionString, name: pair.Key);
                    break;

                case DatabaseType.Oracle:
                    builder.AddOracle(connectionString, name: pair.Key);
                    break;

                default:
                    throw new ArgumentOutOfRangeException($"OSharpOptions中 {pair.Value.DatabaseType} 不受支持");
                }
            }

            //SMTP
            if (options.MailSender != null)
            {
                var smtp = options.MailSender;
                builder.AddSmtpHealthCheck(smtpOptions =>
                {
                    smtpOptions.Host = smtp.Host;
                    smtpOptions.LoginWith(smtp.UserName, smtp.Password);
                });
            }

            //Redis
            if (options.Redis != null && options.Redis.Enabled)
            {
                var redis = options.Redis;
                builder.AddRedis(redis.Configuration);
            }

            //Hangfire
            if (configuration["OSharp:Hangfire:Enabled"].CastTo(false))
            {
                builder.AddHangfire(hangfireOptions =>
                {
                    hangfireOptions.MinimumAvailableServers = 1;
                });
            }

            return(builder);
        }