14 """An example of cancelling requests in gRPC."""
16 from __future__
import absolute_import
17 from __future__
import division
18 from __future__
import print_function
21 from concurrent
import futures
28 from examples.python.cancellation
import hash_name_pb2
29 from examples.python.cancellation
import hash_name_pb2_grpc
31 _LOGGER = logging.getLogger(__name__)
32 _SERVER_HOST =
'localhost'
34 _DESCRIPTION =
"A server for finding hashes similar to names."
43 def Find(self, request, context):
44 stop_event = threading.Event()
47 _LOGGER.debug(
"Attempting to regain servicer thread.")
50 context.add_callback(on_rpc_done)
55 request.ideal_hamming_distance, stop_event,
58 _LOGGER.info(
"Cancelling RPC due to exhausted resources.")
60 _LOGGER.debug(
"Servicer thread returning.")
62 return hash_name_pb2.HashNameResponse()
66 stop_event = threading.Event()
69 _LOGGER.debug(
"Attempting to regain servicer thread.")
72 context.add_callback(on_rpc_done)
75 request.ideal_hamming_distance,
78 interesting_hamming_distance=request.interesting_hamming_distance)
80 for candidate
in secret_generator:
83 _LOGGER.info(
"Cancelling RPC due to exhausted resources.")
85 _LOGGER.debug(
"Regained servicer thread.")
92 server =
grpc.server(futures.ThreadPoolExecutor(max_workers=1),
93 maximum_concurrent_rpcs=1)
94 hash_name_pb2_grpc.add_HashFinderServicer_to_server(
96 address =
'{}:{}'.
format(_SERVER_HOST, port)
97 actual_port = server.add_insecure_port(address)
99 print(
"Server listening at '{}'".
format(address))
104 parser = argparse.ArgumentParser(description=_DESCRIPTION)
105 parser.add_argument(
'--port',
109 help=
'The port on which the server will listen.')
115 help=
'The maximum number of hashes to search before cancelling.')
116 args = parser.parse_args()
118 server.wait_for_termination()
121 if __name__ ==
"__main__":
122 logging.basicConfig()