From 571a564f5111c13c812bbfce397c5793131c8da4 Mon Sep 17 00:00:00 2001 From: Richard Belleville Date: Tue, 24 Mar 2020 14:23:25 -0700 Subject: [PATCH] Add type annotations and comments --- examples/python/xds/README.md | 2 +- examples/python/xds/server.py | 24 ++++++++++++++++++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/examples/python/xds/README.md b/examples/python/xds/README.md index 5dacfc4371e..51bfe715583 100644 --- a/examples/python/xds/README.md +++ b/examples/python/xds/README.md @@ -22,7 +22,7 @@ cd grpc/examples/python/xds ```sh virtualenv venv -p python3 source venv/bin/activate -pip install grpcio protobuf +pip install grpcio protobuf grpcio-reflection grpcio-health-checking python server.py ``` diff --git a/examples/python/xds/server.py b/examples/python/xds/server.py index 2b459eb39f3..3cff567667f 100644 --- a/examples/python/xds/server.py +++ b/examples/python/xds/server.py @@ -16,6 +16,7 @@ from concurrent import futures import argparse import logging +import multiprocessing import socket import grpc @@ -33,31 +34,46 @@ _DESCRIPTION = "A general purpose dummy server." class Greeter(helloworld_pb2_grpc.GreeterServicer): - def __init__(self, hostname): + def __init__(self, hostname: str): self._hostname = hostname if hostname else socket.gethostname() - def SayHello(self, request, context): + def SayHello(self, request: helloworld_pb2.HelloRequest, + context: grpc.ServicerContext) -> helloworld_pb2.HelloReply: return helloworld_pb2.HelloReply( message=f"Hello {request.name} from {self._hostname}!") def serve(port, hostname): - server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) + server = grpc.server( + futures.ThreadPoolExecutor(max_workers=multiprocessing.cpu_count())) + + # Add the application servicer to the server. helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(hostname), server) + + # Create a health check servicer. We use the non-blocking implementation + # to avoid thread starvation. health_servicer = health.HealthServicer( experimental_non_blocking=True, - experimental_thread_pool=futures.ThreadPoolExecutor(max_workers=4)) + experimental_thread_pool=futures.ThreadPoolExecutor(max_workers=1)) health_pb2_grpc.add_HealthServicer_to_server(health_servicer, server) + + # Create a tuple of all of the services we want to export via reflection. services = tuple( service.full_name for service in helloworld_pb2.DESCRIPTOR.services_by_name.values()) + ( reflection.SERVICE_NAME, health.SERVICE_NAME) + + # Add the reflection service to the server. reflection.enable_server_reflection(services, server) server.add_insecure_port(f"[::]:{port}") server.start() + + # Mark all services as healthy. overall_server_health = "" for service in services + (overall_server_health,): health_servicer.set(service, health_pb2.HealthCheckResponse.SERVING) + + # Park the main application thread. server.wait_for_termination()