Java Code Examples for io.grpc.Status#OK

The following examples show how to use io.grpc.Status#OK . 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: RoundRobinLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void internalPickerComparisons() {
  EmptyPicker emptyOk1 = new EmptyPicker(Status.OK);
  EmptyPicker emptyOk2 = new EmptyPicker(Status.OK.withDescription("different OK"));
  EmptyPicker emptyErr = new EmptyPicker(Status.UNKNOWN.withDescription("¯\\_(ツ)_//¯"));

  Iterator<Subchannel> subchannelIterator = subchannels.values().iterator();
  Subchannel sc1 = subchannelIterator.next();
  Subchannel sc2 = subchannelIterator.next();
  StickinessState stickinessState = new StickinessState("stick-key");
  ReadyPicker ready1 = new ReadyPicker(Arrays.asList(sc1, sc2), 0, null);
  ReadyPicker ready2 = new ReadyPicker(Arrays.asList(sc1), 0, null);
  ReadyPicker ready3 = new ReadyPicker(Arrays.asList(sc2, sc1), 1, null);
  ReadyPicker ready4 = new ReadyPicker(Arrays.asList(sc1, sc2), 1, stickinessState);
  ReadyPicker ready5 = new ReadyPicker(Arrays.asList(sc2, sc1), 0, stickinessState);

  assertTrue(emptyOk1.isEquivalentTo(emptyOk2));
  assertFalse(emptyOk1.isEquivalentTo(emptyErr));
  assertFalse(ready1.isEquivalentTo(ready2));
  assertTrue(ready1.isEquivalentTo(ready3));
  assertFalse(ready3.isEquivalentTo(ready4));
  assertTrue(ready4.isEquivalentTo(ready5));
  assertFalse(emptyOk1.isEquivalentTo(ready1));
  assertFalse(ready1.isEquivalentTo(emptyOk1));
}
 
Example 2
Source File: ClientCallsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void unaryBlockingCallSuccess() throws Exception {
  Integer req = 2;
  final String resp = "bar";
  final Status status = Status.OK;
  final Metadata trailers = new Metadata();

  NoopClientCall<Integer, String> call = new NoopClientCall<Integer, String>() {
    @Override
    public void start(ClientCall.Listener<String> listener, Metadata headers) {
      listener.onMessage(resp);
      listener.onClose(status, trailers);
    }
  };

  String actualResponse = ClientCalls.blockingUnaryCall(call, req);
  assertEquals(resp, actualResponse);
}
 
Example 3
Source File: GrpcRetryInterceptorTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoRetryOnOk() throws IOException {
  String uniqueName = InProcessServerBuilder.generateName();
  ExecutionImpl service = new ExecutionImpl(Status.OK, 0);
  InProcessServerBuilder.forName(uniqueName).addService(service).build().start();
  CallCounter beforeRetry = new CallCounter();
  ManagedChannel channel =
      InProcessChannelBuilder.forName(uniqueName)
          .intercept(
              new RetryClientInterceptor(
                  RetryPolicy.builder().setMaxRetries(2).setBeforeRetry(beforeRetry).build()))
          .build();
  ExecutionBlockingStub stub = ExecutionGrpc.newBlockingStub(channel);
  stub.execute(ExecuteRequest.newBuilder().build()).forEachRemaining(resp -> {});

  Assert.assertEquals(1, service.calls);
  Assert.assertEquals(0, beforeRetry.calls);
}
 
Example 4
Source File: ClientCallsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void unaryBlockingCallSuccess() throws Exception {
  Integer req = 2;
  final String resp = "bar";
  final Status status = Status.OK;
  final Metadata trailers = new Metadata();

  NoopClientCall<Integer, String> call = new NoopClientCall<Integer, String>() {
    @Override
    public void start(ClientCall.Listener<String> listener, Metadata headers) {
      listener.onMessage(resp);
      listener.onClose(status, trailers);
    }
  };

  String actualResponse = ClientCalls.blockingUnaryCall(call, req);
  assertEquals(resp, actualResponse);
}
 
Example 5
Source File: RoundRobinLoadBalancerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void internalPickerComparisons() {
  EmptyPicker emptyOk1 = new EmptyPicker(Status.OK);
  EmptyPicker emptyOk2 = new EmptyPicker(Status.OK.withDescription("different OK"));
  EmptyPicker emptyErr = new EmptyPicker(Status.UNKNOWN.withDescription("¯\\_(ツ)_//¯"));

  Iterator<Subchannel> subchannelIterator = subchannels.values().iterator();
  Subchannel sc1 = subchannelIterator.next();
  Subchannel sc2 = subchannelIterator.next();
  ReadyPicker ready1 = new ReadyPicker(Arrays.asList(sc1, sc2), 0);
  ReadyPicker ready2 = new ReadyPicker(Arrays.asList(sc1), 0);
  ReadyPicker ready3 = new ReadyPicker(Arrays.asList(sc2, sc1), 1);
  ReadyPicker ready4 = new ReadyPicker(Arrays.asList(sc1, sc2), 1);
  ReadyPicker ready5 = new ReadyPicker(Arrays.asList(sc2, sc1), 0);

  assertTrue(emptyOk1.isEquivalentTo(emptyOk2));
  assertFalse(emptyOk1.isEquivalentTo(emptyErr));
  assertFalse(ready1.isEquivalentTo(ready2));
  assertTrue(ready1.isEquivalentTo(ready3));
  assertTrue(ready3.isEquivalentTo(ready4));
  assertTrue(ready4.isEquivalentTo(ready5));
  assertFalse(emptyOk1.isEquivalentTo(ready1));
  assertFalse(ready1.isEquivalentTo(emptyOk1));
}
 
Example 6
Source File: OcAgentTraceServiceConfigRpcHandler.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
synchronized void onComplete(@javax.annotation.Nullable Throwable error) {
  if (isCompleted()) {
    return;
  }
  currentConfigObserver = null;
  // TODO(songya): add Runnable
  Status status;
  if (error == null) {
    status = Status.OK;
  } else if (error instanceof StatusRuntimeException) {
    status = ((StatusRuntimeException) error).getStatus();
  } else {
    status = Status.UNKNOWN;
  }
  terminateStatus = status;
}
 
Example 7
Source File: ComputeEngineChannelBuilder.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private ComputeEngineChannelBuilder(String target) {
  delegate = NettyChannelBuilder.forTarget(target);
  SslContext sslContext;
  try {
    sslContext = GrpcSslContexts.forClient().build();
  } catch (SSLException e) {
    throw new RuntimeException(e);
  }
  InternalNettyChannelBuilder.setProtocolNegotiatorFactory(
      delegate(),
      new GoogleDefaultProtocolNegotiatorFactory(
          /* targetServiceAccounts= */ ImmutableList.<String>of(),
          SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL),
          sslContext));
  CallCredentials credentials = MoreCallCredentials.from(ComputeEngineCredentials.create());
  Status status = Status.OK;
  if (!CheckGcpEnvironment.isOnGcp()) {
    status =
        Status.INTERNAL.withDescription(
            "Compute Engine Credentials can only be used on Google Cloud Platform");
  }
  delegate().intercept(new CallCredentialsInterceptor(credentials, status));
}
 
Example 8
Source File: JwtServerInterceptor.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall,
    Metadata metadata, ServerCallHandler<ReqT, RespT> serverCallHandler) {
  String value = metadata.get(Constant.AUTHORIZATION_METADATA_KEY);

  Status status = Status.OK;
  if (value == null) {
    status = Status.UNAUTHENTICATED.withDescription("Authorization token is missing");
  } else if (!value.startsWith(Constant.BEARER_TYPE)) {
    status = Status.UNAUTHENTICATED.withDescription("Unknown authorization type");
  } else {
    Jws<Claims> claims = null;
    // remove authorization type prefix
    String token = value.substring(Constant.BEARER_TYPE.length()).trim();
    try {
      // verify token signature and parse claims
      claims = parser.parseClaimsJws(token);
    } catch (JwtException e) {
      status = Status.UNAUTHENTICATED.withDescription(e.getMessage()).withCause(e);
    }
    if (claims != null) {
      // set client id into current context
      Context ctx = Context.current()
          .withValue(Constant.CLIENT_ID_CONTEXT_KEY, claims.getBody().getSubject());
      return Contexts.interceptCall(ctx, serverCall, metadata, serverCallHandler);
    }
  }

  serverCall.close(status, new Metadata());
  return new ServerCall.Listener<ReqT>() {
    // noop
  };
}
 
Example 9
Source File: AuthorizationUtil.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Given a server call, performs client authorization check, i.e., checks if the client service
 * account matches one of the expected service accounts. It returns OK if client is authorized and
 * an error otherwise.
 */
public static Status clientAuthorizationCheck(
    ServerCall<?, ?> call, Collection<String> expectedServiceAccounts) {
  AltsAuthContext altsContext =
      (AltsAuthContext) call.getAttributes().get(AltsProtocolNegotiator.AUTH_CONTEXT_KEY);
  if (altsContext == null) {
    return Status.PERMISSION_DENIED.withDescription("Peer ALTS AuthContext not found");
  }
  if (expectedServiceAccounts.contains(altsContext.getPeerServiceAccount())) {
    return Status.OK;
  }
  return Status.PERMISSION_DENIED.withDescription(
      "Client " + altsContext.getPeerServiceAccount() + " is not authorized");
}
 
Example 10
Source File: GoogleDefaultChannelBuilder.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public ManagedChannel build() {
  @Nullable CallCredentials credentials = null;
  Status status = Status.OK;
  try {
    credentials = MoreCallCredentials.from(GoogleCredentials.getApplicationDefault());
  } catch (IOException e) {
    status =
        Status.UNAUTHENTICATED
            .withDescription("Failed to get Google default credentials")
            .withCause(e);
  }
  return delegate().intercept(new GoogleDefaultInterceptor(credentials, status)).build();
}
 
Example 11
Source File: GrpcRequestHandler.java    From xio with Apache License 2.0 5 votes vote down vote up
private void sendResponse(
    ChannelHandlerContext ctx, int streamId, ByteBuf grpcResponseBuffer, Status status) {
  Headers headers =
      new DefaultHeaders().set(HttpHeaderNames.CONTENT_TYPE, GRPC_CONTENT_TYPE_VALUE);
  DefaultSegmentedResponse segmentedResponse =
      DefaultSegmentedResponse.builder()
          .streamId(streamId)
          .status(HttpResponseStatus.OK)
          .headers(headers)
          .build();

  ctx.writeAndFlush(segmentedResponse);

  Headers trailingHeaders =
      new DefaultHeaders()
          .set(GRPC_TRAILING_HEADER_STATUS_KEY, Integer.toString(status.getCode().value()));

  if (status.getDescription() != null) {
    trailingHeaders.add(
        GRPC_TRAILING_HEADER_MESSAGE_KEY, grpcEncodedString(status.getDescription()));
  }

  DefaultSegmentedData data =
      DefaultSegmentedData.builder()
          .streamId(streamId)
          .content(grpcResponseBuffer)
          .trailingHeaders(trailingHeaders)
          .endOfMessage(true)
          .build();

  ctx.writeAndFlush(data);

  HashMap<Integer, GrpcState> session = lazyCreateSession(ctx);
  session.remove(streamId);

  if (status != Status.OK) {
    ctx.close();
  }
}
 
Example 12
Source File: OcAgentTraceServiceExportRpcHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
synchronized void onComplete(@javax.annotation.Nullable Throwable error) {
  if (isCompleted()) {
    return;
  }
  // TODO(songya): add Runnable
  Status status;
  if (error == null) {
    status = Status.OK;
  } else if (error instanceof StatusRuntimeException) {
    status = ((StatusRuntimeException) error).getStatus();
  } else {
    status = Status.UNKNOWN;
  }
  terminateStatus = status;
}
 
Example 13
Source File: OcAgentMetricsServiceExportRpcHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
synchronized void onComplete(@javax.annotation.Nullable Throwable error) {
  if (isCompleted()) {
    return;
  }
  // TODO(songya): add Runnable
  Status status;
  if (error == null) {
    status = Status.OK;
  } else if (error instanceof StatusRuntimeException) {
    status = ((StatusRuntimeException) error).getStatus();
  } else {
    status = Status.UNKNOWN;
  }
  terminateStatus = status;
}
 
Example 14
Source File: GrpcTagsTest.java    From java-grpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatusOk() {
  final Status status = Status.OK;
  MockSpan span = new MockTracer().buildSpan("").start();
  GrpcTags.GRPC_STATUS.set(span, status);
  assertThat(span.tags())
      .containsExactly(MapEntry.entry(GrpcTags.GRPC_STATUS.getKey(), status.getCode().name()));
}
 
Example 15
Source File: LocalFallbackStrategy.java    From buck with Apache License 2.0 4 votes vote down vote up
private void handleRemoteBuildFailedWithException(Throwable t) {
  remoteBuildResult =
      Optional.of(t instanceof InterruptedException ? Result.INTERRUPTED : Result.EXCEPTION);
  if (t instanceof StepFailedException) {
    StepFailedException exc = (StepFailedException) t;
    exitCode = exc.getExitCode();
    remoteExecutionMetadata = exc.getRemoteExecutionMetadata();
    if (remoteExecutionMetadata.isPresent()) {
      if (remoteExecutionMetadata
          .get()
          .getExecutedActionInfo()
          .hasIsFallbackEnabledForCompletedAction()) {
        localFallbackEnabledForCompletedAction =
            remoteExecutionMetadata
                .get()
                .getExecutedActionInfo()
                .getIsFallbackEnabledForCompletedAction()
                .getValue();
      }
    }
  }
  remoteGrpcStatus = exitCode.isPresent() ? Status.OK : Status.fromThrowable(t);

  if (remoteStrategyBuildResult
      instanceof RemoteExecutionStrategy.RemoteExecutionStrategyBuildResult) {
    lastNonTerminalState =
        ((RemoteExecutionStrategy.RemoteExecutionStrategyBuildResult) remoteStrategyBuildResult)
            .getRuleContext()
            .lastNonTerminalState;
  }

  remoteBuildErrorMessage = Optional.of(t.toString());
  boolean fallbackEnabledForCurrentResult =
      localFallbackEnabled
          && (localFallbackEnabledForCompletedAction || remoteGrpcStatus != Status.OK);
  if (fallbackEnabledForCurrentResult
      && (!localFallbackDisabledOnCorruptedArtifacts
          || !(MultiThreadedBlobUploader.CorruptArtifactException.isCause(
              ThrowableCauseIterable.of(t))))) {
    LOG.warn(
        t, "Remote build failed for a build rule so trying locally now for [%s].", buildTarget);
    fallbackBuildToLocalStrategy();
  } else {
    if (remoteGrpcStatus == Status.OK) {
      eventBus.post(
          ConsoleEvent.severe(
              "The build failed trying to build remotely. This is most likely due to a missing dependency"
              ));
    }
    completeCombinedFutureWithException(t, remoteBuildResult.get(), Result.NOT_RUN);
  }
}
 
Example 16
Source File: GrpcClientResponseTest.java    From brave with Apache License 2.0 4 votes vote down vote up
@Test public void errorCode_nullWhenOk() {
  status = Status.OK;
  GrpcClientResponse response = new GrpcClientResponse(request, headers, status, trailers);

  assertThat(response.errorCode()).isNull();
}
 
Example 17
Source File: GrpcServerResponseTest.java    From brave with Apache License 2.0 4 votes vote down vote up
@Test public void errorCode_nullWhenOk() {
  status = Status.OK;
  GrpcServerResponse response = new GrpcServerResponse(request, headers, status, trailers);

  assertThat(response.errorCode()).isNull();
}