3
votes


I have a gRPC HelloWorld server running like shown in official getting started guide(https://grpc.io/docs/quickstart/python/). I now want to shutdown/terminate the server from the client, possibly by calling a server method.
I know this can be done because I read this post on how to do this in c++. How to shutdown gRPC server from Client (using RPC function)

My programming language is python for both client and server. Any help will be much appreciated.

1

1 Answers

6
votes

Just like in C++, calling Server.stop() from a handler would be problematic. Instead, you should coordinate between your servicer thread and handler thread using, e.g., a threading.Event.

In your main thread, do something like

stop_event = threading.Event()
server = grpc.server(futures.ThreadPoolExecutor())
foo_pb2_grpc.add_FooServicer_to_server(Foo(stop_event), server)
server.add_insecure_port(...)
server.start()
stop_event.wait()
server.stop()

And then in your servicer, set the event when a shutdown is requested:

class Foo(foo_pb2_grpc.FooServicer):
    def __init__(self, stop_event):
        self._stop_event = stop_event

    def Stop(self, request, context):
        self._stop_event.set()
        return foo_pb2.ShutdownResponse()