From b6a5e94f71917046ae3b0c29825ec986e11876ca Mon Sep 17 00:00:00 2001 From: Richard Belleville Date: Tue, 25 Jun 2019 09:36:49 -0700 Subject: [PATCH] Respond to ctrl+c on client side --- examples/python/cancellation/client.py | 27 ++++++++++++++------------ examples/python/cancellation/server.py | 2 ++ 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/examples/python/cancellation/client.py b/examples/python/cancellation/client.py index 63891d05842..f86a32af175 100644 --- a/examples/python/cancellation/client.py +++ b/examples/python/cancellation/client.py @@ -22,6 +22,7 @@ import argparse import datetime import logging import time +import signal import grpc @@ -31,25 +32,27 @@ from examples.python.cancellation import hash_name_pb2_grpc _DESCRIPTION = "A client for finding hashes similar to names." _LOGGER = logging.getLogger(__name__) -# Interface: -# Cancel on ctrl+c or an ideal candidate. +_TIMEOUT_SECONDS = 0.05 def run_unary_client(server_target, name, ideal_distance): - # TODO(rbellevi): Cancel on ctrl+c with grpc.insecure_channel(server_target) as channel: stub = hash_name_pb2_grpc.HashFinderStub(channel) + print("Sending request") + future = stub.Find.future(hash_name_pb2.HashNameRequest(desired_name=name, + ideal_hamming_distance=ideal_distance)) + def cancel_request(unused_signum, unused_frame): + print("Cancelling request.") + future.cancel() + signal.signal(signal.SIGINT, cancel_request) while True: - print("Sending request") - future = stub.Find.future(hash_name_pb2.HashNameRequest(desired_name=name, - ideal_hamming_distance=ideal_distance)) - # TODO(rbellevi): Do not leave in a cancellation based on timeout. - # That's best handled by, well.. timeout. try: - result = future.result(timeout=20.0) - print("Got response: \n{}".format(result)) + result = future.result(timeout=_TIMEOUT_SECONDS) except grpc.FutureTimeoutError: - print("Cancelling request") - future.cancel() + continue + except grpc.FutureCancelledError: + break + print("Got response: \n{}".format(result)) + break def run_streaming_client(target, name, ideal_distance, interesting_distance): diff --git a/examples/python/cancellation/server.py b/examples/python/cancellation/server.py index 334a3770247..575c2fc8e74 100644 --- a/examples/python/cancellation/server.py +++ b/examples/python/cancellation/server.py @@ -137,9 +137,11 @@ class HashFinder(hash_name_pb2_grpc.HashFinderServicer): def Find(self, request, context): stop_event = threading.Event() def on_rpc_done(): + print("Attempting to regain servicer thread.") stop_event.set() context.add_callback(on_rpc_done) candidates = list(_find_secret(request.desired_name, request.ideal_hamming_distance, stop_event)) + print("Servicer thread returning.") if not candidates: return hash_name_pb2.HashNameResponse() return candidates[-1]