Python grpc.channel_ready_future() Examples

The following are 15 code examples of grpc.channel_ready_future(). 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: server.py    From orbdetpy with GNU General Public License v3.0 6 votes vote down vote up
def connect(cls, datadir, jarfile):
        # Check for running server instances
        jar = os.path.split(jarfile)[-1]
        for p in psutil.process_iter(attrs = ["name", "cmdline"]):
            if (p.info["name"] == "java" and
                any(x.endswith(jar) for x in p.info["cmdline"])):
                return

        # Start server
        cmdline = ["java", "-Xmx2G", "-XX:+UseG1GC", "-jar",
                   jarfile, str(cls.rpc_port), datadir]
        cls.rpc_server_proc = psutil.Popen(cmdline)

        atexit.register(RemoteServer.disconnect)
        with grpc.insecure_channel(cls.rpc_uri) as chan:
            grpc.channel_ready_future(chan).result(timeout = 60.0) 
Example #6
Source File: remote_football_env.py    From football with Apache License 2.0 6 votes vote down vote up
def reset(self):
    if self._channel is not None:
      # Client surrenders in the current game and starts next one.

      self._channel.close()
      self._channel = None

    # Get game server address and side id from master.
    start_game_request = master_pb2.StartGameRequest(
        game_version=config.game_version, username=self._username,
        token=self._token, model_name=self._model_name,
        include_rendering=self._include_rendering)
    response = self._reset_with_retries(start_game_request)
    self._game_id = response.game_id
    self._channel = utils.get_grpc_channel(response.game_server_address)
    grpc.channel_ready_future(self._channel).result()
    get_env_result_request = game_server_pb2.GetEnvResultRequest(
        game_version=config.game_version, game_id=self._game_id,
        username=self._username, token=self._token, model_name=self._model_name)
    return self._get_env_result(get_env_result_request, 'GetEnvResult')[0] 
Example #7
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 #8
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 #9
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 #10
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 #11
Source File: impl.py    From ftlib with Apache License 2.0 5 votes vote down vote up
def _report_join(self, ips):
        for ip in ips:
            channel = grpc.insecure_channel(
                "{ip}:{port}".format(ip=ip, port=self._port)
            )
            try:
                grpc.channel_ready_future(channel).result(timeout=2)
            except Exception as e:
                logging.warning(str(e))
                return False
            else:
                stub = communicate_pb2_grpc.ReportStub(channel)
            try:
                response = stub.GetGroupStatus(
                    communicate_pb2.GroupStatusRequest(), timeout=2
                )
            except Exception as e:
                logging.warning(str(e))
            else:
                logging.info("counter retreived")
                self._count = response.counter
                self._io_tool.register_ip(
                    SharedStorage.ip_address, self._count
                )
                return True
        logging.warning("counter not retreived")
        self._io_tool.register_ip(SharedStorage.ip_address, self._count)
        return False 
Example #12
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 #13
Source File: es_master.py    From es_on_gke with Apache License 2.0 5 votes vote down vote up
def main(config):
    """Train an ES policy."""
    if config.run_on_gke:
        servers = ['{}'.format(addr)
                   for addr in config.server_addresses.split(',')]
    else:
        servers = ['127.0.0.1:{}'.format(config.server_port + i)
                   for i in range(config.num_workers)]
    print(servers)
    stubs = []
    for server in servers:
        if config.run_on_gke:
            channel = grpc.insecure_channel(
                server, [('grpc.lb_policy_name', 'round_robin')])
        else:
            channel = grpc.insecure_channel(server)
        grpc.channel_ready_future(channel).result()
        stubs.append(evaluation_service_pb2_grpc.RolloutStub(channel))

    learner.ESLearner(
        logdir=config.logdir,
        config=config.config,
        stubs=stubs,
    ).train()

    # This is to prevent GKE from restarting pod when the job finishes.
    if config.run_on_gke:
        try:
            while True:
                time.sleep(_ONE_DAY_IN_SECONDS)
        except KeyboardInterrupt:
            print('Job done.') 
Example #14
Source File: openolt_device.py    From voltha with Apache License 2.0 5 votes vote down vote up
def do_state_init(self, event):
        # Initialize gRPC
        self.channel = grpc.insecure_channel(self.host_and_port)
        self.channel_ready_future = grpc.channel_ready_future(self.channel)

        self.log.info('openolt-device-created') 
Example #15
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__()