• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2020 The gRPC authors.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""The Python implementation of the GRPC helloworld.Greeter server."""
15
16from concurrent import futures
17import argparse
18import logging
19import multiprocessing
20import socket
21
22import grpc
23
24import helloworld_pb2
25import helloworld_pb2_grpc
26
27from grpc_reflection.v1alpha import reflection
28from grpc_health.v1 import health
29from grpc_health.v1 import health_pb2
30from grpc_health.v1 import health_pb2_grpc
31
32_DESCRIPTION = "A general purpose dummy server."
33
34
35class Greeter(helloworld_pb2_grpc.GreeterServicer):
36
37    def __init__(self, hostname: str):
38        self._hostname = hostname if hostname else socket.gethostname()
39
40    def SayHello(self, request: helloworld_pb2.HelloRequest,
41                 context: grpc.ServicerContext) -> helloworld_pb2.HelloReply:
42        return helloworld_pb2.HelloReply(
43            message=f"Hello {request.name} from {self._hostname}!")
44
45
46def serve(port: int, hostname: str):
47    server = grpc.server(
48        futures.ThreadPoolExecutor(max_workers=multiprocessing.cpu_count()))
49
50    # Add the application servicer to the server.
51    helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(hostname), server)
52
53    # Create a health check servicer. We use the non-blocking implementation
54    # to avoid thread starvation.
55    health_servicer = health.HealthServicer(
56        experimental_non_blocking=True,
57        experimental_thread_pool=futures.ThreadPoolExecutor(max_workers=1))
58    health_pb2_grpc.add_HealthServicer_to_server(health_servicer, server)
59
60    # Create a tuple of all of the services we want to export via reflection.
61    services = tuple(
62        service.full_name
63        for service in helloworld_pb2.DESCRIPTOR.services_by_name.values()) + (
64            reflection.SERVICE_NAME, health.SERVICE_NAME)
65
66    # Add the reflection service to the server.
67    reflection.enable_server_reflection(services, server)
68    server.add_insecure_port(f"[::]:{port}")
69    server.start()
70
71    # Mark all services as healthy.
72    overall_server_health = ""
73    for service in services + (overall_server_health,):
74        health_servicer.set(service, health_pb2.HealthCheckResponse.SERVING)
75
76    # Park the main application thread.
77    server.wait_for_termination()
78
79
80if __name__ == '__main__':
81    parser = argparse.ArgumentParser(description=_DESCRIPTION)
82    parser.add_argument("port",
83                        default=50051,
84                        type=int,
85                        nargs="?",
86                        help="The port on which to listen.")
87    parser.add_argument("hostname",
88                        type=str,
89                        default=None,
90                        nargs="?",
91                        help="The name clients will see in responses.")
92    args = parser.parse_args()
93    logging.basicConfig()
94    serve(args.port, args.hostname)
95