From 9f6243e824247648534e05414e7253245ca135f2 Mon Sep 17 00:00:00 2001 From: Lidi Zheng Date: Fri, 7 Jun 2019 17:37:55 -0700 Subject: [PATCH] Add wait_for_termination method to grpc.Server --- src/python/grpcio/grpc/__init__.py | 14 ++++++++++++++ src/python/grpcio/grpc/_server.py | 11 +++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/python/grpcio/grpc/__init__.py b/src/python/grpcio/grpc/__init__.py index a1df5fb161c..814bfbac1bd 100644 --- a/src/python/grpcio/grpc/__init__.py +++ b/src/python/grpcio/grpc/__init__.py @@ -1444,6 +1444,20 @@ class Server(six.with_metaclass(abc.ABCMeta)): """ raise NotImplementedError() + def wait_for_termination(self, grace=None): + """Block current thread until the server stops. + + The wait will not consume computational resources during blocking, and it + will block indefinitely. There are two ways to unblock: + + 1) Calling `stop` on the server in another thread; + 2) The `__del__` of the server object is invoked. + + Args: + grace: A duration of time in seconds or None. + """ + raise NotImplementedError() + ################################# Functions ################################ diff --git a/src/python/grpcio/grpc/_server.py b/src/python/grpcio/grpc/_server.py index 370c81100af..70acbcd5068 100644 --- a/src/python/grpcio/grpc/_server.py +++ b/src/python/grpcio/grpc/_server.py @@ -959,6 +959,17 @@ class _Server(grpc.Server): def start(self): _start(self._state) + def wait_for_termination(self, grace=None): + termination_event = threading.Event() + + with self._state.lock: + if self._state.stage is _ServerStage.STOPPED: + raise ValueError('Failed to wait for a stopped server.') + else: + self._state.shutdown_events.append(termination_event) + + termination_event.wait() + def stop(self, grace): return _stop(self._state, grace)