Python grpc.RpcError() Examples

The following are 30 code examples of grpc.RpcError(). 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: test_api_callable.py    From gax-python with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def test_wrap_value_error(self):
        from google.gax.errors import InvalidArgumentError

        invalid_attribute_exc = grpc.RpcError()
        invalid_attribute_exc.code = lambda: grpc.StatusCode.INVALID_ARGUMENT

        def value_error_func(*dummy_args, **dummy_kwargs):
            raise invalid_attribute_exc

        value_error_callable = api_callable.create_api_call(
            value_error_func, _CallSettings())

        with self.assertRaises(ValueError) as exc_info:
            value_error_callable(None)

        self.assertIsInstance(exc_info.exception, InvalidArgumentError)
        self.assertEqual(exc_info.exception.args, (u'RPC failed',))
        self.assertIs(exc_info.exception.cause, invalid_attribute_exc) 
Example #2
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 #3
Source File: exception_interceptor_test.py    From google-ads-python with Apache License 2.0 6 votes vote down vote up
def test_intercept_unary_unary_response_is_exception(self):
        """If response.exception() is not None exception is handled."""
        mock_exception = grpc.RpcError()

        class MockResponse():
            def exception(self):
                return mock_exception

        mock_request = mock.Mock()
        mock_client_call_details = mock.Mock()
        mock_response = MockResponse()

        def mock_continuation(client_call_details, request):
            del client_call_details
            del request
            return mock_response

        interceptor = self._create_test_interceptor()

        with mock.patch.object(interceptor, '_handle_grpc_failure'):
            interceptor.intercept_unary_unary(
                mock_continuation, mock_client_call_details, mock_request)

            interceptor._handle_grpc_failure.assert_called_once_with(
                mock_response) 
Example #4
Source File: exception_interceptor_test.py    From google-ads-python with Apache License 2.0 6 votes vote down vote up
def test_handle_grpc_failure_not_google_ads_failure(self):
        """Raises as-is non-retryable non-GoogleAdsFailure exceptions."""
        class MockRpcErrorResponse(grpc.RpcError):
            def code(self):
                return grpc.StatusCode.INVALID_ARGUMENT

            def trailing_metadata(self):
                return (('bad-failure-key', 'arbitrary-value'),)

            def exception(self):
                return self

        interceptor = self._create_test_interceptor()

        self.assertRaises(MockRpcErrorResponse,
                          interceptor._handle_grpc_failure,
                          MockRpcErrorResponse()) 
Example #5
Source File: Tbon.py    From pcocc with GNU General Public License v3.0 6 votes vote down vote up
def command(self, dest, cmd, data, timeout):
        logging.info("sending %s to %d", cmd, dest)
        try:
            grpc_message = agent_pb2.RouteMessage(destination=dest, name=cmd)
            grpc_message.args.Pack(data)

        except Exception as e:
            return self._handle_route_result(cmd,
                                agent_pb2.RouteMessageResult(
                                    source=dest,
                                    error=agent_pb2.GenericError(
                                        kind=agent_pb2.GenericError.PayloadError,
                                        description="Unable to create message "
                                        "with payload: {}".format(e))))

        try:
            res = self._stub.route_command(grpc_message, timeout=timeout)
        except grpc.RpcError as e:
            res = self._handle_grpc_error(e, dest)
        return self._handle_route_result(cmd, res) 
Example #6
Source File: exception_interceptor_test.py    From google-ads-python with Apache License 2.0 6 votes vote down vote up
def test_handle_grpc_failure(self):
        """Raises non-retryable GoogleAdsFailures as GoogleAdsExceptions."""
        mock_error_message = _MOCK_FAILURE_VALUE

        class MockRpcErrorResponse(grpc.RpcError):
            def code(self):
                return grpc.StatusCode.INVALID_ARGUMENT

            def trailing_metadata(self):
                return ((interceptor._failure_key, mock_error_message),)

            def exception(self):
                return self

        interceptor = self._create_test_interceptor()

        self.assertRaises(GoogleAdsException,
                          interceptor._handle_grpc_failure,
                          MockRpcErrorResponse()) 
Example #7
Source File: base_test.py    From fabric-p4test with Apache License 2.0 6 votes vote down vote up
def next(self):
        while self.idx < len(self.errors):
            p4_error = p4runtime_pb2.Error()
            one_error_any = self.errors[self.idx]
            if not one_error_any.Unpack(p4_error):
                raise P4RuntimeErrorFormatException(
                    "Cannot convert Any message to p4.Error")
            if p4_error.canonical_code == code_pb2.OK:
                continue
            v = self.idx, p4_error
            self.idx += 1
            return v
        raise StopIteration


# P4Runtime uses a 3-level message in case of an error during the processing of
# a write batch. This means that if we do not wrap the grpc.RpcError inside a
# custom exception, we can end-up with a non-helpful exception message in case
# of failure as only the first level will be printed. In this custom exception
# class, we extract the nested error message (one for each operation included in
# the batch) in order to print error code + user-facing message.  See P4 Runtime
# documentation for more details on error-reporting. 
Example #8
Source File: test_inference_endpoints.py    From inference-model-manager with Apache License 2.0 6 votes vote down vote up
def test_wrong_certificates():
    url = endpoint_info.info

    trusted_cert, wrong_key, wrong_ca = prepare_certs(
        CERT_SERVER,
        CERT_BAD_CLIENT_KEY,
        CERT_BAD_CLIENT)
    creds = grpc.ssl_channel_credentials(root_certificates=trusted_cert,
                                         private_key=wrong_key, certificate_chain=wrong_ca)
    stub, request = prepare_stub_and_request(url, MODEL_NAME, creds=creds)

    numpy_input = numpy.zeros((1, 224, 224, 3), numpy.dtype('<f'))

    request.inputs[model_input].CopyFrom(
        tf.contrib.util.make_tensor_proto(numpy_input, shape=[1, 224, 224, 3]))

    with pytest.raises(grpc.RpcError) as context:
        stub.Predict(request, RPC_TIMEOUT)

    assert context.value.details() == 'Received http2 header with status: 403' 
Example #9
Source File: grpc_lib.py    From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run(self):
        self.status = 'running'
        try:
            self.receiver()
        except RpcError as rpc_error:
            logger.error('{code} {details}'.format(code=rpc_error.code(),
                                                   details=rpc_error.details()))
            self.error = rpc_error
        except Exception as e:
            logger.error('Unhandled exception happened')
            logger.error(str(e))
            self.error = e
            self.status = 'erroneous'
            raise
        finally:
            self.work_queue = Queue()
            self.rpc_handler = None
        self.status = 'finished' 
Example #10
Source File: lnd.initwallet.py    From raspiblitz with MIT License 6 votes vote down vote up
def seed(stub, wallet_password="", seed_words="", seed_password=""):
    request = ln.InitWalletRequest(
        wallet_password=wallet_password.encode(),
        cipher_seed_mnemonic=[x.encode() for x in seed_words],
        recovery_window=5000,
        aezeed_passphrase=seed_password.encode()
    )

    try:
        response = stub.InitWallet(request)
    except grpc.RpcError as rpc_error_call:
        code = rpc_error_call.code()
        print(code, file=sys.stderr)
        details = rpc_error_call.details()
        print("err='RPCError InitWallet'")
        print("errMore=\"" + details + "\"")
        sys.exit(1)
    except:
        e = sys.exc_info()[0]
        print(e, file=sys.stderr)
        print("err='InitWallet'")
        sys.exit(1) 
Example #11
Source File: assistant.py    From google-assistant-hotword-raspi with MIT License 6 votes vote down vote up
def is_grpc_error_unavailable(e):
        is_grpc_error = isinstance(e, grpc.RpcError)
        if is_grpc_error and (e.code() == grpc.StatusCode.UNAVAILABLE):
            logging.error('grpc unavailable error: %s', e)
            return True
        return False 
Example #12
Source File: remote_executor.py    From federated with Apache License 2.0 6 votes vote down vote up
def _is_retryable_grpc_error(error):
  """Predicate defining what is a retryable gRPC error."""
  non_retryable_errors = {
      grpc.StatusCode.INVALID_ARGUMENT,
      grpc.StatusCode.NOT_FOUND,
      grpc.StatusCode.ALREADY_EXISTS,
      grpc.StatusCode.PERMISSION_DENIED,
      grpc.StatusCode.FAILED_PRECONDITION,
      grpc.StatusCode.ABORTED,
      grpc.StatusCode.OUT_OF_RANGE,
      grpc.StatusCode.UNIMPLEMENTED,
      grpc.StatusCode.DATA_LOSS,
      grpc.StatusCode.UNAUTHENTICATED,
  }
  return (isinstance(error, grpc.RpcError) and
          error.code() not in non_retryable_errors) 
Example #13
Source File: exception_interceptor_test.py    From google-ads-python with Apache License 2.0 5 votes vote down vote up
def test_intercept_unary_stream_response_is_exception(self):
        """Ensure errors raised from response iteration are handled/wrapped."""
        mock_exception = grpc.RpcError()

        class MockResponse():
            # Mock the response object so that it raises an error when
            # iterated upon.
            def __next__(self):
                raise mock_exception

        mock_request = mock.Mock()
        mock_client_call_details = mock.Mock()
        mock_response = MockResponse()

        def mock_continuation(client_call_details, request):
            del client_call_details
            del request
            return mock_response

        interceptor = self._create_test_interceptor()

        with mock.patch.object(interceptor, '_handle_grpc_failure'):
            response = interceptor.intercept_unary_stream(
                    mock_continuation, mock_client_call_details, mock_request)

            # Ensure the returned value is a wrapped response object.
            self.assertIsInstance(response, _UnaryStreamWrapper)

            # Initiate an iteration of the wrapped response object
            next(response)

            # Check that the error handler method on the interceptor instance
            # was called as a result of the iteration.
            interceptor._handle_grpc_failure.assert_called_once_with(
                mock_response) 
Example #14
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 #15
Source File: test_opentracing.py    From python-grpc with Apache License 2.0 5 votes vote down vote up
def testStreamUnaryOpenTracing(self):
        multi_callable = self._service.stream_unary_multi_callable
        requests = [b'\x01', b'\x02']
        self.assertRaises(grpc.RpcError, multi_callable, iter(requests))

        span0 = self._tracer.get_span(0)
        self.assertIsNotNone(span0)
        self.assertTrue(span0.get_tag('error'))

        span1 = self._tracer.get_span(1)
        self.assertIsNotNone(span1)
        self.assertTrue(span1.get_tag('error')) 
Example #16
Source File: test_opentracing.py    From python-grpc with Apache License 2.0 5 votes vote down vote up
def testUnaryUnaryOpenTracing(self):
        multi_callable = self._service.unary_unary_multi_callable
        request = b'\x01'
        self.assertRaises(grpc.RpcError, multi_callable, request)

        span0 = self._tracer.get_span(0)
        self.assertIsNotNone(span0)
        self.assertTrue(span0.get_tag('error'))

        span1 = self._tracer.get_span(1)
        self.assertIsNotNone(span1)
        self.assertTrue(span1.get_tag('error')) 
Example #17
Source File: test_opentracing.py    From python-grpc with Apache License 2.0 5 votes vote down vote up
def testStreamUnaryOpenTracingWithCall(self):
        multi_callable = self._service.stream_unary_multi_callable
        requests = [b'\x01', b'\x02']
        self.assertRaises(grpc.RpcError, multi_callable.with_call,
                          iter(requests))

        span0 = self._tracer.get_span(0)
        self.assertIsNotNone(span0)
        self.assertTrue(span0.get_tag('error'))

        span1 = self._tracer.get_span(1)
        self.assertIsNotNone(span1)
        self.assertTrue(span1.get_tag('error')) 
Example #18
Source File: test_opentracing.py    From python-grpc with Apache License 2.0 5 votes vote down vote up
def testStreamUnaryOpenTracing(self):
        multi_callable = self._service.stream_unary_multi_callable
        requests = [b'\x01', b'\x02']
        self.assertRaises(grpc.RpcError, multi_callable, iter(requests))

        span0 = self._tracer.get_span(0)
        self.assertIsNotNone(span0)
        self.assertTrue(span0.get_tag('error'))

        span1 = self._tracer.get_span(1)
        self.assertIsNotNone(span1)
        self.assertTrue(span1.get_tag('error')) 
Example #19
Source File: test_opentracing.py    From python-grpc with Apache License 2.0 5 votes vote down vote up
def testUnaryStreamOpenTracing(self):
        multi_callable = self._service.unary_stream_multi_callable
        request = b'\x01'
        response = multi_callable(request)
        self.assertRaises(grpc.RpcError, list, response)

        span0 = self._tracer.get_span(0)
        self.assertIsNotNone(span0)
        self.assertTrue(span0.get_tag('error'))

        span1 = self._tracer.get_span(1)
        self.assertIsNotNone(span1)
        self.assertTrue(span1.get_tag('error')) 
Example #20
Source File: test_opentracing.py    From python-grpc with Apache License 2.0 5 votes vote down vote up
def testUnaryUnaryOpenTracingWithCall(self):
        multi_callable = self._service.unary_unary_multi_callable
        request = b'\x01'
        self.assertRaises(grpc.RpcError, multi_callable.with_call, request)

        span0 = self._tracer.get_span(0)
        self.assertIsNotNone(span0)
        self.assertTrue(span0.get_tag('error'))

        span1 = self._tracer.get_span(1)
        self.assertIsNotNone(span1)
        self.assertTrue(span1.get_tag('error')) 
Example #21
Source File: clusterspecgenerator_client.py    From hops-tensorflow with Apache License 2.0 5 votes vote down vote up
def register_container(self, application_id, ip, port, job_name, task_index, tb_port):
    container = csg.Container()
    container.applicationId = application_id
    container.ip = ip
    container.port = port
    container.jobName = job_name
    container.taskIndex = task_index
    container.tbPort = tb_port
    request = csg.RegisterContainerRequest(container=container)
    try:
      self.stub.RegisterContainer(request)
    except grpc.RpcError:
      return False
    return True 
Example #22
Source File: __init__.py    From platypush with MIT License 5 votes vote down vote up
def is_grpc_error_unavailable(e):
        is_grpc_error = isinstance(e, grpc.RpcError)
        if is_grpc_error and (e.code() == grpc.StatusCode.UNAVAILABLE):
            logging.error('grpc unavailable error: %s', e)
            return True
        return False 
Example #23
Source File: streaming_pull_manager.py    From python-pubsub with Apache License 2.0 5 votes vote down vote up
def _maybe_wrap_exception(exception):
    """Wraps a gRPC exception class, if needed."""
    if isinstance(exception, grpc.RpcError):
        return exceptions.from_grpc_error(exception)
    return exception 
Example #24
Source File: remote_executor_test.py    From federated with Apache License 2.0 5 votes vote down vote up
def test_create_call_reraises_grpc_error(self, mock_stub):
    instance = mock_stub.return_value
    instance.CreateCall = mock.Mock(side_effect=_raise_non_retryable_grpc_error)
    loop = asyncio.get_event_loop()
    executor = create_remote_executor()
    type_signature = computation_types.FunctionType(None, tf.int32)
    comp = remote_executor.RemoteValue(executor_pb2.ValueRef(), type_signature,
                                       executor)

    with self.assertRaises(grpc.RpcError) as context:
      loop.run_until_complete(executor.create_call(comp, None))

    self.assertEqual(context.exception.code(), grpc.StatusCode.ABORTED) 
Example #25
Source File: remote_executor_test.py    From federated with Apache License 2.0 5 votes vote down vote up
def test_compute_reraises_grpc_error(self, mock_stub):
    instance = mock_stub.return_value
    instance.Compute = mock.Mock(side_effect=_raise_non_retryable_grpc_error)
    loop = asyncio.get_event_loop()
    executor = create_remote_executor()
    type_signature = computation_types.FunctionType(None, tf.int32)
    comp = remote_executor.RemoteValue(executor_pb2.ValueRef(), type_signature,
                                       executor)

    with self.assertRaises(grpc.RpcError) as context:
      loop.run_until_complete(comp.compute())

    self.assertEqual(context.exception.code(), grpc.StatusCode.ABORTED) 
Example #26
Source File: exception_interceptor_test.py    From google-ads-python with Apache License 2.0 5 votes vote down vote up
def test_handle_grpc_failure_retryable(self):
        """Raises retryable exceptions as-is."""
        class MockRpcErrorResponse(grpc.RpcError):
            def code(self):
                return grpc.StatusCode.INTERNAL

            def exception(self):
                return self

        interceptor = self._create_test_interceptor()

        self.assertRaises(MockRpcErrorResponse,
                          interceptor._handle_grpc_failure,
                          MockRpcErrorResponse()) 
Example #27
Source File: remote_executor_test.py    From federated with Apache License 2.0 5 votes vote down vote up
def test_create_selection_reraises_non_retryable_grpc_error(self, mock_stub):
    instance = mock_stub.return_value
    instance.CreateSelection = mock.Mock(
        side_effect=_raise_non_retryable_grpc_error)
    loop = asyncio.get_event_loop()
    executor = create_remote_executor()
    type_signature = computation_types.NamedTupleType([tf.int32, tf.int32])
    source = remote_executor.RemoteValue(executor_pb2.ValueRef(),
                                         type_signature, executor)

    with self.assertRaises(grpc.RpcError) as context:
      loop.run_until_complete(executor.create_selection(source, index=0))

    self.assertEqual(context.exception.code(), grpc.StatusCode.ABORTED) 
Example #28
Source File: remote_executor.py    From federated with Apache License 2.0 5 votes vote down vote up
def _request(rpc_func, request):
  with tracing.wrap_rpc_in_trace_context():
    try:
      return rpc_func(request)
    except grpc.RpcError as e:
      if _is_retryable_grpc_error(e):
        logging.info('Received retryable gRPC error: %s', e)
        raise execution_context.RetryableError(e)
      else:
        raise 
Example #29
Source File: test_inference_endpoints.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def test_no_certificates():
    url = endpoint_info.info
    trusted_cert, _, _ = prepare_certs(CERT_SERVER)
    creds = grpc.ssl_channel_credentials(root_certificates=trusted_cert)
    stub, request = prepare_stub_and_request(url, MODEL_NAME, creds=creds)

    numpy_input = numpy.zeros((1, 224, 224, 3), numpy.dtype('<f'))

    request.inputs[model_input].CopyFrom(
        tf.contrib.util.make_tensor_proto(numpy_input, shape=[1, 224, 224, 3]))

    with pytest.raises(grpc.RpcError) as context:
        stub.Predict(request, RPC_TIMEOUT)

    assert context.value.details() == 'Received http2 header with status: 400' 
Example #30
Source File: test_inference_endpoints.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def test_version_not_served():
    stub, request = prepare_stub_and_request(endpoint_info.url, MODEL_NAME,
                                             model_version=1,
                                             creds=endpoint_info.credentials)

    request.inputs[model_input].CopyFrom(
        tf.contrib.util.make_tensor_proto(image, shape=image.shape))
    with pytest.raises(grpc.RpcError) as context:
        stub.Predict(request, RPC_TIMEOUT)

    logs = get_logs_of_pod(TENANT_NAME, endpoint_info.pod_name)
    logging.info(filter_serving_logs(logs))

    assert "Servable not found" in context.value.details()