Java Code Examples for io.grpc.StatusRuntimeException#getStatus()

The following examples show how to use io.grpc.StatusRuntimeException#getStatus() . 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 check out the related API usage on the sidebar.
Example 1
Source File: CottontailWrapper.java    From cineast with MIT License 6 votes vote down vote up
/**
 * Pings the Cottontail DB endpoint and returns true on success and false otherwise.
 *
 * @return True on success, false otherwise.
 */
public boolean ping() {
  final CottonDQLBlockingStub stub = CottonDQLGrpc.newBlockingStub(this.channel).withDeadlineAfter(MAX_CALL_TIMEOUT, TimeUnit.MILLISECONDS);
  try {
    final SuccessStatus status = stub.ping(Empty.newBuilder().build());
    return true;
  } catch (StatusRuntimeException e) {
    if (e.getStatus() == Status.DEADLINE_EXCEEDED) {
      LOGGER.error("CottontailWrapper.ping has timed out.");
    } else {
      LOGGER.error("Error occurred during invocation of CottontailWrapper.ping: {}", e.getMessage());

    }
    return false;
  }
}
 
Example 2
Source File: CascadingTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * Test that when RPC cancellation propagates up a call chain, the cancellation of the parent
 * RPC triggers cancellation of all of its children.
 */
@Test
public void testCascadingCancellationViaLeafFailure() throws Exception {
  // All nodes (15) except one edge of the tree (4) will be cancelled.
  observedCancellations = new CountDownLatch(11);
  receivedCancellations = new CountDownLatch(11);
  startCallTreeServer(3);
  try {
    // Use response size limit to control tree nodeCount.
    blockingStub.unaryCall(Messages.SimpleRequest.newBuilder().setResponseSize(3).build());
    fail("Expected abort");
  } catch (StatusRuntimeException sre) {
    // Wait for the workers to finish
    Status status = sre.getStatus();
    // Outermost caller observes ABORTED propagating up from the failing leaf,
    // The descendant RPCs are cancelled so they receive CANCELLED.
    assertEquals(Status.Code.ABORTED, status.getCode());

    if (!observedCancellations.await(5, TimeUnit.SECONDS)) {
      fail("Expected number of cancellations not observed by clients");
    }
    if (!receivedCancellations.await(5, TimeUnit.SECONDS)) {
      fail("Expected number of cancellations to be received by servers not observed");
    }
  }
}
 
Example 3
Source File: CascadingTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Test that when RPC cancellation propagates up a call chain, the cancellation of the parent
 * RPC triggers cancellation of all of its children.
 */
@Test
public void testCascadingCancellationViaLeafFailure() throws Exception {
  // All nodes (15) except one edge of the tree (4) will be cancelled.
  observedCancellations = new CountDownLatch(11);
  receivedCancellations = new CountDownLatch(11);
  startCallTreeServer(3);
  try {
    // Use response size limit to control tree nodeCount.
    blockingStub.unaryCall(Messages.SimpleRequest.newBuilder().setResponseSize(3).build());
    fail("Expected abort");
  } catch (StatusRuntimeException sre) {
    // Wait for the workers to finish
    Status status = sre.getStatus();
    // Outermost caller observes ABORTED propagating up from the failing leaf,
    // The descendant RPCs are cancelled so they receive CANCELLED.
    assertEquals(Status.Code.ABORTED, status.getCode());

    if (!observedCancellations.await(5, TimeUnit.SECONDS)) {
      fail("Expected number of cancellations not observed by clients");
    }
    if (!receivedCancellations.await(5, TimeUnit.SECONDS)) {
      fail("Expected number of cancellations to be received by servers not observed");
    }
  }
}
 
Example 4
Source File: CottontailWrapper.java    From cineast with MIT License 5 votes vote down vote up
/**
 * Uses the Cottontail DB endpoint to list all entities.
 *
 * @param schema Schema for which to list entities.
 * @return List of entities.
 */
public List<Entity> listEntities(Schema schema) {
  ArrayList<Entity> entities = new ArrayList<>();
  final CottonDDLBlockingStub stub = CottonDDLGrpc.newBlockingStub(this.channel).withDeadlineAfter(MAX_CALL_TIMEOUT, TimeUnit.MILLISECONDS);
  try {
    stub.listEntities(schema).forEachRemaining(entities::add);
  } catch (StatusRuntimeException e) {
    if (e.getStatus() == Status.DEADLINE_EXCEEDED) {
      LOGGER.error("CottontailWrapper.listEntities has timed out (timeout = {}ms).", MAX_CALL_TIMEOUT);
    } else {
      LOGGER.error("Error occurred during invocation of CottontailWrapper.listEntities: {}", e.getMessage());
    }
  }
  return entities;
}
 
Example 5
Source File: AbstractInteropTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void maxOutboundSize_tooBig() {
  // set at least one field to ensure the size is non-zero.
  StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
      .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
      .build();


  MethodDescriptor<StreamingOutputCallRequest, StreamingOutputCallResponse> md =
      TestServiceGrpc.getStreamingOutputCallMethod();
  ByteSizeMarshaller<StreamingOutputCallRequest> mar =
      new ByteSizeMarshaller<>(md.getRequestMarshaller());
  blockingServerStreamingCall(
      blockingStub.getChannel(),
      md.toBuilder(mar, md.getResponseMarshaller()).build(),
      blockingStub.getCallOptions(),
      request)
      .next();

  TestServiceGrpc.TestServiceBlockingStub stub =
      blockingStub.withMaxOutboundMessageSize(mar.lastOutSize - 1);
  try {
    stub.streamingOutputCall(request).next();
    fail();
  } catch (StatusRuntimeException ex) {
    Status s = ex.getStatus();
    assertThat(s.getCode()).named(s.toString()).isEqualTo(Status.Code.CANCELLED);
    assertThat(Throwables.getStackTraceAsString(ex)).contains("message too large");
  }
}
 
Example 6
Source File: AbstractInteropTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void maxOutboundSize_tooBig() {
  // set at least one field to ensure the size is non-zero.
  StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
      .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
      .build();


  MethodDescriptor<StreamingOutputCallRequest, StreamingOutputCallResponse> md =
      TestServiceGrpc.getStreamingOutputCallMethod();
  ByteSizeMarshaller<StreamingOutputCallRequest> mar =
      new ByteSizeMarshaller<>(md.getRequestMarshaller());
  blockingServerStreamingCall(
      blockingStub.getChannel(),
      md.toBuilder(mar, md.getResponseMarshaller()).build(),
      blockingStub.getCallOptions(),
      request)
      .next();

  TestServiceGrpc.TestServiceBlockingStub stub =
      blockingStub.withMaxOutboundMessageSize(mar.lastOutSize - 1);
  try {
    stub.streamingOutputCall(request).next();
    fail();
  } catch (StatusRuntimeException ex) {
    Status s = ex.getStatus();
    assertWithMessage(s.toString()).that(s.getCode()).isEqualTo(Status.Code.CANCELLED);
    assertThat(Throwables.getStackTraceAsString(ex)).contains("message too large");
  }
}
 
Example 7
Source File: AbstractInteropTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void maxInboundSize_tooBig() {
  StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
      .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
      .build();

  MethodDescriptor<StreamingOutputCallRequest, StreamingOutputCallResponse> md =
      TestServiceGrpc.getStreamingOutputCallMethod();
  ByteSizeMarshaller<StreamingOutputCallRequest> mar =
      new ByteSizeMarshaller<>(md.getRequestMarshaller());
  blockingServerStreamingCall(
      blockingStub.getChannel(),
      md.toBuilder(mar, md.getResponseMarshaller()).build(),
      blockingStub.getCallOptions(),
      request)
      .next();

  int size = mar.lastOutSize;

  TestServiceGrpc.TestServiceBlockingStub stub =
      blockingStub.withMaxInboundMessageSize(size - 1);

  try {
    stub.streamingOutputCall(request).next();
    fail();
  } catch (StatusRuntimeException ex) {
    Status s = ex.getStatus();
    assertWithMessage(s.toString()).that(s.getCode()).isEqualTo(Status.Code.RESOURCE_EXHAUSTED);
    assertThat(Throwables.getStackTraceAsString(ex)).contains("exceeds maximum");
  }
}
 
Example 8
Source File: MinaSshdManagementClient.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
/**
 * Wraps call to unregisterSshTunnelingKey.
 *
 * @param requestId         the request ID for the request
 * @param minaSshdServiceId the minasshd service ID
 * @param keyId             the key ID
 * @return the response
 * @throws CcmException if an exception occurs
 */
public UnregisterSshTunnelingKeyResponse unregisterSshTunnelingKey(
        String requestId, String minaSshdServiceId, String keyId) throws CcmException {
    checkNotNull(requestId);
    checkNotNull(minaSshdServiceId);
    checkNotNull(keyId);

    MinaSshdManagementBlockingStub blockingStub = newStub(requestId);
    UnregisterSshTunnelingKeyRequest.Builder requestBuilder = UnregisterSshTunnelingKeyRequest.newBuilder()
            .setMinaSshdServiceId(minaSshdServiceId)
            .setKeyId(keyId);

    try {
        LOGGER.debug("Calling unregisterSshTunnelingKey with requestId: {}, minaSshdServiceId: {}, keyId: {}",
                requestId, minaSshdServiceId, keyId);
        UnregisterSshTunnelingKeyResponse response = blockingStub.unregisterSshTunnelingKey(requestBuilder.build());
        if (response == null) {
            throw new CcmException("Got null response from MinaSshdManagementService unregisterSshTunnelingKey gRPC call", false);
        } else {
            return response;
        }
    } catch (StatusRuntimeException e) {
        String message = "MinaSshdManagementService unregisterSshTunnelingKey gRPC call failed: " + e.getMessage();
        Status status = e.getStatus();
        Status.Code code = status.getCode();
        boolean retryable = GrpcUtil.isRetryable(code);
        LOGGER.debug("Got status code: {}, retryable: {}", code, retryable);
        throw new CcmException(message, e, retryable);
    }
}
 
Example 9
Source File: MinaSshdManagementClient.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
/**
 * Wraps call to generateAndRegisterSshTunnelingKeyPair.
 *
 * @param requestId         the request ID for the request
 * @param accountId         the account ID
 * @param minaSshdServiceId the minasshd service ID
 * @param keyId             the key ID
 * @return the response containing the key pair
 * @throws CcmException if an exception occurs
 */
public GenerateAndRegisterSshTunnelingKeyPairResponse generateAndRegisterSshTunnelingKeyPair(
        String requestId, String accountId, String minaSshdServiceId, String keyId) throws CcmException {
    checkNotNull(requestId);
    checkNotNull(accountId);
    checkNotNull(minaSshdServiceId);
    checkNotNull(keyId);

    MinaSshdManagementBlockingStub blockingStub = newStub(requestId);
    GenerateAndRegisterSshTunnelingKeyPairRequest.Builder requestBuilder = GenerateAndRegisterSshTunnelingKeyPairRequest.newBuilder()
            .setAccountId(accountId)
            .setMinaSshdServiceId(minaSshdServiceId)
            .setKeyId(keyId);

    try {
        LOGGER.debug("Calling generateAndRegisterSshTunnelingKeyPair with requestId: {}, accountId: {}, minaSshdServiceId: {}, keyId: {}",
                requestId, accountId, minaSshdServiceId, keyId);
        GenerateAndRegisterSshTunnelingKeyPairResponse response = blockingStub.generateAndRegisterSshTunnelingKeyPair(requestBuilder.build());
        if (response == null) {
            throw new CcmException("Got null response from MinaSshdManagementService generateAndRegisterSshTunnelingKeyPair gRPC call", false);
        } else {
            return response;
        }
    } catch (StatusRuntimeException e) {
        String message = "MinaSshdManagementService generateAndRegisterSshTunnelingKeyPair gRPC call failed: " + e.getMessage();
        Status status = e.getStatus();
        Status.Code code = status.getCode();
        boolean retryable = GrpcUtil.isRetryable(code);
        LOGGER.debug("Got status code: {}, retryable: {}", code, retryable);
        throw new CcmException(message, e, retryable);
    }
}
 
Example 10
Source File: MinaSshdManagementClient.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
/**
 * Wraps call to acquireMinaSshdService.
 *
 * @param requestId the request ID for the request
 * @param accountId the account ID
 * @return the minasshd service
 * @throws CcmException if an exception occurs
 */
public MinaSshdService acquireMinaSshdService(String requestId, String accountId) throws CcmException {
    checkNotNull(requestId);
    checkNotNull(accountId);

    MinaSshdManagementBlockingStub blockingStub = newStub(requestId);
    AcquireMinaSshdServiceRequest.Builder requestBuilder = AcquireMinaSshdServiceRequest.newBuilder()
            .setAccountId(accountId);

    try {
        LOGGER.debug("Calling acquireMinaSshdService with requestId: {}, accountId: {}",
                requestId, accountId);
        AcquireMinaSshdServiceResponse response = blockingStub.acquireMinaSshdService(requestBuilder.build());
        if (response == null) {
            throw new CcmException("Got null response from MinaSshdManagementService acquireMinaSshdService gRPC call", false);
        } else {
            MinaSshdService minaSshdService = response.getMinaSshdService();
            if (minaSshdService == null) {
                throw new CcmException("Got null minasshd service in MinaSshdManagementService acquireMinaSshdService gRPC response", false);
            } else {
                return minaSshdService;
            }
        }
    } catch (StatusRuntimeException e) {
        String message = "MinaSshdManagementService acquireMinaSshdService gRPC call failed: " + e.getMessage();
        Status status = e.getStatus();
        Status.Code code = status.getCode();
        boolean retryable = GrpcUtil.isRetryable(code);
        LOGGER.debug("Got status code: {}, retryable: {}", code, retryable);
        throw new CcmException(message, e, retryable);
    }
}
 
Example 11
Source File: AbstractInteropTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void maxInboundSize_tooBig() {
  StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
      .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
      .build();

  MethodDescriptor<StreamingOutputCallRequest, StreamingOutputCallResponse> md =
      TestServiceGrpc.getStreamingOutputCallMethod();
  ByteSizeMarshaller<StreamingOutputCallRequest> mar =
      new ByteSizeMarshaller<>(md.getRequestMarshaller());
  blockingServerStreamingCall(
      blockingStub.getChannel(),
      md.toBuilder(mar, md.getResponseMarshaller()).build(),
      blockingStub.getCallOptions(),
      request)
      .next();

  int size = mar.lastOutSize;

  TestServiceGrpc.TestServiceBlockingStub stub =
      blockingStub.withMaxInboundMessageSize(size - 1);

  try {
    stub.streamingOutputCall(request).next();
    fail();
  } catch (StatusRuntimeException ex) {
    Status s = ex.getStatus();
    assertThat(s.getCode()).named(s.toString()).isEqualTo(Status.Code.RESOURCE_EXHAUSTED);
    assertThat(Throwables.getStackTraceAsString(ex)).contains("exceeds maximum");
  }
}
 
Example 12
Source File: CottontailWrapper.java    From cineast with MIT License 5 votes vote down vote up
/**
 * Issues a batched query to the Cottontail DB endpoint in a blocking fashion.
 *
 * @return The query results (unprocessed).
 */
public List<QueryResponseMessage> batchedQuery(BatchedQueryMessage query) {
  final ArrayList<QueryResponseMessage> results = new ArrayList<>();
  final CottonDQLBlockingStub stub = CottonDQLGrpc.newBlockingStub(this.channel).withDeadlineAfter(MAX_QUERY_CALL_TIMEOUT, TimeUnit.MILLISECONDS);
  try {
    stub.batchedQuery(query).forEachRemaining(results::add);
  } catch (StatusRuntimeException e) {
    if (e.getStatus() == Status.DEADLINE_EXCEEDED) {
      LOGGER.error("CottontailWrapper.batchedQuery has timed out (timeout = {}ms).", MAX_QUERY_CALL_TIMEOUT);
    } else {
      LOGGER.error("Error occurred during invocation of CottontailWrapper.batchedQuery: {}", e.getMessage());
    }
  }
  return results;
}
 
Example 13
Source File: TestStreamObserver.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private RuntimeException exceptionMapper(Throwable error) {
    if (error instanceof StatusRuntimeException) {
        StatusRuntimeException e = (StatusRuntimeException) error;
        String errorMessage = "GRPC status " + e.getStatus() + ": " + e.getTrailers().get(ErrorResponses.KEY_TITUS_ERROR_REPORT);

        Optional<BadRequest> badRequest = GrpcClientErrorUtils.getDetail(e, BadRequest.class);
        if (badRequest.isPresent()) {
            return new RuntimeException(errorMessage + ". Invalid field values: " + badRequest, error);
        }
        return new RuntimeException(errorMessage, error);
    }
    return new RuntimeException(error.getMessage(), error);
}
 
Example 14
Source File: ProtocolCompatibilityTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private static void assertStatusRuntimeException(final StatusRuntimeException statusException,
                                                 final boolean withStatus)
        throws InvalidProtocolBufferException {
    final Status grpcStatus = statusException.getStatus();
    assertEquals(CUSTOM_ERROR_MESSAGE, grpcStatus.getDescription());
    final com.google.rpc.Status status = StatusProto.fromThrowable(statusException);
    assertNotNull(status);
    if (withStatus) {
        assertStatus(status, grpcStatus.getCode().value(), grpcStatus.getDescription());
    } else {
        assertFallbackStatus(status, grpcStatus.getCode().value(), grpcStatus.getDescription());
    }
}
 
Example 15
Source File: ExecutionStatusException.java    From bazel with Apache License 2.0 4 votes vote down vote up
ExecutionStatusException(
    StatusRuntimeException e, Status original, @Nullable ExecuteResponse response) {
  super(e.getStatus(), e.getTrailers());
  this.status = original;
  this.response = response;
}
 
Example 16
Source File: MinaSshdManagementClient.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
/**
 * Wraps calls to listMinaSshdServices with an account ID.
 *
 * @param requestId  the request ID for the request
 * @param accountId  the account ID
 * @param serviceIds the minasshd services to list. if null or empty then all minasshd services will be listed
 * @return the list of minasshd services
 */
public List<MinaSshdService> listMinaSshdServices(String requestId, String accountId, List<String> serviceIds) throws CcmException {
    checkNotNull(requestId);
    checkNotNull(accountId);

    List<MinaSshdService> groups = new ArrayList<>();

    MinaSshdManagementBlockingStub minaSshdManagementBlockingStub = newStub(requestId);

    ListMinaSshdServicesRequest.Builder requestBuilder = ListMinaSshdServicesRequest.newBuilder()
            .setAccountId(accountId)
            .setPageSize(minaSshdManagementClientConfig.getListMinaSshdServicesPageSize());

    if (serviceIds != null && !serviceIds.isEmpty()) {
        requestBuilder.addAllId(serviceIds);
    }

    ListMinaSshdServicesResponse response;
    do {
        try {
            LOGGER.debug("Calling listMinaSshdServices with requestId: {}, accountId: {}, serviceIds: [{}]",
                    requestId, accountId, serviceIds);
            response = minaSshdManagementBlockingStub.listMinaSshdServices(requestBuilder.build());
            if (response == null) {
                throw new CcmException("Got null response from MinaSshdManagementService listMinaSshdServices gRPC call", false);
            } else {
                List<MinaSshdService> minaSshdServices = response.getMinaSshdServiceList();
                if (minaSshdServices == null) {
                    throw new CcmException("Got null minasshd services in MinaSshdManagementService listMinaSshdServices gRPC response", false);
                } else {
                    groups.addAll(minaSshdServices);
                }
            }
        } catch (StatusRuntimeException e) {
            String message = "MinaSshdManagementService listMinaSshdServices gRPC call failed: " + e.getMessage();
            Status status = e.getStatus();
            Status.Code code = status.getCode();
            boolean retryable = GrpcUtil.isRetryable(code);
            LOGGER.debug("Got status code: {}, retryable: {}", code, retryable);
            throw new CcmException(message, e, retryable);
        }
        requestBuilder.setPageToken(response.getNextPageToken());
    } while (response.hasNextPageToken());

    return groups;
}
 
Example 17
Source File: GrpcAssertions.java    From grpc-spring-boot-starter with MIT License 4 votes vote down vote up
public static Status assertStatus(final Status.Code code, final StatusRuntimeException exception) {
    final Status status = exception.getStatus();
    assertEquals(code, status.getCode());
    return status;
}
 
Example 18
Source File: GrpcAssertions.java    From grpc-spring-boot-starter with MIT License 4 votes vote down vote up
public static Status assertStatus(final Status.Code code, final StatusRuntimeException exception) {
    final Status status = exception.getStatus();
    assertEquals(code, status.getCode());
    return status;
}
 
Example 19
Source File: FailoverUtils.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
/**
 * 根据nameResolver获取对应的服务提供者Id
 *
 * @return 返回服务提供者Id,以IP:port的形式表示
 * @author sxp
 * @since 2018-6-25
 * @since 2019-11-19 modify by sxp 将获取host:port的代码独立为方法
 */
static String getProviderId(Channel channel, Exception e) {
  // 先尝试从Exception中获取出错的服务端地址
  /*
  io.grpc.StatusRuntimeException: UNAVAILABLE: io exception
    at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:414)
    ...
  Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: /192.168.106.3:50062
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    ...
  */
  if (e != null && (e instanceof StatusRuntimeException)) {
    StatusRuntimeException statusException = (StatusRuntimeException) e;
    Status status = statusException.getStatus();
    if (Status.Code.UNAVAILABLE.equals(status.getCode())) {
      String errorMsg = ExceptionUtils.getExceptionStackMsg(e);
      if (StringUtils.isNotEmpty(errorMsg)) {
        int startIndex = errorMsg.indexOf("Connection refused: no further information");
        if (startIndex >= 0) {
          int endIndex = errorMsg.indexOf("\n", startIndex);
          if (endIndex >= 0) {
            String message = errorMsg.substring(startIndex, endIndex);
            // 提取出IP:port
            String ipAndPort = IpPortUtils.getAddress(message);
            if (StringUtils.isNotEmpty(ipAndPort)) {
              return ipAndPort;
            }
          }
        }
      }
    }
  }

  if (channel == null) {
    return null;
  }

  LoadBalancer loadBalancer = channel.getLoadBalancer();
  if (loadBalancer == null) {
    return null;
  }

  EquivalentAddressGroup addressGroup = loadBalancer.getAddresses();
  if (addressGroup == null) {
    return null;
  }

  List<SocketAddress> addrs = addressGroup.getAddrs();
  if (addrs == null || addrs.size() == 0) {
    return null;
  }

  SocketAddress address = addrs.get(0);

  String providerId = Networks.getHostAndPort(address);

  return providerId;
}