コード例 #1
0
        private void HookupPostgres(IServiceCollection services, IHealthChecksBuilder healthCheckBuilder)
        {
#if Debug || DEBUG
            // The line below is a compile-time debug feature for `docker build` outputting which database engine is hooked up
#warning Using PostgreSQL for a database
#endif
            this.HookupDatabase <NpgsqlConnectionStringBuilder, NpgsqlDbContextOptionsConfigurator>(services, "Postgres");
            healthCheckBuilder.AddNpgSql(GetConnectionString, name: dbHealthCheckName, tags: dbHealthCheckTags);
        }
        public static IHealthChecksBuilder AddDependencies(
            this IHealthChecksBuilder builder,
            List <Dependency> dependencies)
        {
            foreach (var dependencia in dependencies)
            {
                string nomeDependencia = dependencia.Name.ToLower();

                if (nomeDependencia.StartsWith("sqlserver-"))
                {
                    builder = builder.AddSqlServer(dependencia.ConnectionString, name: dependencia.Name);
                }
                else if (nomeDependencia.StartsWith("mongodb-"))
                {
                    builder = builder.AddMongoDb(dependencia.ConnectionString, name: dependencia.Name);
                }
                else if (nomeDependencia.StartsWith("redis-"))
                {
                    builder = builder.AddRedis(dependencia.ConnectionString, name: dependencia.Name);
                }
                else if (nomeDependencia.StartsWith("postgres-"))
                {
                    builder = builder.AddNpgSql(dependencia.ConnectionString, name: dependencia.Name);
                }
                else if (nomeDependencia.StartsWith("mysql-"))
                {
                    builder = builder.AddMySql(dependencia.ConnectionString, name: dependencia.Name);
                }
                else if (nomeDependencia.StartsWith("url-"))
                {
                    builder = builder.AddUrlGroup(new Uri(dependencia.Url), name: dependencia.Name);
                }
                else if (nomeDependencia.StartsWith("rabbitmq-"))
                {
                    builder = builder.AddRabbitMQ(dependencia.ConnectionString, name: dependencia.Name);
                }
                else if (nomeDependencia.StartsWith("azureservicebusqueue-"))
                {
                    builder = builder.AddAzureServiceBusQueue(dependencia.ConnectionString, queueName: dependencia.QueueName, name: dependencia.Name);
                }
                else if (nomeDependencia.StartsWith("azureblobstorage-"))
                {
                    builder = builder.AddAzureBlobStorage(dependencia.ConnectionString, name: dependencia.Name);
                }
                else if (nomeDependencia.StartsWith("documentdb-"))
                {
                    builder = builder.AddDocumentDb(
                        docdb => {
                        docdb.UriEndpoint = dependencia.UriEndpoint;
                        docdb.PrimaryKey  = dependencia.PrimaryKey;
                    });
                }
            }

            return(builder);
        }
 /// <summary>
 /// Add a health check for Postgres databases.
 /// </summary>
 /// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
 /// <param name="npgsqlConnectionString">The Postgres connection string to be used.</param>
 /// <param name="healthQuery">The query to be used in check. Optional. If <c>null</c> SELECT 1 is used.</param>
 /// <param name="connectionAction">An optional action to allow additional Npgsql-specific configuration.</param>
 /// <param name="name">The health check name. Optional. If <c>null</c> the type name 'npgsql' will be used for the name.</param>
 /// <param name="failureStatus">
 /// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
 /// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
 /// </param>
 /// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
 /// <param name="timeout">An optional <see cref="TimeSpan"/> representing the timeout of the check.</param>
 /// <returns>The specified <paramref name="builder"/>.</returns>
 public static IHealthChecksBuilder AddNpgSql(
     this IHealthChecksBuilder builder,
     string npgsqlConnectionString,
     string healthQuery = "SELECT 1;",
     Action <NpgsqlConnection>?connectionAction = null,
     string?name = default,
     HealthStatus?failureStatus = default,
     IEnumerable <string>?tags  = default,
     TimeSpan?timeout           = default)
 {
     return(builder.AddNpgSql(_ => npgsqlConnectionString, healthQuery, connectionAction, name, failureStatus, tags, timeout));
 }
コード例 #4
0
 public static void ConfigureNpgsql(this IServiceCollection services, string connectionString, int poolSize, IHealthChecksBuilder checksBuilder, HealthChecksUIBuilder healthChecksUI)
 {
     services.AddEntityFrameworkNpgsql();
     services.AddSingleton <IDataBaseModelBuilderOptions>(c => new NpgsqlModelBuilderOptions());
     services.AddDbContextPool <ApplicationDbContext>(builder =>
     {
         builder.UseNpgsql(connectionString, s => s.MigrationsAssembly("IoTSharp.Data.PostgreSQL"));
         builder.UseInternalServiceProvider(services.BuildServiceProvider());
     }
                                                      , poolSize);
     checksBuilder.AddNpgSql(connectionString, name: "IoTSharp.Data.PostgreSQL");
     healthChecksUI.AddPostgreSqlStorage(connectionString);
 }
コード例 #5
0
        public static IHealthChecksBuilder AddDependencies(
            this IHealthChecksBuilder builder,
            List <Dependency> dependencies)
        {
            foreach (var dependencia in dependencies)
            {
                string nomeDependencia = dependencia.Name.ToLower();

                if (nomeDependencia.StartsWith("postgres-"))
                {
                    builder = builder.AddNpgSql(dependencia.ConnectionString, name: dependencia.Name);
                }
            }

            return(builder);
        }
コード例 #6
0
        private static void DoAdd(IServiceCollection services, PostgresServiceInfo info, IConfiguration config, ServiceLifetime contextLifetime, IHealthChecksBuilder healthChecksBuilder)
        {
            Type postgresConnection = ConnectorHelpers.FindType(PostgreSqlTypeLocator.Assemblies, PostgreSqlTypeLocator.ConnectionTypeNames);
            var  postgresConfig     = new PostgresProviderConnectorOptions(config);
            var  factory            = new PostgresProviderConnectorFactory(info, postgresConfig, postgresConnection);

            services.Add(new ServiceDescriptor(typeof(IDbConnection), factory.Create, contextLifetime));
            services.Add(new ServiceDescriptor(postgresConnection, factory.Create, contextLifetime));
            if (healthChecksBuilder == null)
            {
                services.Add(new ServiceDescriptor(typeof(IHealthContributor), ctx => new RelationalHealthContributor((IDbConnection)factory.Create(ctx), ctx.GetService <ILogger <RelationalHealthContributor> >()), ServiceLifetime.Singleton));
            }
            else
            {
                healthChecksBuilder.AddNpgSql(factory.CreateConnectionString());
            }
        }
コード例 #7
0
        public static void AddIdSHealthChecks <TConfigurationDbContext, TPersistedGrantDbContext, TIdentityDbContext,
                                               TLogDbContext, TAuditLoggingDbContext, TDataProtectionDbContext, TAuditLog>
            (this IHealthChecksBuilder healthChecksBuilder, AdminConfiguration adminConfiguration,
            ConnectionStringsConfiguration connectionStringsConfiguration, DatabaseProviderConfiguration databaseProviderConfiguration)
            where TConfigurationDbContext : DbContext, IAdminConfigurationDbContext
            where TPersistedGrantDbContext : DbContext, IAdminPersistedGrantDbContext
            where TIdentityDbContext : DbContext
            where TLogDbContext : DbContext, IAdminLogDbContext
            where TAuditLoggingDbContext : DbContext, IAuditLoggingDbContext <TAuditLog>
            where TDataProtectionDbContext : DbContext, IDataProtectionKeyContext
            where TAuditLog : AuditLog
        {
            var configurationDbConnectionString   = connectionStringsConfiguration.ConfigurationDbConnection;
            var persistedGrantsDbConnectionString = connectionStringsConfiguration.PersistedGrantDbConnection;
            var identityDbConnectionString        = connectionStringsConfiguration.IdentityDbConnection;
            var logDbConnectionString             = connectionStringsConfiguration.AdminLogDbConnection;
            var auditLogDbConnectionString        = connectionStringsConfiguration.AdminAuditLogDbConnection;
            var dataProtectionDbConnectionString  = connectionStringsConfiguration.DataProtectionDbConnection;

            var identityServerUri = adminConfiguration.IdentityServerBaseUrl;

            healthChecksBuilder = healthChecksBuilder
                                  .AddDbContextCheck <TConfigurationDbContext>("ConfigurationDbContext")
                                  .AddDbContextCheck <TPersistedGrantDbContext>("PersistedGrantsDbContext")
                                  .AddDbContextCheck <TIdentityDbContext>("IdentityDbContext")
                                  .AddDbContextCheck <TLogDbContext>("LogDbContext")
                                  .AddDbContextCheck <TAuditLoggingDbContext>("AuditLogDbContext")
                                  .AddDbContextCheck <TDataProtectionDbContext>("DataProtectionDbContext")

                                  .AddIdentityServer(new Uri(identityServerUri), "Identity Server");

            var serviceProvider = healthChecksBuilder.Services.BuildServiceProvider();
            var scopeFactory    = serviceProvider.GetRequiredService <IServiceScopeFactory>();

            using (var scope = scopeFactory.CreateScope())
            {
                var configurationTableName  = DbContextHelpers.GetEntityTable <TConfigurationDbContext>(scope.ServiceProvider);
                var persistedGrantTableName = DbContextHelpers.GetEntityTable <TPersistedGrantDbContext>(scope.ServiceProvider);
                var identityTableName       = DbContextHelpers.GetEntityTable <TIdentityDbContext>(scope.ServiceProvider);
                var logTableName            = DbContextHelpers.GetEntityTable <TLogDbContext>(scope.ServiceProvider);
                var auditLogTableName       = DbContextHelpers.GetEntityTable <TAuditLoggingDbContext>(scope.ServiceProvider);
                var dataProtectionTableName = DbContextHelpers.GetEntityTable <TDataProtectionDbContext>(scope.ServiceProvider);

                switch (databaseProviderConfiguration.ProviderType)
                {
                case DatabaseProviderType.SqlServer:
                    healthChecksBuilder
                    .AddSqlServer(configurationDbConnectionString, name: "ConfigurationDb",
                                  healthQuery: $"SELECT TOP 1 * FROM dbo.[{configurationTableName}]")
                    .AddSqlServer(persistedGrantsDbConnectionString, name: "PersistentGrantsDb",
                                  healthQuery: $"SELECT TOP 1 * FROM dbo.[{persistedGrantTableName}]")
                    .AddSqlServer(identityDbConnectionString, name: "IdentityDb",
                                  healthQuery: $"SELECT TOP 1 * FROM dbo.[{identityTableName}]")
                    .AddSqlServer(logDbConnectionString, name: "LogDb",
                                  healthQuery: $"SELECT TOP 1 * FROM dbo.[{logTableName}]")
                    .AddSqlServer(auditLogDbConnectionString, name: "AuditLogDb",
                                  healthQuery: $"SELECT TOP 1 * FROM dbo.[{auditLogTableName}]")
                    .AddSqlServer(dataProtectionDbConnectionString, name: "DataProtectionDb",
                                  healthQuery: $"SELECT TOP 1 * FROM dbo.[{dataProtectionTableName}]");
                    break;

                case DatabaseProviderType.PostgreSQL:
                    healthChecksBuilder
                    .AddNpgSql(configurationDbConnectionString, name: "ConfigurationDb",
                               healthQuery: $"SELECT * FROM \"{configurationTableName}\" LIMIT 1")
                    .AddNpgSql(persistedGrantsDbConnectionString, name: "PersistentGrantsDb",
                               healthQuery: $"SELECT * FROM \"{persistedGrantTableName}\" LIMIT 1")
                    .AddNpgSql(identityDbConnectionString, name: "IdentityDb",
                               healthQuery: $"SELECT * FROM \"{identityTableName}\" LIMIT 1")
                    .AddNpgSql(logDbConnectionString, name: "LogDb",
                               healthQuery: $"SELECT * FROM \"{logTableName}\" LIMIT 1")
                    .AddNpgSql(auditLogDbConnectionString, name: "AuditLogDb",
                               healthQuery: $"SELECT * FROM \"{auditLogTableName}\"  LIMIT 1")
                    .AddNpgSql(dataProtectionDbConnectionString, name: "DataProtectionDb",
                               healthQuery: $"SELECT * FROM \"{dataProtectionTableName}\"  LIMIT 1");
                    break;

                case DatabaseProviderType.MySql:
                    healthChecksBuilder
                    .AddMySql(configurationDbConnectionString, name: "ConfigurationDb")
                    .AddMySql(persistedGrantsDbConnectionString, name: "PersistentGrantsDb")
                    .AddMySql(identityDbConnectionString, name: "IdentityDb")
                    .AddMySql(logDbConnectionString, name: "LogDb")
                    .AddMySql(auditLogDbConnectionString, name: "AuditLogDb")
                    .AddMySql(dataProtectionDbConnectionString, name: "DataProtectionDb");
                    break;

                default:
                    throw new NotImplementedException($"Health checks not defined for database provider {databaseProviderConfiguration.ProviderType}");
                }
            }
        }
コード例 #8
0
        /// <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);
        }