Ejemplo n.º 1
0
        /// <summary>
        /// 执行注册
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="endPoint"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        private bool ExecuteRegister(string serviceName, DnsEndPoint endPoint, Action <string> callback)
        {
            var serviceId = BuildServiceId(serviceName, endPoint);
            var checkId   = BuildCheckId(serviceName, endPoint);
            var checkName = BuildCheckName(serviceName, endPoint);
            var acr       = new AgentCheckRegistration
            {
                ID       = checkId,
                Name     = checkName,
                TCP      = $"{endPoint.Host}:{endPoint.Port}", //尝试连接到给定的主机/ IP地址和端口号。如果可以建立连接,则将健康检查状态视为通过
                Interval = ConsulTimeConfig.HealthCheckInterval,
                Status   = HealthStatus.Passing,
                DeregisterCriticalServiceAfter = ConsulTimeConfig.RemoveServerInterval,
            };
            var asr = new AgentServiceRegistration
            {
                ID      = serviceId,
                Name    = serviceName,
                Address = endPoint.Host,
                Port    = endPoint.Port,
                Check   = acr
            };
            var res = _consulClient.Agent.ServiceRegister(asr).Result;

            if (res.StatusCode != HttpStatusCode.OK)
            {
                return(false);
            }
            callback?.Invoke(serviceId);
            return(true);
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _registrationId = $"{_config.Service}-{Guid.NewGuid()}";
            var registration = new AgentServiceRegistration
            {
                ID      = _registrationId,
                Name    = _config.Service,
                Address = _config.Address,
                Port    = _config.Port
            };

            if (_config.HealthCheckEnabled)
            {
                var healthCheckEndpoint = _config.HealthCheckEndpoint;
                var healthCheckInterval = _config.HealthCheckInterval <= 0 ? 5 : _config.HealthCheckInterval;
                var removeAfterInterval = _config.RemoveAfterInterval <= 0 ? 10 : _config.RemoveAfterInterval;

                var tlsSkipVerify = _config.Address.StartsWith("https", StringComparison.InvariantCultureIgnoreCase);

                var check = new AgentCheckRegistration()
                {
                    Interval = TimeSpan.FromSeconds(healthCheckInterval),
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(removeAfterInterval),
                    HTTP          = $"{_config.Address}:{_config.Port}{healthCheckEndpoint}",
                    TLSSkipVerify = tlsSkipVerify // if is hosted as tls
                };

                registration.Checks = new AgentServiceCheck[] { check };
            }

            await _client.Agent.ServiceDeregister(registration.ID, cancellationToken);

            await _client.Agent.ServiceRegister(registration, cancellationToken);
        }
Ejemplo n.º 3
0
        private static void RegServer(IConfiguration configuration, IConsulClient consulClient)
        {
            //服务组名
            string consulGroup = configuration["consulGroup"];
            //服务IP
            string ip = configuration["ip"];
            //服务端口
            int port = int.Parse(configuration["port"]);
            //服务ID
            string id = $"{consulGroup}_{ip}_{port}";
            //服务健康检查
            var check = new AgentCheckRegistration()
            {
                HTTP     = $"http://{ip}:{port}/Health",
                Interval = TimeSpan.FromSeconds(10),
                Timeout  = TimeSpan.FromSeconds(5),
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(60)
            };
            //服务注册类
            var regist = new AgentServiceRegistration()
            {
                Name    = consulGroup,
                Address = ip,
                Port    = port,
                ID      = id,
                Check   = check
            };

            //注册服务
            consulClient.Agent.ServiceRegister(regist);
        }
Ejemplo n.º 4
0
        public async Task Agent_Checks_ServiceBound()
        {
            var svcID      = KVTest.GenerateTestKeyName();
            var serviceReg = new AgentServiceRegistration
            {
                Name = svcID
            };
            await _client.Agent.ServiceRegister(serviceReg);

            var reg = new AgentCheckRegistration
            {
                Name      = "redischeck",
                ServiceID = svcID,
                TTL       = TimeSpan.FromSeconds(15),
                DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(90)
            };
            await _client.Agent.CheckRegister(reg);

            var checks = await _client.Agent.Checks();

            Assert.True(checks.Response.ContainsKey("redischeck"));
            Assert.Equal(svcID, checks.Response["redischeck"].ServiceID);

            await _client.Agent.CheckDeregister("redischeck");

            await _client.Agent.ServiceDeregister(svcID);
        }
Ejemplo n.º 5
0
        public Entry RegisterService(string name, int port)
        {
            var hostName  = Dns.GetHostName();
            var serviceId = $"{hostName}-{name}-{port}";
            var checkId   = $"{hostName}-{port}";

            var acr = new AgentCheckRegistration
            {
                TCP      = $"{hostName}:{port}",
                Name     = checkId,
                ID       = checkId,
                Interval = ConsulConfig.CheckInterval,
                DeregisterCriticalServiceAfter = ConsulConfig.CriticalInterval
            };

            var asr = new AgentServiceRegistration
            {
                Address = hostName,
                ID      = serviceId,
                Name    = name,
                Port    = port,
                Check   = acr
            };

            var res = _client.Agent.ServiceRegister(asr).Result;

            if (res.StatusCode != HttpStatusCode.OK)
            {
                throw new ApplicationException($"Failed to register service {name} on port {port}");
            }

            return(new Entry(this, name, port, serviceId));
        }
Ejemplo n.º 6
0
        public async Task <string> RegisterHealthCheckAsync(string serviceName, string serviceId, Uri checkUri, TimeSpan?interval = null, string notes = null)
        {
            if (checkUri == null)
            {
                throw new ArgumentNullException(nameof(checkUri));
            }

            var checkId           = GetCheckId(serviceId, checkUri);
            var checkRegistration = new AgentCheckRegistration
            {
                ID        = checkId,
                Name      = serviceName,
                Notes     = notes,
                ServiceID = serviceId,
                HTTP      = checkUri.ToString(),
                //GRPC = checkUri.ToString(),
                //GRPCUseTLS = false,
                Interval = interval,
                Timeout  = TimeSpan.FromSeconds(15),
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(15)
            };
            var writeResult = await _consul.Agent.CheckRegister(checkRegistration);

            bool   isSuccess = writeResult.StatusCode == HttpStatusCode.OK;
            string success   = isSuccess ? "succeeded" : "failed";

            return(checkId);
        }
Ejemplo n.º 7
0
        public void Agent_Checks_ServiceBound()
        {
            var client = new Client();

            var serviceReg = new AgentServiceRegistration()
            {
                Name = "redis"
            };

            client.Agent.ServiceRegister(serviceReg);

            var reg = new AgentCheckRegistration()
            {
                Name      = "redischeck",
                ServiceID = "redis",
                TTL       = TimeSpan.FromSeconds(15)
            };

            client.Agent.CheckRegister(reg);

            var checks = client.Agent.Checks();

            Assert.IsTrue(checks.Response.ContainsKey("redischeck"));
            Assert.AreEqual("redis", checks.Response["redischeck"].ServiceID);

            client.Agent.CheckDeregister("redischeck");
            client.Agent.ServiceDeregister("redis");
        }
Ejemplo n.º 8
0
        public async Task Agent_Checks_Docker()
        {
            var svcID      = KVTest.GenerateTestKeyName();
            var serviceReg = new AgentServiceRegistration
            {
                Name = svcID
            };
            await _client.Agent.ServiceRegister(serviceReg);

            var reg = new AgentCheckRegistration
            {
                Name              = "redischeck",
                ServiceID         = svcID,
                DockerContainerID = "f972c95ebf0e",
                Args              = new string[] { "/bin/true" },
                Shell             = "/bin/bash",
                Interval          = TimeSpan.FromSeconds(10)
            };
            await _client.Agent.CheckRegister(reg);

            var checks = await _client.Agent.Checks();

            Assert.True(checks.Response.ContainsKey("redischeck"));
            Assert.Equal(svcID, checks.Response["redischeck"].ServiceID);

            await _client.Agent.CheckDeregister("redischeck");

            await _client.Agent.ServiceDeregister(svcID);
        }
Ejemplo n.º 9
0
        public virtual void AddHeadlthCheck(ICollection <Service> services)
        {
            if (services.Count == 0)
            {
                return;
            }
            IServiceHealthCheckCreator checkCreator = GlobalSetting.GetService <IServiceHealthCheckCreator>();

            if (checkCreator == null)
            {
                throw new NullReferenceException("IServiceHealthCheckCreator接口不能为空");
            }
            AgentCheckRegistration check = checkCreator.CreateCheck();

            if (check == null)
            {
                throw new NullReferenceException("无法创建健康检查实例");
            }
            var task = _client.Agent.CheckRegister(check);

            task.ConfigureAwait(false);
            task.Wait(_waitConsulTime);
            if (task.Result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception("添加健康检查信息失败");
            }
            checkCreator.EnableHealthCheckInterface();
        }
Ejemplo n.º 10
0
        public async Task <bool> RegisteAsync()
        {
            var check = new AgentCheckRegistration()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromMilliseconds(10),
                Status  = HealthStatus.Critical,
                TTL     = TimeSpan.FromMilliseconds(Options.TTL),
                Timeout = TimeSpan.FromMilliseconds(Options.Timeout)
            };
            var service = new AgentServiceRegistration()
            {
                ID      = Options.ServiceID,
                Name    = Options.ServiceName,
                Tags    = Options.Tags,
                Port    = Options.Port,
                Address = Options.Address,
                Check   = check
            };

            await _client.Agent.ServiceRegister(service);

            var task = Task.Run(() =>
            {
                while (!_isCancel)
                {
                    _client.Agent.PassTTL($"service:{service.ID}", "pass");
                    System.Threading.Thread.Sleep((int)(Options.TTL * 0.9));
                }
            });

            return(true);
        }
Ejemplo n.º 11
0
        private string GetHealthCheckType(AgentCheckRegistration heathCheck)
        {
            if (heathCheck.TTL != null)
            {
                return("TTL");
            }
            if (heathCheck.HTTP != null)
            {
                return("HTTP");
            }
            if (heathCheck.TCP != null)
            {
                return("TCP");
            }
            if (heathCheck.Script != null)
            {
                return("SCRIPT");
            }
            if (heathCheck.Shell != null)
            {
                return("DOCKER");
            }

            return("Unknown");
        }
Ejemplo n.º 12
0
        public async Task Agent_Checks_ServiceBound()
        {
            var client = new ConsulClient();

            var serviceReg = new AgentServiceRegistration()
            {
                Name = "redis"
            };
            await client.Agent.ServiceRegister(serviceReg);

            var reg = new AgentCheckRegistration()
            {
                Name      = "redischeck",
                ServiceID = "redis",
                TTL       = TimeSpan.FromSeconds(15),
                DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(90)
            };
            await client.Agent.CheckRegister(reg);

            var checks = await client.Agent.Checks();

            Assert.True(checks.Response.ContainsKey("redischeck"));
            Assert.Equal("redis", checks.Response["redischeck"].ServiceID);

            await client.Agent.CheckDeregister("redischeck");

            await client.Agent.ServiceDeregister("redis");
        }
Ejemplo n.º 13
0
        public async Task Agent_Checks_Docker()
        {
            using (var client = new ConsulClient())
            {
                var serviceReg = new AgentServiceRegistration()
                {
                    Name = "redis"
                };
                await client.Agent.ServiceRegister(serviceReg);

                var reg = new AgentCheckRegistration()
                {
                    Name              = "redischeck",
                    ServiceID         = "redis",
                    DockerContainerID = "f972c95ebf0e",
                    Script            = "/bin/true",
                    Shell             = "/bin/bash",
                    Interval          = TimeSpan.FromSeconds(10)
                };
                await client.Agent.CheckRegister(reg);

                var checks = await client.Agent.Checks();

                Assert.True(checks.Response.ContainsKey("redischeck"));
                Assert.Equal("redis", checks.Response["redischeck"].ServiceID);

                await client.Agent.CheckDeregister("redischeck");

                await client.Agent.ServiceDeregister("redis");
            }
        }
Ejemplo n.º 14
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            // Create a linked token so we can trigger cancellation outside of this token's cancellation
            _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            var features  = _server.Features;
            var addresses = features.Get <IServerAddressesFeature>();
            var address   = addresses.Addresses.First();

            var uri = new Uri(address);

            _registrationID = $"{_consulConfig.Value.ServiceID}-{uri.Port}";

            var check = new AgentCheckRegistration();

            check.HTTP     = $"http://{uri.Host}:{uri.Port}/healthcheck";
            check.Interval = new TimeSpan(0, 0, 1);

            var registration = new AgentServiceRegistration()
            {
                ID      = _registrationID,
                Name    = _consulConfig.Value.ServiceName,
                Address = uri.Host,
                Port    = uri.Port,
                Tags    = _consulConfig.Value.Tags.ToArray(),
                Check   = check
            };

            _logger.LogInformation("Registering in Consul");
            await _consulClient.Agent.ServiceDeregister(registration.ID, _cts.Token);

            await _consulClient.Agent.ServiceRegister(registration, _cts.Token);
        }
Ejemplo n.º 15
0
        public async Task <string> RegisterHealthCheckAsync(string serviceName, string serviceId, Uri checkUri, TimeSpan?interval = null, string notes = null)
        {
            if (checkUri == null)
            {
                throw new ArgumentNullException(nameof(checkUri));
            }

            var checkId           = GetCheckId(serviceId, checkUri);
            var checkRegistration = new AgentCheckRegistration
            {
                ID        = checkId,
                Name      = serviceName,
                Notes     = notes,
                ServiceID = serviceId,
                HTTP      = checkUri.ToString(),
                Interval  = interval
            };
            var writeResult = await _consul.Agent.CheckRegister(checkRegistration);

            bool   isSuccess = writeResult.StatusCode == HttpStatusCode.OK;
            string success   = isSuccess ? "succeeded" : "failed";

            s_log.Info($"Registration of health check with id {checkId} on {serviceName} with id {serviceId}" + success);

            return(checkId);
        }
Ejemplo n.º 16
0
        public void RegistServer(int port)
        {
            var hostName = "127.0.0.1";

            serviceId = $"http://{hostName}:{port}/Service/";
            var checkId = $"http://{hostName}:{port}";
            var name    = "mywcf";
            var acr     = new AgentCheckRegistration
            {
                HTTP     = serviceId,
                Name     = checkId,
                ID       = checkId,
                Interval = ConsulConfig.CheckInterval,
                DeregisterCriticalServiceAfter = ConsulConfig.CriticalInterval
            };

            var asr = new AgentServiceRegistration
            {
                Address = hostName,
                ID      = serviceId,
                Name    = name,
                Port    = port,
                Check   = acr
            };

            var res = _client.Agent.ServiceRegister(asr).Result;

            if (res.StatusCode != HttpStatusCode.OK)
            {
                throw new ApplicationException($"Failed to register service {name} on port {port}");
            }
            Console.ReadLine();
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="dnsEndPoint"></param>
        /// <param name="registered">注册成功后执行</param>
        /// <returns></returns>
        private bool RegisterService(string serviceName, DnsEndPoint dnsEndPoint, Action <Entry> registered = null)
        {
            var serviceId = GenServiceId(serviceName, dnsEndPoint);
            var checkId   = GenCheckId(serviceName, dnsEndPoint);
            var checkName = GenCheckName(serviceName, dnsEndPoint);
            var acr       = new AgentCheckRegistration
            {
                ID       = checkId,
                Name     = checkName,
                TCP      = $"{dnsEndPoint.Host}:{dnsEndPoint.Port}",
                Interval = ConsulTimespan.CheckInterval,
                Status   = HealthStatus.Passing,
                DeregisterCriticalServiceAfter = ConsulTimespan.CriticalInterval,
            };
            var asr = new AgentServiceRegistration
            {
                ID      = serviceId,
                Name    = serviceName,
                Address = dnsEndPoint.Host,
                Port    = dnsEndPoint.Port,
                Check   = acr
            };

            var res = _client.Agent.ServiceRegister(asr).Result;

            if (res.StatusCode != HttpStatusCode.OK)
            {
                return(false);
            }

            registered?.Invoke(new Entry(this, serviceId));
            return(true);
        }
Ejemplo n.º 18
0
        public string RegisterHealthCheck(URL checkUrl)
        {
            if (checkUrl == null)
            {
                throw new ArgumentNullException(nameof(checkUrl));
            }
            var      serviceId    = checkUrl.GetParameter(SERVICEID_KEY);
            var      checkId      = GetCheckId(serviceId, checkUrl);
            var      notes        = checkUrl.GetParameter(NOTES_KEY);
            TimeSpan?interval     = null;
            var      intervalPara = checkUrl.GetParameter <double>(INTERVAL_KEY, -1);

            if (intervalPara > 0)
            {
                interval = TimeSpan.FromSeconds(intervalPara);
            }
            var checkRegistration = new AgentCheckRegistration
            {
                ID        = checkId,
                Name      = checkUrl.ServiceInterface,
                Notes     = notes,
                ServiceID = serviceId,
                HTTP      = checkUrl.ToString(),
                Interval  = interval
            };
            var writeResult = _consul.Agent.CheckRegister(checkRegistration).GetAwaiter().GetResult();
            var isSuccess   = writeResult.StatusCode == HttpStatusCode.OK;

            //string success = isSuccess ? "succeeded" : "failed";

            return(checkId);
        }
Ejemplo n.º 19
0
        public IConsulServiceRegistrationBuilder WithHealthCheck(AgentCheckRegistration healthCheck)
        {
            healthCheck.ID = this.GetCheckID(healthCheck);
            this._healthChecks.Add(healthCheck);

            this._logger.LogDebug($"Added {this.GetHealthCheckType(healthCheck)} health check.");
            return(this);
        }
Ejemplo n.º 20
0
        private string GetCheckID(AgentCheckRegistration healthCheck)
        {
            if (!string.IsNullOrEmpty(healthCheck.ID))
            {
                return(healthCheck.ID);
            }

            return($"service:{this.ID}:{this._healthChecks.Count + 1}");
        }
        public void WithHealthCheckTest()
        {
            var registrationBuilder = new ConsulServiceRegistrationBuilder(this._loggerFactory);

            var serviceName = "test";
            var id          = $"{serviceName}_{Environment.MachineName}";

            var httpCheck = new AgentCheckRegistration
            {
                ID   = "http_check",
                Name = "HTTP Check",
                HTTP = "http://127.0.0.1",
                DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(2)
            };

            var ttlCheck = new AgentCheckRegistration
            {
                Name = "TTL Check",
                DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(2),
                TTL = TimeSpan.FromSeconds(30)
            };

            registrationBuilder.WithServiceName(serviceName);
            registrationBuilder.WithHealthCheck(httpCheck);
            registrationBuilder.WithHealthCheck(ttlCheck);

            var registration = registrationBuilder.Build();

            registration.ShouldNotBeNull();

            var consulRegistration = registration as ConsulServiceRegistration;

            consulRegistration.ShouldNotBeNull();
            consulRegistration.Registration.Checks.Length.ShouldBe(2);

            consulRegistration.Registration.Checks[0].ShouldNotBeNull();
            var httpRegistrationCheck = consulRegistration.Registration.Checks[0] as AgentCheckRegistration;

            httpRegistrationCheck.ShouldNotBeNull();
            httpRegistrationCheck.ID.ShouldBe(httpCheck.ID);
            httpRegistrationCheck.Name.ShouldBe(httpCheck.Name);
            httpRegistrationCheck.HTTP.ShouldBe(httpCheck.HTTP);

            consulRegistration.Registration.Checks[1].ShouldNotBeNull();
            var ttlRegistrationCheck = consulRegistration.Registration.Checks[1] as AgentCheckRegistration;

            ttlRegistrationCheck.ShouldNotBeNull();
            ttlRegistrationCheck.ID.ShouldBe($"service:{id}:2");
            ttlRegistrationCheck.Name.ShouldBe(ttlCheck.Name);
            ttlRegistrationCheck.TTL.ShouldBe(ttlCheck.TTL);
        }
Ejemplo n.º 22
0
        public AgentCheckRegistration GetCheck(AgentServiceRegistration registration)
        {
            var check = new AgentCheckRegistration
            {
                Name     = "tcpcheck",
                TCP      = $"{registration.Address}:{registration.Port}",
                Interval = TimeSpan.FromSeconds(15),
                Timeout  = TimeSpan.FromSeconds(3),
                Status   = HealthStatus.Passing,
                DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1)
            };

            return(check);
        }
Ejemplo n.º 23
0
 /// <summary>
 /// 注册服务
 /// </summary>
 /// <param name="GrpcServerRegister">服务注册</param>
 /// <returns></returns>
 public override Entry RegisterService(GrpcServerRegister grpcServerRegister)
 {
     try
     {
         if (string.IsNullOrEmpty(grpcServerRegister.Host))
         {
             grpcServerRegister.Host = IPUtils.GetAddressIP();
         }
         var serviceId = $"{grpcServerRegister.ServiceName}_{grpcServerRegister.Host}:{grpcServerRegister.Port}";
         var acr       = new AgentCheckRegistration
         {
             TCP      = $"{grpcServerRegister.Host}:{grpcServerRegister.Port}",
             Name     = serviceId,
             ID       = serviceId,
             Interval = GlobalConfig.CheckInterval,
             DeregisterCriticalServiceAfter = GlobalConfig.CriticalInterval
         };
         if (grpcServerRegister.Meta == null)
         {
             grpcServerRegister.Meta = new Dictionary <string, string>();
         }
         if (!grpcServerRegister.Meta.ContainsKey("weights"))
         {
             grpcServerRegister.Meta.Add("weights", "1");
         } //权重值,如果等于0,客户端会自动移除
         var asr = new AgentServiceRegistration
         {
             Address           = grpcServerRegister.Host,
             ID                = serviceId,
             Name              = grpcServerRegister.ServiceName,
             Port              = grpcServerRegister.Port,
             Check             = acr,
             Tags              = grpcServerRegister.Tags,
             Meta              = grpcServerRegister.Meta,
             EnableTagOverride = grpcServerRegister.EnableTagOverride
         };
         var res = _clientManager.GetClient.Agent.ServiceRegister(asr).Result;
         if (res.StatusCode != HttpStatusCode.OK)
         {
             throw new GrpcConsulException($"Failed to register service by {serviceId}");
         }
         return(new Entry(this, serviceId, grpcServerRegister.ServiceName, grpcServerRegister.Host, grpcServerRegister.Port));
     }
     catch (Exception ex)
     {
         CommonUtilsHelper._.LoggerWriter(ex.Message, ex);
     }
     return(null);
 }
Ejemplo n.º 24
0
        public static IConsulServiceRegistrationBuilder AddTTLCheck(this IConsulServiceRegistrationBuilder registrationBuilder, TimeSpan ttl, TimeSpan interval, TimeSpan deregisterFailedAfter)
        {
            var ttlCheck = new AgentCheckRegistration
            {
                DockerContainerID = Environment.MachineName,
                DeregisterCriticalServiceAfter = deregisterFailedAfter,
                TTL  = ttl,
                Name = "TTL check"
            };

            registrationBuilder.WithTTLUpdatingPeriod(interval);
            registrationBuilder.WithHealthCheck(ttlCheck);

            return(registrationBuilder);
        }
Ejemplo n.º 25
0
        public static IConsulRegistration AddTTLCheck(this IConsulRegistration registration, TimeSpan ttl, TimeSpan interval, TimeSpan deregisterFailedAfter)
        {
            var ttlCheck = new AgentCheckRegistration
            {
                DockerContainerID = Environment.MachineName,
                DeregisterCriticalServiceAfter = deregisterFailedAfter,
                Interval = interval,
                TTL      = ttl,
                Name     = $"TTL check"
            };

            registration.AddHealthCheck(ttlCheck);

            return(registration);
        }
Ejemplo n.º 26
0
        internal static AgentCheckRegistration BuildHttpHealthCheck(string address, int port, string path, int interval, int deregisterIfCriticalAfterMinutes)
        {
            var healthCheck = new AgentCheckRegistration()
            {
                HTTP     = $"{address}:{port}/{path}",
                Interval = TimeSpan.FromSeconds(interval),
                DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(deregisterIfCriticalAfterMinutes)
            };

            if (!healthCheck.HTTP.StartsWith("HTTP", StringComparison.OrdinalIgnoreCase))
            {
                healthCheck.HTTP = "http://" + healthCheck.HTTP;
            }
            return(healthCheck);
        }
Ejemplo n.º 27
0
        public static IConsulServiceRegistrationBuilder AddHttpCheck(this IConsulServiceRegistrationBuilder registrationBuilder, int port, string relativePath, TimeSpan interval, TimeSpan deregisterFailedAfter)
        {
            var url       = $"{registrationBuilder.Address}:{port}{relativePath}";
            var httpCheck = new AgentCheckRegistration
            {
                DockerContainerID = Environment.MachineName,
                DeregisterCriticalServiceAfter = deregisterFailedAfter,
                Interval = interval,
                HTTP     = url,
                Name     = $"HTTP GET {url} check"
            };

            registrationBuilder.WithHealthCheck(httpCheck);

            return(registrationBuilder);
        }
Ejemplo n.º 28
0
        public void Agent_Checks()
        {
            var c = ClientTest.MakeClient();
            var reg = new AgentCheckRegistration
            {
                Name = "foo",
                TTL = TimeSpan.FromSeconds(15)
            };
            c.Agent.CheckRegister(reg);

            var checks = c.Agent.Checks();
            Assert.IsTrue(checks.Response.ContainsKey("foo"));
            Assert.AreEqual(checks.Response["foo"].Status, CheckStatus.Critical);

            c.Agent.CheckDeregister("foo");
        }
Ejemplo n.º 29
0
        public async Task Agent_Checks()
        {
            var svcID        = KVTest.GenerateTestKeyName();
            var registration = new AgentCheckRegistration
            {
                Name = svcID,
                TTL  = TimeSpan.FromSeconds(15)
            };
            await _client.Agent.CheckRegister(registration);

            var checks = await _client.Agent.Checks();

            Assert.True(checks.Response.ContainsKey(svcID));
            Assert.Equal(HealthStatus.Critical, checks.Response[svcID].Status);

            await _client.Agent.CheckDeregister(svcID);
        }
Ejemplo n.º 30
0
        public async Task Agent_Checks()
        {
            var client       = new ConsulClient();
            var registration = new AgentCheckRegistration
            {
                Name = "foo",
                TTL  = TimeSpan.FromSeconds(15)
            };
            await client.Agent.CheckRegister(registration);

            var checks = await client.Agent.Checks();

            Assert.True(checks.Response.ContainsKey("foo"));
            Assert.Equal(CheckStatus.Critical, checks.Response["foo"].Status);

            await client.Agent.CheckDeregister("foo");
        }
Ejemplo n.º 31
0
        public void Agent_Checks()
        {
            var client       = new Client();
            var registration = new AgentCheckRegistration
            {
                Name = "foo",
                TTL  = TimeSpan.FromSeconds(15)
            };

            client.Agent.CheckRegister(registration);

            var checks = client.Agent.Checks();

            Assert.IsTrue(checks.Response.ContainsKey("foo"));
            Assert.AreEqual(CheckStatus.Critical, checks.Response["foo"].Status);

            client.Agent.CheckDeregister("foo");
        }
Ejemplo n.º 32
0
 internal bool RegisterServiceReadyCheck(string name)
 {
     MyLogger.Trace("Entering " + MethodBase.GetCurrentMethod().Name);
     AgentCheckRegistration cr = new AgentCheckRegistration
     {
         ID = name + "_Ready",
         Name = "Ready Status",
         TTL = TimeSpan.FromSeconds(5),
         Notes = "Is service " + name + " ready to run",
         ServiceID = name
     };
     try
     {
         ConsulClient.Agent.CheckRegister(cr);
         return true;
     }
     catch (Exception ex)
     {
         MyLogger.Error("Heartbeat Check registration failed: {0}", ex.Message);
         MyLogger.Debug(ex);
         return false;
     }
 }
Ejemplo n.º 33
0
 internal bool RegisterServiceRunningCheck(string name, int ttl)
 {
     MyLogger.Trace("Entering " + MethodBase.GetCurrentMethod().Name);
     AgentCheckRegistration cr = new AgentCheckRegistration
     {
         ID = name + "_Running",
         //Name = name + "_Running",
         Name = "Run Status",
         TTL = TimeSpan.FromMilliseconds(ttl),
         Notes = "Status of service " + name,
         ServiceID = name
     };
     try
     {
         ConsulClient.Agent.CheckRegister(cr);
         return true;
     }
     catch (Exception ex)
     {
         MyLogger.Error("Heartbeat Check registration failed: {0}", ex.Message);
         MyLogger.Debug(ex);
         return false;
     }
 }
Ejemplo n.º 34
0
 internal bool RegisterInternalMonitorCheck()
 {
     AgentCheckRegistration cr = new AgentCheckRegistration
     {
         Name = Name + "_Internalcheck",
         TTL = TimeSpan.FromSeconds(5),
         Notes = "Status from within service thread",
         ServiceID = Name
     };
     return _parent.ConsulClient.Agent.CheckRegister(cr).Wait(5000);
 }
Ejemplo n.º 35
0
        public async Task Agent_Checks_ServiceBound()
        {
            var client = new ConsulClient();

            var serviceReg = new AgentServiceRegistration()
            {
                Name = "redis"
            };
            await client.Agent.ServiceRegister(serviceReg);

            var reg = new AgentCheckRegistration()
            {
                Name = "redischeck",
                ServiceID = "redis",
                TTL = TimeSpan.FromSeconds(15)
            };
            await client.Agent.CheckRegister(reg);

            var checks = await client.Agent.Checks();
            Assert.True(checks.Response.ContainsKey("redischeck"));
            Assert.Equal("redis", checks.Response["redischeck"].ServiceID);

            await client.Agent.CheckDeregister("redischeck");
            await client.Agent.ServiceDeregister("redis");
        }
Ejemplo n.º 36
0
        public async Task Agent_CheckStartPassing()
        {
            var client = new ConsulClient();
            var registration = new AgentCheckRegistration
            {
                Name = "foo",
                Status = CheckStatus.Passing,
                TTL = TimeSpan.FromSeconds(15)
            };
            await client.Agent.CheckRegister(registration);

            var checks = await client.Agent.Checks();
            Assert.True(checks.Response.ContainsKey("foo"));
            Assert.Equal(CheckStatus.Passing, checks.Response["foo"].Status);

            await client.Agent.CheckDeregister("foo");
        }
Ejemplo n.º 37
0
 internal bool RegisterThreadMonitorCheck()
 {
     AgentCheckRegistration cr = new AgentCheckRegistration
     {
         Name = Name + "_Threadcheck",
         TTL = TimeSpan.FromSeconds(5),
         Notes = "Checks if service thread is alive",
         ServiceID = Name
     };
     return _parent.ConsulClient.Agent.CheckRegister(cr).Wait(5000);
 }
Ejemplo n.º 38
0
        public async Task Agent_Checks_Docker()
        {
            using (var client = new ConsulClient())
            {
                var serviceReg = new AgentServiceRegistration()
                {
                    Name = "redis"
                };
                await client.Agent.ServiceRegister(serviceReg);

                var reg = new AgentCheckRegistration()
                {
                    Name = "redischeck",
                    ServiceID = "redis",
                    DockerContainerID = "f972c95ebf0e",
                    Script = "/bin/true",
                    Shell = "/bin/bash",
                    Interval = TimeSpan.FromSeconds(10)
                };
                await client.Agent.CheckRegister(reg);

                var checks = await client.Agent.Checks();
                Assert.True(checks.Response.ContainsKey("redischeck"));
                Assert.Equal("redis", checks.Response["redischeck"].ServiceID);

                await client.Agent.CheckDeregister("redischeck");
                await client.Agent.ServiceDeregister("redis");
            }
        }
Ejemplo n.º 39
0
        public void Agent_Checks_ServiceBound()
        {
            var c = ClientTest.MakeClient();

            var serviceReg = new AgentServiceRegistration()
            {
                Name = "redis"
            };
            c.Agent.ServiceRegister(serviceReg);

            var reg = new AgentCheckRegistration()
            {
                Name = "redischeck",
                ServiceID = "redis",
                TTL = TimeSpan.FromSeconds(15)
            };
            c.Agent.CheckRegister(reg);

            var checks = c.Agent.Checks();
            Assert.IsTrue(checks.Response.ContainsKey("redischeck"));
            Assert.AreEqual(checks.Response["redischeck"].ServiceID, "redis");

            c.Agent.CheckDeregister("redischeck");
            c.Agent.ServiceDeregister("redis");
        }