1# Copyright 2017 gRPC authors. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""Tests that a channel will reconnect if a connection is dropped""" 15 16import logging 17import socket 18import time 19import unittest 20 21import grpc 22from grpc.framework.foundation import logging_pool 23 24from tests.unit.framework.common import bound_socket 25from tests.unit.framework.common import test_constants 26 27_REQUEST = b"\x00\x00\x00" 28_RESPONSE = b"\x00\x00\x01" 29 30_SERVICE_NAME = "test" 31_UNARY_UNARY = "UnaryUnary" 32 33 34def _handle_unary_unary(unused_request, unused_servicer_context): 35 return _RESPONSE 36 37 38_METHOD_HANDLERS = { 39 _UNARY_UNARY: grpc.unary_unary_rpc_method_handler(_handle_unary_unary) 40} 41 42 43class ReconnectTest(unittest.TestCase): 44 def test_reconnect(self): 45 server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY) 46 handler = grpc.method_handlers_generic_handler( 47 "test", 48 { 49 "UnaryUnary": grpc.unary_unary_rpc_method_handler( 50 _handle_unary_unary 51 ) 52 }, 53 ) 54 options = (("grpc.so_reuseport", 1),) 55 with bound_socket() as (host, port): 56 addr = "{}:{}".format(host, port) 57 server = grpc.server(server_pool, options=options) 58 server.add_registered_method_handlers( 59 _SERVICE_NAME, _METHOD_HANDLERS 60 ) 61 server.add_insecure_port(addr) 62 server.start() 63 channel = grpc.insecure_channel(addr) 64 multi_callable = channel.unary_unary( 65 grpc._common.fully_qualified_method(_SERVICE_NAME, _UNARY_UNARY), 66 _registered_method=True, 67 ) 68 self.assertEqual(_RESPONSE, multi_callable(_REQUEST)) 69 server.stop(None) 70 # By default, the channel connectivity is checked every 5s 71 # GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS can be set to change 72 # this. 73 time.sleep(5.1) 74 server = grpc.server(server_pool, (handler,), options=options) 75 server.add_insecure_port(addr) 76 server.start() 77 self.assertEqual(_RESPONSE, multi_callable(_REQUEST)) 78 server.stop(None) 79 channel.close() 80 81 82if __name__ == "__main__": 83 logging.basicConfig() 84 unittest.main(verbosity=2) 85