/// <summary>
        ///
        /// </summary>
        /// <param name="connectionString">RavenDB connection string</param>
        /// <param name="database">Optional : database name to connect to</param>
        /// <returns></returns>
        public static HealthResponse CheckHealth(string connectionString, string database = null)
        {
            try
            {
                ConnectionStringParser <RavenConnectionStringOptions> parser = ConnectionStringParser <RavenConnectionStringOptions> .FromConnectionString(connectionString);

                parser.Parse();
                var store = new Raven.Client.Document.DocumentStore
                {
                    Url             = parser.ConnectionStringOptions.Url,
                    DefaultDatabase = database == null ? parser.ConnectionStringOptions.DefaultDatabase : database
                };
                store.Initialize();
                // Client doesn't seem to throw an exception until we try to do something so let's just do something simple and get the build number of the server.
                var build = store.DatabaseCommands.GlobalAdmin.GetBuildNumber();
                // Dispose the store object
                store.Dispose();

                return(HealthResponse.Healthy(new { server = store.Url, database = store.DefaultDatabase, serverBuild = build.BuildVersion }));
            }
            catch (Exception ex)
            {
                return(HealthResponse.Unhealthy(ex));
            }
        }
Beispiel #2
0
 public static HealthResponse CheckHealth(string connectionString)
 {
     try
     {
         var client = new MongoClient(connectionString);
         return(HealthResponse.Healthy(new { databases = client.ListDatabases().ToList(), server = client.Settings.Server }));
     }
     catch (Exception ex)
     {
         return(HealthResponse.Unhealthy(ex));
     }
 }
Beispiel #3
0
        public void Configuration(IAppBuilder app)
        {
            // Setup logging
            ApplicationLog.AddConsole();
            Logger logger = ApplicationLog.CreateLogger <Startup>();

            logger.Info("Initializing service");

            // Build an IConfiguration instance using the ConfigurationBuilder as normal
            Dictionary <string, string> collection = new Dictionary <string, string>()
            {
                { "key1", "value1" }, { "key2", "value2" }
            };
            var config1 = new ConfigurationBuilder().AddInMemoryCollection(collection).Build();
            var config3 = new ConfigurationBuilder().AddJsonFile("Config.json").Build();

            // AppConfig is a static class that groups together instances of IConfiguration and makes them available statically anywhere in the application
            AppConfig.AddConfigurationObject(config1, "memorySource");
            AppConfig.AddConfigurationObject(config3, "jsonSource");

            // The above configuration sources can now be referenced easily with a static helper function
            Console.WriteLine("key1 key in memorySource: " + AppConfig.Get("memorySource", "key1"));
            Console.WriteLine("config:setting key in jsonSource: " + AppConfig.Get("jsonSource", "config:setting"));

            // Runtime configuration can be updated easily as well
            AppConfig.Set("jsonSource", "config:setting", "http://localhost:5001");
            Console.WriteLine("Modified config:setting key in jsonSource: " + AppConfig.Get("jsonSource", "config:setting"));

            // Redis health check (Requires StackExchange.Redis)
            //HealthCheckRegistry.RegisterHealthCheck("Redis", () => RedisHealthCheck.CheckHealth("localhost"));
            // PostgreSQL health check (Requires Npgsql)
            //HealthCheckRegistry.RegisterHealthCheck("Postgresql", () => PostgresqlHealthCheck.CheckHealth("Host=localhost;Username=postgres;Password=postgres;Database=postgres"));
            // SQL Server health check (Requires System.Data.SqlClient)
            //HealthCheckRegistry.RegisterHealthCheck("SqlServer", () => SqlServerCheck.CheckHealth("Server=localhost;Database=master;User Id=sa;Password=password; "));
            // HealthCheckRegistry.RegisterHealthCheck("mongodb", () => MongoHealthCheck.CheckHealth("mongodb://localhost:27017"));

            /*
             *   Health checks are simply functions that return either healthy or unhealthy with an optional message string
             */
            HealthCheckRegistry.RegisterHealthCheck("MyCustomMonitor", () => HealthResponse.Healthy("Test Message"));
            HealthCheckRegistry.RegisterHealthCheck("MyCustomMonitor2", () => HealthResponse.Healthy("Test Message2"));
            HealthCheckRegistry.RegisterHealthCheck("SampleOperation", () => SampleHealthCheckOperation());

            // Activate the info endpoint
            app.UseInfoEndpoint();

            // Activate the environment endpoint
            app.UseEnvironmentEndpoint();

            // Activate the health endpoint
            app.UseHealthEndpoint();
        }
 /// <summary>
 /// Check that a connection to Redis can be established and attempt to pull back server statistics
 /// </summary>
 /// <param name="connectionString">A StackExchange.Redis connection string</param>
 /// <returns>A <see cref="HealthResponse"/> object that contains the return status of this health check</returns>
 public static HealthResponse CheckHealth(string connectionString)
 {
     try
     {
         ConnectionMultiplexer conn = ConnectionMultiplexer.Connect(connectionString);
         string[] server            = conn.GetStatus().Split(';');
         conn.Close();
         return(HealthResponse.Healthy(server[0]));
     }
     catch (Exception e)
     {
         return(HealthResponse.Unhealthy(e));
     }
 }
 /// <summary>
 /// Check that a connection can be established to Postgresql and return the server version
 /// </summary>
 /// <param name="connectionString">An Npgsql connection string</param>
 /// <returns>A <see cref="HealthResponse"/> object that contains the return status of this health check</returns>
 public static HealthResponse CheckHealth(string connectionString)
 {
     try
     {
         SqlConnection conn = new SqlConnection(connectionString);
         conn.Open();
         string host    = conn.DataSource;
         string version = conn.ServerVersion;
         conn.Close();
         conn.Dispose();
         return(HealthResponse.Healthy(new { host = host, version = version }));
     }
     catch (Exception e)
     {
         return(HealthResponse.Unhealthy(e));
     }
 }
 /// <summary>
 /// Check that a connection can be established to Postgresql and return the server version
 /// </summary>
 /// <param name="connectionString">An Npgsql connection string</param>
 /// <returns>A <see cref="HealthResponse"/> object that contains the return status of this health check</returns>
 public static HealthResponse CheckHealth(string connectionString)
 {
     try
     {
         NpgsqlConnection conn = new NpgsqlConnection(connectionString);
         NpgsqlConnection.ClearPool(conn);
         conn.Open();
         string host    = conn.Host;
         string version = conn.PostgreSqlVersion.ToString();
         int    port    = conn.Port;
         conn.Close();
         conn.Dispose();
         return(HealthResponse.Healthy(new { host = host, port = port, version = version }));
     }
     catch (Exception e)
     {
         return(HealthResponse.Unhealthy(e));
     }
 }
Beispiel #7
0
        /// <summary>
        /// Add services to the application and configure service provider
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration root of the application</param>
        /// <returns>Configured service provider</returns>
        public static (IEngine, NetProOption) ConfigureApplicationServices(this IServiceCollection services,
                                                                           IConfiguration configuration, IHostEnvironment hostEnvironment)
        {
            var netProOption = services.ConfigureStartupConfig <NetProOption>(configuration.GetSection(nameof(NetProOption)));

            services.ConfigureStartupConfig <HostingConfig>(configuration.GetSection("Hosting"));
            if (string.IsNullOrWhiteSpace(netProOption.ApplicationName))
            {
                netProOption.ApplicationName = hostEnvironment.ApplicationName;
            }

            if (hostEnvironment.EnvironmentName == Environments.Development)
            {
                Console.WriteAscii("Hello NetPro", Color.FromArgb(244, 212, 255));
                //使用dotnet watch run  启动后可以调试此进程id
                Console.WriteLine($"[{DateTime.Now:HH:mm:ss} {hostEnvironment.EnvironmentName}] dotnet process id:{Process.GetCurrentProcess().Id}");
            }

            //most of API providers require TLS 1.2 nowadays
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            services.AddHttpContextAccessor();

            //create default file provider
            CoreHelper.DefaultFileProvider = new NetProFileProvider(hostEnvironment);

            //日志初始化配置
            services.ConfigureSerilogConfig(configuration);
            //create, initialize and configure the engine
            var engine = EngineContext.Create();

            engine.ConfigureServices(services, configuration, netProOption);

            if (int.TryParse(configuration.GetValue <string>("NetPro:ThreadMinCount"), out int threadMinCount) && threadMinCount > 2)
            {
                if (ThreadPool.SetMinThreads(Environment.ProcessorCount * threadMinCount, Environment.ProcessorCount * threadMinCount))
                {
                    ThreadPool.GetMinThreads(out int work, out int comple);
                    ThreadPool.GetAvailableThreads(out int worktemp, out int completemp);
                    Console.WriteLine($"核心数为:{Environment.ProcessorCount}--默认线程最小为:{work}--Available:{worktemp}");
                }
                else
                {
                    Console.WriteLine("最小线程数设置大于系统提供,设置失效!!");
                }
            }

            if (!configuration.GetValue <bool>("Apollo:Enabled", false))
            {
                HealthCheckRegistry.RegisterHealthCheck("apollo", () =>
                {
                    var uri = new Uri(configuration.GetValue <string>("Apollo:MetaServer"));
                    using (var tcpClient = new System.Net.Sockets.TcpClient(uri.Host, uri.Port))
                    {
                        if (tcpClient.Connected)
                        {
                            Console.WriteLine($"pollo:Env:{configuration.GetValue<string>("Apollo:Env")}");
                            Console.WriteLine($"Apollo:Cluster:{configuration.GetValue<string>("Apollo:Cluster")}");
                            return(HealthResponse.Healthy($"{uri.Host}:{uri.Port}连接正常--pollo:Env:{configuration.GetValue<string>("Apollo:Env")}--Apollo:Cluster:{configuration.GetValue<string>("Apollo:Cluster")}"));
                        }
                        return(HealthResponse.Unhealthy($"Apollo{uri.Host}:{uri.Port}连接不正常"));
                    }
                });
            }
            return(engine, netProOption);
        }
Beispiel #8
0
        public void Configure(IApplicationBuilder app)
        {
            // Add logging
            ApplicationLog.AddConsole();
            ApplicationLog.AddFile("Test.log");
            Logger logger = ApplicationLog.CreateLogger <Startup>();

            logger.Info("Initializing service");

            // Build an IConfiguration instance using the ConfigurationBuilder as normal
            Dictionary <string, string> collection = new Dictionary <string, string>()
            {
                { "key1", "value1" }, { "key2", "value2" }
            };
            var config1 = new ConfigurationBuilder().AddInMemoryCollection(collection).Build();
            var config2 = new ConfigurationBuilder().SetBasePath(_env.ContentRootPath).AddIniFile("hosting.ini").Build();
            var config3 = new ConfigurationBuilder().SetBasePath(_env.ContentRootPath).AddJsonFile("config.json").Build();

            // AppConfig is a static class that groups together instances of IConfiguration and makes them available statically anywhere in the application
            AppConfig.AddConfigurationObject(config1, "memorySource");
            AppConfig.AddConfigurationObject(config2, "iniSource");
            AppConfig.AddConfigurationObject(config3, "jsonSource");

            // The above configuration sources can now be referenced easily with a static helper function
            Console.WriteLine("key1 key in memorySource: " + AppConfig.Get("memorySource", "key1"));
            Console.WriteLine("server.urls key in iniSource: " + AppConfig.Get("iniSource", "server.urls"));

            // Runtime configuration can be updated easily as well
            AppConfig.Set("iniSource", "server.urls", "http://localhost:5001");
            Console.WriteLine("Modified server.urls key in iniSource: " + AppConfig.Get("iniSource", "server.urls"));

            /*
             *   Health checks are simply functions that return either healthy or unhealthy with an optional message string
             */
            HealthCheckRegistry.RegisterHealthCheck("MyCustomMonitor", () => HealthResponse.Healthy("Test Message"));
            HealthCheckRegistry.RegisterHealthCheck("MyCustomMonitor2", () => HealthResponse.Healthy("Test Message2"));
            HealthCheckRegistry.RegisterHealthCheck("SampleOperation", () => SampleHealthCheckOperation());

            /*
             *   Some bundled health checks that can be used
             */
            // Redis health check (Requires StackExchange.Redis)
            //HealthCheckRegistry.RegisterHealthCheck("Redis", () => RedisHealthCheck.CheckHealth("localhost"));
            // PostgreSQL health check (Requires Npgsql)
            //HealthCheckRegistry.RegisterHealthCheck("Postgresql", () => PostgresqlHealthCheck.CheckHealth("Host=localhost;Username=postgres;Password=postgres;Database=postgres"));
            // SQL Server health check (Requires System.Data.SqlClient)
            //HealthCheckRegistry.RegisterHealthCheck("SqlServer", () => SqlServerCheck.CheckHealth("Server=localhost;Database=master;User Id=sa;Password=password; "));
            // RavenDB health check
            //HealthCheckRegistry.RegisterHealthCheck("ravendb", () => RavenDbHealthCheck.CheckHealth("Url=http://192.168.153.55:8080;DefaultDatabase=<system>"));
            // MongoDB health check
            //HealthCheckRegistry.RegisterHealthCheck("mongodb", () => MongoHealthCheck.CheckHealth("mongodb://localhost:27017"));

            /*
             *  Uncomment the below line to only allow access to the actuator endpoints from localhost
             *
             *  Allowed patterns are:
             *
             *  1. CIDR range: "192.168.0.0/24", "fe80::/10"
             *  2. Single address: "127.0.0.1", ":;1"
             *  3. Begin end range: "169.258.0.0-169.258.0.255"
             *  4. Bit mask range: "192.168.0.0/255.255.255.0"
             *
             *  NOTE: Currently this feature is not supported under Kestrel self-host as it does not set the client's IP address in HttpContext
             */

            //MicroserviceBootstrap.AllowedIpAddresses = IpAddressRange.Parse("127.0.0.0/8");

            // Activate /health endpoint
            app.UseHealthEndpoint();

            /*
             * Activate /env endpoint
             *
             * The ApplicationConfiguration element of the env endpoint will only contain data if the AppConfig helper class is
             * used to manage application configuration
             */
            app.UseEnvironmentEndpoint();

            /*
             *   The compiler directive below is only required if you plan to target .NET core as well as the full CLR
             *   If you don't target dnxcore50 in your project.json you can remove the below #if and just call UseInfoEndpoint()
             *   without any parameters
             */

            // Activate /info endpoint
#if NETCOREAPP1_0
            // Required for .NET Core until the relevant APIs are added
            app.UseInfoEndpoint(typeof(Startup).GetTypeInfo().Assembly.GetName());
#else
            app.UseInfoEndpoint();
#endif
        }
        /// <summary>
        /// Add services to the application and configure service provider
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration root of the application</param>
        /// <returns>Configured service provider</returns>
        public static (IEngine, NetProOption) ConfigureApplicationServices(this IServiceCollection services,
                                                                           IConfiguration configuration, IHostEnvironment hostEnvironment)
        {
            //文件查找组件注入
            services.AddFileProcessService();
            var netProOption = services.ConfigureStartupConfig <NetProOption>(configuration.GetSection(nameof(NetProOption)));

            services.ConfigureStartupConfig <HostingConfig>(configuration.GetSection("Hosting"));
            if (string.IsNullOrWhiteSpace(netProOption.ApplicationName))
            {
                netProOption.ApplicationName = hostEnvironment.ApplicationName;
            }

            if (hostEnvironment.EnvironmentName == Environments.Development)
            {
                Console.Title           = hostEnvironment.ApplicationName;
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine(Figgle.FiggleFonts.Varsity.Render(new string(new char[] { 'N', 'e', 't', 'P', 'r', 'o' })));
                Console.ResetColor();
                //使用dotnet watch run  启动后可以调试此进程id
                Console.WriteLine($"[{DateTime.Now:HH:mm:ss} {hostEnvironment.EnvironmentName}] dotnet process id:{Process.GetCurrentProcess().Id}");
            }

            //most of API providers require TLS 1.2 nowadays
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            services.AddHttpContextAccessor();
            services.AddHttpClient();
            ////create default file provider
            //CoreHelper.DefaultFileProvider = new NetProFileProvider(hostEnvironment);

            //日志初始化配置
            services.ConfigureSerilogConfig(configuration);
            //create, initialize and configure the engine
            var engine = EngineContext.Create();

            engine.ConfigureServices(services, configuration, netProOption);

            if (netProOption.ThreadMinCount > 2)
            {
                if (ThreadPool.SetMinThreads(Environment.ProcessorCount * netProOption.ThreadMinCount, Environment.ProcessorCount * netProOption.ThreadMinCount))
                {
                    ThreadPool.GetMinThreads(out int work, out int comple);
                    ThreadPool.GetAvailableThreads(out int worktemp, out int completemp);
                    Console.WriteLine($"[{DateTime.Now:HH:mm:ss} 核心数为:{Environment.ProcessorCount}--默认线程最小为:{work}--Available:{worktemp}");
                }
                else
                {
                    Console.WriteLine($"[{DateTime.Now:HH:mm:ss} 最小线程数设置大于系统提供,设置失效!!");
                }
            }

            if (configuration.GetValue <bool>("Apollo:Enabled", false))
            {
                Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] apollo已开启");
                Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Apollo MetaServer={configuration.GetValue<string>("Apollo:MetaServer")}");

                HealthCheckRegistry.RegisterHealthCheck("apollo", () =>
                {
                    var uri = new Uri(configuration.GetValue <string>("Apollo:MetaServer"));
                    using (var tcpClient = new System.Net.Sockets.TcpClient(uri.Host, uri.Port))
                    {
                        if (tcpClient.Connected)
                        {
                            Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] pollo:Env={configuration.GetValue<string>("Apollo:Env")}");
                            Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Apollo:Cluster={configuration.GetValue<string>("Apollo:Cluster")}");
                            return(HealthResponse.Healthy($"{uri.Host}:{uri.Port}connection successful; pollo:Env={configuration.GetValue<string>("Apollo:Env")}--Apollo:Cluster={configuration.GetValue<string>("Apollo:Cluster")}"));
                        }
                        return(HealthResponse.Unhealthy($"Apollo{uri.Host}:{uri.Port} connection failed"));
                    }