How to shutdown gRPC server from gRPC client in python?
Asked Answered
M

1

6


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.

Minda answered 10/12, 2019 at 7:15 Comment(0)
W
7

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()
Worcestershire answered 10/12, 2019 at 20:41 Comment(2)
There seems to be a caveat in the server.wait_for_termination() source code: threading.Event().wait() does not work with CTRL+C across platforms. Will this affect the solution?Gujarat
1. This example doesn't use wait_for_termination() 2. Can you clarify what you mean by "doesn't work with CTRL+C". This question is about how to shut down a server based on an RPC, not based on CTRL+C. Are you wondering how to shut down a server based on either of these two events?Worcestershire

© 2022 - 2024 — McMap. All rights reserved.