Python grpc.FutureTimeoutError() Examples

The following are 12 code examples of grpc.FutureTimeoutError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module grpc , or try the search function .
Example #1
Source File: sample_client_demo_timeout.py    From python-grpc-demo with MIT License 6 votes vote down vote up
def run():
    channel = grpc.insecure_channel('localhost:50051')
    try:
        grpc.channel_ready_future(channel).result(timeout=10)
    except grpc.FutureTimeoutError:
        sys.exit('Error connecting to server')
    else:
        stub = users_service.UsersStub(channel)
        metadata = [('ip', '127.0.0.1')]
        response = stub.CreateUser(
            users_messages.CreateUserRequest(username='tom'),
            metadata=metadata,
        )
        if response:
            print("User created:", response.user.username)
        request = users_messages.GetUsersRequest(
            user=[users_messages.User(username="alexa", user_id=1),
                  users_messages.User(username="christie", user_id=1)]
        )
        response = stub.GetUsers(request, timeout=0.00001)
        for resp in response:
            print(resp) 
Example #2
Source File: sample_client_demo_timeout.py    From python-grpc-demo with MIT License 6 votes vote down vote up
def run():
    channel = grpc.insecure_channel('localhost:50051')
    try:
        grpc.channel_ready_future(channel).result(timeout=10)
    except grpc.FutureTimeoutError:
        sys.exit('Error connecting to server')
    else:
        stub = users_service.UsersStub(channel)
        metadata = [('ip', '127.0.0.1')]
        response = stub.CreateUser(
            users_messages.CreateUserRequest(username='tom'),
            metadata=metadata,
        )
        if response:
            print("User created:", response.user.username)
        request = users_messages.GetUsersRequest(
            user=[users_messages.User(username="alexa", user_id=1),
                  users_messages.User(username="christie", user_id=1)]
        )
        response = stub.GetUsers(request, timeout=0.00001)
        for resp in response:
            print(resp) 
Example #3
Source File: sample_client_demo.py    From python-grpc-demo with MIT License 6 votes vote down vote up
def run():
    channel = grpc.insecure_channel('localhost:50051')
    try:
        grpc.channel_ready_future(channel).result(timeout=10)
    except grpc.FutureTimeoutError:
        sys.exit('Error connecting to server')
    else:
        stub = users_service.UsersStub(channel)
        metadata = [('ip', '127.0.0.1')]
        response = stub.CreateUser(
            users_messages.CreateUserRequest(username='tom'),
            metadata=metadata,
        )
        if response:
            print("User created:", response.user.username)
        request = users_messages.GetUsersRequest(
            user=[users_messages.User(username="alexa", user_id=1),
                  users_messages.User(username="christie", user_id=1)]
        )
        response = stub.GetUsers(request)
        for resp in response:
            print(resp) 
Example #4
Source File: grpc_handler.py    From pymilvus with Apache License 2.0 6 votes vote down vote up
def ping(self, timeout=30):
        ft = grpc.channel_ready_future(self._channel)
        retry = self._max_retry
        try:
            while retry > 0:
                try:
                    ft.result(timeout=timeout)
                    return True
                except:
                    retry -= 1
                    LOGGER.debug("Retry connect addr <{}> {} times".format(self._uri, self._max_retry - retry))
                    if retry > 0:
                        continue
                    else:
                        LOGGER.error("Retry to connect server {} failed.".format(self._uri))
                        raise
        except grpc.FutureTimeoutError:
            raise NotConnectError('Fail connecting to server on {}. Timeout'.format(self._uri))
        except grpc.RpcError as e:
            raise NotConnectError("Connect error: <{}>".format(e))
        # Unexpected error
        except Exception as e:
            raise NotConnectError("Error occurred when trying to connect server:\n"
                                  "\t<{}>".format(str(e))) 
Example #5
Source File: test_collection.py    From pymilvus with Apache License 2.0 6 votes vote down vote up
def test_create_collection_exception(self, gcon):
        collection_param = {
            "collection_name": "test_create_collection_exceptions",
            "dimension": 128,
            "metric_type": MetricType.L2,
            "index_file_size": 10
        }

        mock_grpc_timeout = mock.MagicMock(side_effect=grpc.FutureTimeoutError())
        with mock.patch.object(Uum, 'future', mock_grpc_timeout):
            status = gcon.create_collection(collection_param)
            assert not status.OK()

        mock_grpc_error = mock.MagicMock(side_effect=MockGrpcError())
        with mock.patch.object(Uum, 'future', mock_grpc_error):
            status = gcon.create_collection(collection_param)
            assert not status.OK()

        mock_exception = mock.MagicMock(side_effect=Exception("error"))
        with mock.patch.object(Uum, 'future', mock_exception):
            status = gcon.create_collection(collection_param)
            assert not status.OK() 
Example #6
Source File: configure.py    From VectorCloud with GNU General Public License v3.0 5 votes vote down vote up
def user_authentication(session_id: bytes, cert: bytes, ip: str, name: str) -> str:
    # Pin the robot certificate for opening the channel
    creds = grpc.ssl_channel_credentials(root_certificates=cert)

    print("Attempting to download guid from {} at {}:443...".format(
        colored(name, "cyan"), colored(ip, "cyan")), end="")
    sys.stdout.flush()
    channel = grpc.secure_channel("{}:443".format(ip), creds,
                                  options=(("grpc.ssl_target_name_override", name,),))

    # Verify the connection to Vector is able to be established (client-side)
    try:
        # Explicitly grab _channel._channel to test the underlying grpc channel directly
        grpc.channel_ready_future(channel).result(timeout=15)
    except grpc.FutureTimeoutError:
        print(colored(" ERROR", "red"))
        sys.exit("\nUnable to connect to Vector\n"
                 "Please be sure to connect via the Vector companion app first, and connect your computer to the same network as your Vector.")

    try:
        interface = messaging.client.ExternalInterfaceStub(channel)
        request = messaging.protocol.UserAuthenticationRequest(
            user_session_id=session_id.encode('utf-8'),
            client_name=socket.gethostname().encode('utf-8'))
        response = interface.UserAuthentication(request)
        if response.code != messaging.protocol.UserAuthenticationResponse.AUTHORIZED:  # pylint: disable=no-member
            print(colored(" ERROR", "red"))
            sys.exit("\nFailed to authorize request:\n"
                     "Please be sure to first set up Vector using the companion app.")
    except grpc.RpcError as e:
        print(colored(" ERROR", "red"))
        sys.exit("\nFailed to authorize request:\n"
                 "An unknown error occurred '{}'".format(e))

    print(colored(" DONE\n", "green"))
    return response.client_token_guid 
Example #7
Source File: _load_environment.py    From dm_memorytasks with Apache License 2.0 5 votes vote down vote up
def _check_grpc_channel_ready(channel):
  """Helper function to check the gRPC channel is ready N times."""
  for _ in range(_MAX_CONNECTION_ATTEMPTS - 1):
    try:
      return grpc.channel_ready_future(channel).result(timeout=1)
    except grpc.FutureTimeoutError:
      pass
  return grpc.channel_ready_future(channel).result(timeout=1) 
Example #8
Source File: sample_client_demo.py    From python-grpc-demo with MIT License 5 votes vote down vote up
def run():
    # read in certificate
    with open('server.crt') as f:
        trusted_certs = f.read().encode()

    # create credentials
    credentials = grpc.ssl_channel_credentials(root_certificates=trusted_certs)
    channel = grpc.secure_channel('localhost:50051', credentials)
    try:
        grpc.channel_ready_future(channel).result(timeout=10)
    except grpc.FutureTimeoutError:
        sys.exit('Error connecting to server')
    else:
        stub = users_service.UsersStub(channel)
        metadata = [('ip', '127.0.0.1')]

        try:
            response = stub.CreateUser(
                users_messages.CreateUserRequest(username='tom'),
                metadata=metadata,
            )
        except grpc.RpcError as e:
            print('CreateUser failed with {0}: {1}'.format(e.code(), e.details()))
        else:
            print("User created:", response.user.username)

        request = users_messages.GetUsersRequest(
            user=[users_messages.User(username="alexa", user_id=1),
                  users_messages.User(username="christie", user_id=1)]
        )
        response = stub.GetUsers(request)
        for resp in response:
            print(resp) 
Example #9
Source File: client_wrapper.py    From python-grpc-demo with MIT License 5 votes vote down vote up
def __init__(self, service_module, stub_name, host, port, timeout=10):
        channel = grpc.insecure_channel('{0}:{1}'.format(host, port))
        try:
            grpc.channel_ready_future(channel).result(timeout=10)
        except grpc.FutureTimeoutError:
            sys.exit('Error connecting to server')
        self.stub = getattr(service_module, stub_name)(channel)
        self.timeout = timeout 
Example #10
Source File: grpc_handler.py    From pymilvus with Apache License 2.0 5 votes vote down vote up
def error_handler(*rargs):
    def wrapper(func):
        def handler(self, *args, **kwargs):
            record_dict = {}
            try:
                record_dict["API start"] = str(datetime.datetime.now())
                if self._pre_ping:
                    self.ping()
                record_dict["RPC start"] = str(datetime.datetime.now())
                return func(self, *args, **kwargs)
            except grpc.FutureTimeoutError as e:
                record_dict["RPC timeout"] = str(datetime.datetime.now())
                LOGGER.error("\nAddr [{}] {}\nRequest timeout: {}\n\t{}".format(self.server_address, func.__name__, e, record_dict))
                status = Status(Status.UNEXPECTED_ERROR, message='Request timeout')
                return status if not rargs else tuple([status]) + rargs
            except grpc.RpcError as e:
                record_dict["RPC error"] = str(datetime.datetime.now())

                LOGGER.error("\nAddr [{}] {}\nRpc error: {}\n\t{}".format(self.server_address, func.__name__, e, record_dict))
                status = Status(e.code(), message='Error occurred. {}'.format(e.details()))
                return status if not rargs else tuple([status]) + rargs
            except Exception as e:
                record_dict["Exception"] = str(datetime.datetime.now())
                LOGGER.error("\nAddr [{}] {}\nExcepted error: {}\n\t{}".format(self.server_address, func.__name__, e, record_dict))
                status = Status(Status.UNEXPECTED_ERROR, message=str(e))
                return status if not rargs else tuple([status]) + rargs

        return handler

    return wrapper 
Example #11
Source File: remote_football_env.py    From football with Apache License 2.0 5 votes vote down vote up
def _update_master(self):
    while True:
      try:
        master_address = utils.get_master_address(self._track)
        logging.info('Connecting to %s', master_address)
        self._master_channel = utils.get_grpc_channel(master_address)
        grpc.channel_ready_future(self._master_channel).result(timeout=10)
        break
      except grpc.FutureTimeoutError:
        logging.info('Failed to connect to master')
      except BaseException as e:
        logging.info('Error %s, sleeping 10 secs', e)
        time.sleep(10)
    logging.info('Connection successful') 
Example #12
Source File: grpc_handler.py    From pymilvus with Apache License 2.0 4 votes vote down vote up
def set_uri(host, port, uri):
    if host is not None:
        _port = port if port is not None else config.GRPC_PORT
        _host = host
    elif port is None:
        try:
            _uri = urlparse(uri) if uri else urlparse(config.GRPC_URI)
            _host = _uri.hostname
            _port = _uri.port
        except (AttributeError, ValueError, TypeError) as e:
            raise ParamError("uri is illegal: {}".format(e))
    else:
        raise ParamError("Param is not complete. Please invoke as follow:\n"
                         "\t(host = ${HOST}, port = ${PORT})\n"
                         "\t(uri = ${URI})\n")

    if not is_legal_host(_host) or not is_legal_port(_port):
        raise ParamError("host or port is illeagl")

    return "{}:{}".format(str(_host), str(_port))


# def connect(addr, timeout):
#     channel = grpc.insecure_channel(
#         addr,
#         options=[(cygrpc.ChannelArgKey.max_send_message_length, -1),
#                  (cygrpc.ChannelArgKey.max_receive_message_length, -1)]
#     )
#     try:
#         ft = grpc.channel_ready_future(channel)
#         ft.result(timeout=timeout)
#         return True
#     except grpc.FutureTimeoutError:
#         raise NotConnectError('Fail connecting to server on {}. Timeout'.format(addr))
#     except grpc.RpcError as e:
#         raise NotConnectError("Connect error: <{}>".format(e))
#     # Unexpected error
#     except Exception as e:
#         raise NotConnectError("Error occurred when trying to connect server:\n"
#                               "\t<{}>".format(str(e)))
#     finally:
#         ft.cancel()
#         ft.__del__()
#         channel.__del__()