Ejemplo n.º 1
0
        /// <summary>
        /// Determines whether the specified endpoint is connected to the specified service
        /// that responds with health status 'Serving' .
        /// </summary>
        /// <param name="healthClient"></param>
        /// <param name="serviceName"></param>
        /// <param name="statusCode">Status code from the RPC call</param>
        /// <returns></returns>
        public static bool IsServing([NotNull] Health.HealthClient healthClient,
                                     [NotNull] string serviceName,
                                     out StatusCode statusCode)
        {
            statusCode = StatusCode.Unknown;

            try
            {
                HealthCheckResponse healthResponse =
                    healthClient.Check(new HealthCheckRequest()
                {
                    Service = serviceName
                });

                statusCode = StatusCode.OK;

                return(healthResponse.Status == HealthCheckResponse.Types.ServingStatus.Serving);
            }
            catch (RpcException rpcException)
            {
                _msg.Debug($"Error checking health of service {serviceName}", rpcException);

                statusCode = rpcException.StatusCode;
            }
            catch (Exception e)
            {
                _msg.Debug($"Error checking health of service {serviceName}", e);
                return(false);
            }

            return(false);
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            var httpHandler = new HttpClientHandler();

// Return `true` to allow certificates that are untrusted/invalid
            httpHandler.ServerCertificateCustomValidationCallback =
                HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
            var channel = GrpcChannel.ForAddress("https://localhost:50051",
                                                 new GrpcChannelOptions {
                HttpHandler = httpHandler
            });

            // var client = new Greet.GreeterClient(channel);
            //
            //
            // var channelTarget = $"{DefaultHost}:{Port}";
            //
            // var channel = new Channel(channelTarget, ChannelCredentials.Insecure);

            Health.HealthClient cc = new Health.HealthClient(channel);
            var c = cc.Check(new HealthCheckRequest());

            Console.WriteLine(c.Status);

            // Create a channel
            // Hello.HelloClient client = new Hello.HelloClient(channel);
            //
            // for (int i = 0; i < 10; i++)
            // {
            //     var reply = client.SayHello(new HelloRequest{Name = "Vincent"});
            //
            //     Console.WriteLine(reply.Message);
            // }
        }
Ejemplo n.º 3
0
        private async static Task HealthCheck(GrpcChannel channel)
        {
            var client = new Health.HealthClient(channel);

            Console.WriteLine("Watching health status");
            Console.WriteLine("Press any key to exit...");

            var cts = new CancellationTokenSource();

            using var call = client.Watch(new HealthCheckRequest { Service = "HealthCheck" }, cancellationToken: cts.Token);
            var watchTask = Task.Run(async() =>
            {
                try
                {
                    await foreach (var message in call.ResponseStream.ReadAllAsync())
                    {
                        Console.WriteLine($"{DateTime.Now}: Service is {message.Status}");
                    }
                }
                catch (RpcException ex) when(ex.StatusCode == StatusCode.Cancelled)
                {
                    Console.WriteLine(ex.Status.Detail);
                }
            });

            Console.ReadKey();
            Console.WriteLine("Finished");

            cts.Cancel();
            await watchTask;
        }
Ejemplo n.º 4
0
        static async Task Main(string[] args)
        {
            AppContext.SetSwitch(
                "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            Channel channel = new Channel("healthchecker:5000",
                                          ChannelCredentials.Insecure);

            Health.HealthClient client = new Health.HealthClient(channel);

            while (true)
            {
                try
                {
                    var watch = System.Diagnostics.Stopwatch.StartNew();

                    HealthCheckResponse response = await client.CheckAsync(new HealthCheckRequest()
                    {
                        Service = "healthchecker"
                    });

                    watch.Stop();
                    Console.WriteLine("gRPC call to Healthchecker Server took " + watch.ElapsedMilliseconds + "ms");

                    response.Status.ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + " " + ex.StackTrace);
                }

                System.Threading.Thread.Sleep(1000);
            }
        }
        static async Task Main(string[] args)
        {
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client = new Health.HealthClient(channel);

            Console.WriteLine("Watching health status");
            Console.WriteLine("Press any key to exit...");

            var cts = new CancellationTokenSource();

            using var call = client.Watch(new HealthCheckRequest { Service = "" }, cancellationToken: cts.Token);
            var watchTask = Task.Run(async() =>
            {
                try
                {
                    await foreach (var message in call.ResponseStream.ReadAllAsync())
                    {
                        Console.WriteLine($"{DateTime.Now}: Service is {message.Status}");
                    }
                }
                catch (RpcException ex) when(ex.StatusCode == StatusCode.Cancelled)
                {
                    // Handle cancellation exception.
                }
            });

            Console.ReadKey();
            Console.WriteLine("Finished");

            cts.Cancel();
            await watchTask;
        }
Ejemplo n.º 6
0
        private static void Main(string[] args)
        {
            var channel             = new Channel(ServerAddress, ChannelCredentials.Insecure);
            var healthCheckClient   = new Health.HealthClient(channel);
            var healthCheckResponse = healthCheckClient.Check(new HealthCheckRequest {
                Service = ServiceName
            });

            Console.WriteLine($"Service: '{ServiceName}' has a health status: {healthCheckResponse.Status.ToString()}");
            try
            {
                healthCheckClient.Check(new HealthCheckRequest {
                    Service = "Bad Name"
                });
            }
            catch (RpcException ex)
            {
                Console.WriteLine($"Service: 'Bad Name' has a health status: {ex.Status.StatusCode.ToString()}");
            }

            var bookClient = new BookService.BookServiceClient(channel);
            var book       = bookClient.GetBookById(new GetBookByIdRequest {
                Id = 1
            });

            Console.WriteLine($"Retrieved book: {book.Name}");

            channel.ShutdownAsync().GetAwaiter().GetResult();

            Console.WriteLine("Press key to shut down ... .. .");
            Console.ReadKey();
        }
Ejemplo n.º 7
0
        protected void OpenChannel(bool useTls,
                                   string clientCertificate = null,
                                   bool assumeLoadBalancer  = false)
        {
            if (string.IsNullOrEmpty(HostName))
            {
                _msg.Debug("Host name is null or empty. No channel opened.");
                return;
            }

            ChannelCredentials credentials =
                GrpcUtils.CreateChannelCredentials(useTls, clientCertificate);

            var enoughForLargeGeometries = (int)Math.Pow(1024, 3);

            Channel channel = GrpcUtils.CreateChannel(
                HostName, Port, credentials, enoughForLargeGeometries);

            if (assumeLoadBalancer)
            {
                ChannelIsLoadBalancer =
                    IsServingLoadBalancerEndpoint(channel, credentials, ServiceName,
                                                  enoughForLargeGeometries);
            }

            Channel = channel;

            _msg.DebugFormat("Created grpc channel to {0} on port {1}", HostName, Port);

            _healthClient = new Health.HealthClient(Channel);

            ChannelOpenedCore(Channel);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Determines whether the specified endpoint is connected to the specified service
        /// that responds with health status 'Serving' .
        /// </summary>
        /// <param name="healthClient"></param>
        /// <param name="serviceName"></param>
        /// <returns>StatusCode.OK if the service is healthy.</returns>
        public static async Task <StatusCode> IsServingAsync(
            [NotNull] Health.HealthClient healthClient,
            [NotNull] string serviceName)
        {
            StatusCode statusCode = StatusCode.Unknown;

            try
            {
                HealthCheckResponse healthResponse =
                    await healthClient.CheckAsync(new HealthCheckRequest()
                {
                    Service = serviceName
                });

                statusCode =
                    healthResponse.Status == HealthCheckResponse.Types.ServingStatus.Serving
                                                ? StatusCode.OK
                                                : StatusCode.ResourceExhausted;
            }
            catch (RpcException rpcException)
            {
                _msg.Debug($"Error checking health of service {serviceName}", rpcException);

                statusCode = rpcException.StatusCode;
            }
            catch (Exception e)
            {
                _msg.Debug($"Error checking health of service {serviceName}", e);
                return(statusCode);
            }

            return(statusCode);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Press any key to start the check.");
            Console.ReadKey(true);


            var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client  = new Health.HealthClient(channel);
            var req     = new HealthCheckRequest
            {
                Service = "Liveness"
            };

            try
            {
                var res = client.Check(req);
                Console.WriteLine(res.Status);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey(true);
        }
Ejemplo n.º 10
0
        public void HealthCheck()
        {
            var client   = new Health.HealthClient(_channel);
            var response = client.Check(new HealthCheckRequest
            {
                Service = ""
            });

            Console.WriteLine(response.Status);
        }
Ejemplo n.º 11
0
        private void DoCheck(object state)
        {
            using var channel = GrpcChannel.ForAddress("https://localhost:8001");;
            var client = new Health.HealthClient(channel);

            client.Check(new HealthCheckRequest()
            {
                Service = "https://localhost:8001"
            });
        }
Ejemplo n.º 12
0
        public async Task <IActionResult> HealthOrdering([FromServices] Health.HealthClient healthClient, [FromServices] IOrderingServiceClient orderingServiceClient)
        {
            await Mediator.Send(new FindProductsQuery());

            var a = await orderingServiceClient.SayHello(new HelloRequest());

            //var result = await healthClient.CheckAsync(new HealthCheckRequest());

            return(Ok(new { a }));
        }
Ejemplo n.º 13
0
        private void OpenChannel()
        {
            if (string.IsNullOrEmpty(HostName))
            {
                throw new ArgumentNullException(nameof(HostName));
            }

            Channel = GrpcUtils.CreateChannel(HostName, Port, _credentials);

            _logger.LogDebug("Created grpc channel to {HostName} on port {Port}", HostName, Port);

            _healthClient = new Health.HealthClient(Channel);
        }
Ejemplo n.º 14
0
        private static async Task Main()
        {
            using var channel = GrpcChannel.ForAddress("https://localhost:5005");

            var healthClient = new Health.HealthClient(channel);

            var health = await healthClient.CheckAsync(new HealthCheckRequest { Service = "Weather" });

            Console.WriteLine($"Health Status: {health.Status}");

            Console.WriteLine("Press a key to exit");
            Console.ReadKey();
        }
Ejemplo n.º 15
0
        private static async Task Main(string[] args)
        {
            GrpcChannel channel           = GrpcChannel.ForAddress("https://localhost:45679");
            var         httpsClientTicker = new Ticker.TickerClient(channel);

            GrpcChannel authChannel = GrpcChannel.ForAddress("https://localhost:56790");
            var         httpsClient = new Auth.AuthClient(authChannel);

            var interceptorHttps = channel.Intercept(new HeaderLoggerInterceptor());
            var healthChecker    = new Health.HealthClient(interceptorHttps);

            string serviceName = "Ticker";

            var result = await healthChecker.CheckAsync(new HealthCheckRequest { Service = serviceName });

            Console.WriteLine(result?.Status);

            /*  var reply = await httpsClient.LogInAsync(new LogInRequest { Username = "******", Password = "******" });
             * var replyUser = await httpsClient.LogInAsync(new LogInRequest { Username = "******", Password = "******" });
             *
             * var tokenAdmin =
             *    await Authenticate(reply.Role);
             *
             * var tokenUser = await Authenticate(replyUser.Role);
             *
             *
             * Console.WriteLine(tokenAdmin);
             * Console.WriteLine(tokenUser);
             *
             * await ClientStreaming(httpsClientTicker, 1, tokenUser);
             *
             *
             *
             * /*await UpdateTickHandling(httpsClient,
             *    new TickToAdd
             *    {
             *        InstrumentId = 1,
             *        Close = (DecimalValue)5.6234m,
             *        Open = (DecimalValue)5.6225m,
             *        High = (DecimalValue)5.6238m,
             *        Low = (DecimalValue)5.6224m,
             *        Symbol = 2
             *    });
             * await GetTicksForQuota(httpsClient, 1);*/
            //await ClientStreaming(httpsClient, 1);


            Console.WriteLine("Press any key to close app...");
            Console.ReadLine();
        }
Ejemplo n.º 16
0
        private static async Task Main(string[] args)
        {
            Channel channel        = new Channel("localhost:5000", ChannelCredentials.Insecure);
            var     healthClient   = new Health.HealthClient(channel);
            var     healthResponse = await healthClient.CheckAsync(new HealthCheckRequest());

            Console.WriteLine($"Server is: {healthResponse.Status}");

            healthResponse = await healthClient.CheckAsync(new HealthCheckRequest { Service = CustomerService.Descriptor.Name });

            Console.WriteLine($"CustomerService is: {healthResponse.Status}");

            var customerClient   = new CustomerService.CustomerServiceClient(channel);
            var customerResponse = await customerClient.GetCustomerByIdAsync(
                new GetCustomerByIdRequest { Id = 1 },
                new CallOptions(new Metadata {
                { "correlation-id", Guid.NewGuid().ToString() }
            })).ResponseAsync.ConfigureAwait(false);

            Console.WriteLine($"Customer: {customerResponse.Customer.Id} retrieved.");

            customerResponse = await customerClient.GetCustomerById2Async(
                new GetCustomerByIdRequest { Id = 1 },
                new CallOptions(new Metadata {
                { "correlation-id", Guid.NewGuid().ToString() }
            })).ResponseAsync.ConfigureAwait(false);

            Console.WriteLine($"Customer: {customerResponse.Customer.Id} retrieved.");
            var customerResponse2 = customerClient.DeleteCustomerById(new DeleteCustomerByIdRequest {
                Id = 1
            });

            var customerResponse3 = customerClient.ListCustomers(new CustomerSearch {
                FirstName = "test"
            });

            while (await customerResponse3.ResponseStream.MoveNext(CancellationToken.None))
            {
                var response = customerResponse3.ResponseStream.Current;
            }

            await channel.ShutdownAsync().ConfigureAwait(false);

            Console.ReadKey();
        }
Ejemplo n.º 17
0
        private static bool IsServingLoadBalancerEndpoint(
            [NotNull] Channel channel,
            [NotNull] ChannelCredentials credentials,
            string serviceName,
            int enoughForLargeGeometries)
        {
            var channelHealth = new Health.HealthClient(channel);

            bool isServingEndpoint = GrpcUtils.IsServing(channelHealth, serviceName, out _);

            if (isServingEndpoint)
            {
                return(false);
            }

            bool isLoadBalancer = GrpcUtils.IsServing(channelHealth, nameof(ServiceDiscoveryGrpc),
                                                      out StatusCode lbStatusCode);

            if (isLoadBalancer)
            {
                _msg.DebugFormat("{0} is a load balancer address.", channel.ResolvedTarget);

                Channel suggestedLocation =
                    TryGetChannelFromLoadBalancer(channel, credentials, serviceName,
                                                  enoughForLargeGeometries);

                if (suggestedLocation != null)
                {
                    _msg.DebugFormat("Using serving load balancer at {0}", channel.ResolvedTarget);
                    return(true);
                }

                // Assumption: A load balancer is never also serving real requests -> lets not use it at all!
                _msg.Debug(
                    "The load balancer has no service locations available. It will not be used.");

                return(false);
            }

            _msg.DebugFormat("No {0} service and no serving load balancer at {1}. Error code: {2}",
                             serviceName, channel.ResolvedTarget, lbStatusCode);

            return(false);
        }
Ejemplo n.º 18
0
        private bool TryGetHealthClient(out Health.HealthClient healthClient)
        {
            healthClient = null;

            if (Port < 0)
            {
                // Avoid waiting for the timeout of the health check, if possible.
                return(false);
            }

            if (_healthClient == null)
            {
                return(false);
            }

            healthClient = _healthClient;

            return(true);
        }
        private async Task <bool> IsHealthy(ServiceLocation serviceLocation, Channel channel,
                                            TimeSpan workerResponseTimeout)
        {
            Health.HealthClient healthClient = new Health.HealthClient(channel);

            StatusCode healthStatus = await TaskUtils.TimeoutAfter(
                GrpcUtils.IsServingAsync(healthClient, serviceLocation.ServiceName),
                workerResponseTimeout);

            if (healthStatus != StatusCode.OK)
            {
                _logger.LogDebug(
                    "Service location {serviceLocation} is unhealthy and will not be used.",
                    serviceLocation);

                return(false);
            }

            return(true);
        }
Ejemplo n.º 20
0
        public async Task GrpcService_Exec_Test()
        {
            var locator = new GrpcLocator();

            Console.WriteLine("Testing in {0}", locator.ServiceDomain);

            GrpcService svc = await locator.Locate("alpha-users", ChannelCredentials.Insecure);

            Assert.IsNotNull(svc);

            HealthCheckResponse reply = await svc.Execute(async channel =>
            {
                var client = new Health.HealthClient(channel);
                return(await client.CheckAsync(new HealthCheckRequest {
                    Service = "users"
                }));
            }, TimeSpan.FromSeconds(2));


            Assert.AreEqual(HealthCheckResponse.Types.ServingStatus.Serving, reply.Status);
        }
Ejemplo n.º 21
0
        protected void OpenChannel(bool useTls, string clientCertificate = null)
        {
            if (string.IsNullOrEmpty(HostName))
            {
                _msg.Debug("Host name is null or empty. No channel opened.");
                return;
            }

            var enoughForLargeGeometries = (int)Math.Pow(1024, 3);

            ChannelCredentials credentials =
                GrpcUtils.CreateChannelCredentials(useTls, clientCertificate);

            Channel = GrpcUtils.CreateChannel(
                HostName, Port, credentials, enoughForLargeGeometries);

            _msg.DebugFormat("Created grpc channel to {0} on port {1}", HostName, Port);

            _healthClient = new Health.HealthClient(Channel);

            ChannelOpenedCore(Channel);
        }
Ejemplo n.º 22
0
        public async Task Run()
        {
            var host = config.GetValue("GRPC_HOST", "localhost");
            var port = config.GetValue("GRPC_PORT", "50051");

            this.Context.Logger.LogInformation($"connect to the server. {host}:{port}");
            Channel channel = new Channel($"{host}:{port}", ChannelCredentials.Insecure);

            this.Context.Logger.LogInformation($"* Begin Greet Check");
            var    greeter = new Greeter.GreeterClient(channel);
            String user    = "******";
            var    greet   = greeter.SayHello(new HelloRequest {
                Name = user
            });

            this.Context.Logger.LogInformation("Greeting: " + greet.Message);

            this.Context.Logger.LogInformation($"* Begin Version Check");
            var myversion = new MyVersionInfo.MyVersionInfoClient(channel);
            var v         = myversion.Get(new MyVersionInfoRequest
            {
                Message = "hoge",
            });

            this.Context.Logger.LogInformation(v.Version + $"({v.Guid})");

            this.Context.Logger.LogInformation($"* Begin Health Check");
            var health   = new Health.HealthClient(channel);
            var response = health.Check(new HealthCheckRequest
            {
                Service = "Check"
            });

            this.Context.Logger.LogInformation($"Health Checked: {response.Status}");
            channel.ShutdownAsync().Wait();
        }
Ejemplo n.º 23
0
        static async Task RunAsync(string endpoint, string prefix)
        {
            // The port number(5001) must match the port of the gRPC server.
            var handler = new SocketsHttpHandler();

            if (endpoint.StartsWith("https://"))
            {
                handler.SslOptions = new SslClientAuthenticationOptions
                {
                    RemoteCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true,
                };
            }
            using var channel = GrpcChannel.ForAddress(endpoint, new GrpcChannelOptions
            {
                HttpHandler = handler,
            });

            // health
            var healthClient = new Health.HealthClient(channel);
            var health       = await healthClient.CheckAsync(new HealthCheckRequest
            {
                Service = "",
            });

            Console.WriteLine($"Health Status: {health.Status}");

            // unary
            var client = new Greeter.GreeterClient(channel);
            var reply  = await client.SayHelloAsync(new HelloRequest { Name = $"{prefix} GreeterClient" });

            Console.WriteLine("Greeting: " + reply.Message);

            // duplex
            var requestHeaders = new Metadata
            {
                { "x-host-port", "10-0-0-10" },
            };

            using var streaming = client.StreamingBothWays(requestHeaders);
            var readTask = Task.Run(async() =>
            {
                await foreach (var response in streaming.ResponseStream.ReadAllAsync())
                {
                    Console.WriteLine(response.Message);
                }
            });

            var i = 0;

            while (i++ < 100)
            {
                await streaming.RequestStream.WriteAsync(new HelloRequest
                {
                    Name = $"{prefix} {i}",
                });

                await Task.Delay(TimeSpan.FromMilliseconds(10));
            }

            await streaming.RequestStream.CompleteAsync();

            await readTask;
        }
Ejemplo n.º 24
0
 static HealthCheckServiceClient()
 {
     _channel = new Channel("127.0.0.1:23333", ChannelCredentials.Insecure);
     _client  = new Health.HealthClient(_channel);
 }