/**** help method *****/ private void notifyLoadBalance(GrpcURL subscribeUrl, List<GrpcURL> urls) { if (urls != null && !urls.isEmpty()) { List<EquivalentAddressGroup> servers = Lists.newArrayList(); List<SocketAddress> addresses = Lists.newArrayList(); Map<List<SocketAddress>, GrpcURL> addressUrlMapping = Maps.newHashMap(); for (GrpcURL url : urls) { String host = url.getHost(); int port = url.getPort(); List<SocketAddress> hostAddressMapping; if (NetUtils.isIP(host)) { hostAddressMapping = IpResolved(servers, addresses, host, port); } else { hostAddressMapping = DnsResolved(servers, addresses, host, port); } addressUrlMapping.put(hostAddressMapping, url); } this.addresses.put(subscribeUrl, addresses); Attributes config = this.buildAttributes(subscribeUrl, addressUrlMapping); GrpcNameResolver.this.listener.onAddresses(servers, config); } else { GrpcNameResolver.this.listener .onError(Status.NOT_FOUND.withDescription("There is no service registy in consul ")); } }
private List<SocketAddress> DnsResolved(List<EquivalentAddressGroup> servers, List<SocketAddress> addresses, String host, int port) { List<SocketAddress> hostAddressMapping = Lists.newArrayList(); try { InetAddress[] inetAddrs = InetAddress.getAllByName(host); for (int j = 0; j < inetAddrs.length; j++) { InetAddress inetAddr = inetAddrs[j]; SocketAddress sock = new InetSocketAddress(inetAddr, port); hostAddressMapping.add(sock); addSocketAddress(servers, addresses, sock); } return hostAddressMapping; } catch (UnknownHostException e) { GrpcNameResolver.this.listener.onError(Status.UNAVAILABLE.withCause(e)); } return hostAddressMapping; }
@Override public void failPlease(FailWithProbabilityOrSucceedEchoRequest request, StreamObserver<EchoResponse> responseObserver) { EchoRequest echoRequest = request.getEchoRequest(); int failProbability = request.getFailProbability(); Preconditions.checkArgument(failProbability >= 0 && failProbability <= 100, "fail probability not [" + failProbability + "] not in range [0, 100] inclusive"); logger.info("fail please - p(" + failProbability + " / 100)" + " echo: " + echoRequest.getEcho() + " with " + "repetitions: " + echoRequest.getRepeatEcho() + " received at " + DATE_FORMAT.format(new Date(System.currentTimeMillis()))); int randomFail = RANDOM.nextInt(100); if (randomFail < failProbability) { Status status = Status.INTERNAL; status = status.withCause(new FailPleaseException("Looks like you hit jackpot - we failed!")); responseObserver.onError(status.asRuntimeException()); } else { responseObserver.onNext(buildEchoResponseFromEchoRequest(echoRequest)); responseObserver.onCompleted(); } }
@Test public void statusExceptionTriggersHandler() { ClientResponseObserver<Object, Object> delegate = mock(ClientResponseObserver.class); final AtomicBoolean called = new AtomicBoolean(false); CancellableStreamObserver<Object, Object> observer = new CancellableStreamObserver<Object, Object>(delegate, new Runnable() { @Override public void run() { called.set(true); } }); observer.onError(Status.CANCELLED.asException()); assertThat(called.get()).isTrue(); }
@Test public void statusRuntimeExceptionTriggersHandler() { ClientResponseObserver<Object, Object> delegate = mock(ClientResponseObserver.class); final AtomicBoolean called = new AtomicBoolean(false); CancellableStreamObserver<Object, Object> observer = new CancellableStreamObserver<Object, Object>(delegate, new Runnable() { @Override public void run() { called.set(true); } }); observer.onError(Status.CANCELLED.asRuntimeException()); assertThat(called.get()).isTrue(); }
@Test public void otherExceptionDoesNotTriggersHandler() { ClientResponseObserver<Object, Object> delegate = mock(ClientResponseObserver.class); final AtomicBoolean called = new AtomicBoolean(false); CancellableStreamObserver<Object, Object> observer = new CancellableStreamObserver<Object, Object>(delegate, new Runnable() { @Override public void run() { called.set(true); } }); observer.onError(Status.INTERNAL.asRuntimeException()); assertThat(called.get()).isFalse(); }
@Override public Mono<JWTToken> authenticate(Mono<Login> request) { return request .map( login -> { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword()); try { Authentication authentication = this.authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); return tokenProvider.createToken(authentication, login.getRememberMe()); } catch (AuthenticationException ae) { log.trace("Authentication exception", ae); throw Status.UNAUTHENTICATED.asRuntimeException(); } }) .map(jwt -> JWTToken.newBuilder().setIdToken(jwt).build()); }
private void statusError(Status status, Metadata trailers) { if (enabledRetry) { final NameResolverNotify nameResolverNotify = this.createNameResolverNotify(); boolean retryHaveDone = this.retryHaveDone(); if (retryHaveDone) { completionFuture.setException(status.asRuntimeException(trailers)); } else { nameResolverNotify.refreshChannel(); scheduleRetryService.execute(this); SocketAddress remoteAddress = (SocketAddress) callOptions.getOption(GrpcCallOptions.CALLOPTIONS_CUSTOME_KEY) .get(GrpcCallOptions.GRPC_CURRENT_ADDR_KEY); logger.error(String.format("Retrying failed call. Failure #%d,Failure Server: %s", currentRetries.get(), String.valueOf(remoteAddress))); currentRetries.getAndIncrement(); } } else { completionFuture.setException(status.asRuntimeException(trailers)); } }
@Override public StreamObserver<Message> invoke(StreamObserver<Message> responseObserver) { try { this.remote = RpcContext.getContext().getAttachment(Constants.REMOTE_ADDRESS); Class<?> requestType = grpcMethodType.requestType(); PoJo2ProtoStreamObserver servserResponseObserver = PoJo2ProtoStreamObserver.newObserverWrap(responseObserver); Object result = method.invoke(serviceToInvoke, servserResponseObserver); return Proto2PoJoStreamObserver.newObserverWrap((StreamObserver<Object>) result, requestType); } catch (Throwable e) { String stackTrace = ThrowableUtil.stackTraceToString(e); log.error(e.getMessage(), e); StatusRuntimeException statusException = Status.UNAVAILABLE.withDescription(stackTrace).asRuntimeException(); responseObserver.onError(statusException); } finally { log.debug(String.format("Service: %s Method: %s RemoteAddress: %s", providerUrl.getServiceInterface(), method.getName(), this.remote)); } return null; }
private void streamCall(Message request, StreamObserver<Message> responseObserver) { try { Class<?> requestType = grpcMethodType.requestType(); Object reqPojo = SerializerUtil.protobuf2Pojo(request, requestType); Object[] requestParams = new Object[] {reqPojo, PoJo2ProtoStreamObserver.newObserverWrap(responseObserver)}; method.invoke(serviceToInvoke, requestParams); } catch (Throwable e) { String stackTrace = ThrowableUtil.stackTraceToString(e); log.error(e.getMessage(), e); StatusRuntimeException statusException = Status.UNAVAILABLE.withDescription(stackTrace).asRuntimeException(); responseObserver.onError(statusException); } finally { log.debug(String.format("Service: %s Method: %s RemoteAddress: %s", providerUrl.getServiceInterface(), method.getName(), this.remote)); } }
@Test public void testFailingResolution() throws Exception { new Expectations() {{ catalogClient.getCatalogService(SERVICE_NAME, QueryParams.DEFAULT); result = new RuntimeException(); maxTimes = 5; }}; final List<NameResolverEvent<?>> events = runTest(resolver, 5); // allow for an off by 1 assertTrue(events.size() >= 4); assertTrue(events.size() <= 5); for (final NameResolverEvent<?> event : events) { assertEquals(NameResolverEventType.ON_ERROR, event.type); final Status s = (Status) event.payload; assertEquals(Status.UNAVAILABLE.getCode(), s.getCode()); assertTrue(s.getCause() instanceof RuntimeException); } }
@Override public void publish(@NonNull MSG_Facts request, @NonNull StreamObserver<MSG_Empty> responseObserver) { List<Fact> facts = request.getFactList().stream().map(converter::fromProto).collect( Collectors.toList()); final int size = facts.size(); log.debug("publish {} fact{}", size, size > 1 ? "s" : ""); log.trace("publish {}", facts); try { log.trace("store publish {}", facts); store.publish(facts); log.trace("store publish done"); responseObserver.onNext(MSG_Empty.getDefaultInstance()); responseObserver.onCompleted(); } catch (Throwable e) { log.error("Problem while publishing: ", e); responseObserver.onError(new StatusRuntimeException(Status.INTERNAL.withDescription(e .getMessage()))); } }
@Test public void getAllAuthoritiesRejected() throws Exception { Authentication authentication = new UsernamePasswordAuthenticationToken( DEFAULT_EMAIL, DEFAULT_PASSWORD, Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) ); SecurityContextHolder.getContext().setAuthentication(authentication); try { List<String> roles = new ArrayList<>(); stub.getAllAuthorities(Empty.getDefaultInstance()).forEachRemaining(role -> roles.add(role.getValue())); failBecauseExceptionWasNotThrown(StatusRuntimeException.class); } catch (StatusRuntimeException e){ assertThat(e.getStatus().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); } }
@Override public void rawGet( com.pingcap.tikv.kvproto.Kvrpcpb.RawGetRequest request, io.grpc.stub.StreamObserver<com.pingcap.tikv.kvproto.Kvrpcpb.RawGetResponse> responseObserver) { try { verifyContext(request.getContext()); ByteString key = request.getKey(); Kvrpcpb.RawGetResponse.Builder builder = Kvrpcpb.RawGetResponse.newBuilder(); Integer errorCode = errorMap.remove(key); Errorpb.Error.Builder errBuilder = Errorpb.Error.newBuilder(); if (errorCode != null) { setErrorInfo(errorCode, errBuilder); builder.setRegionError(errBuilder.build()); } else { builder.setValue(dataMap.get(Comparables.wrap(key))); } responseObserver.onNext(builder.build()); responseObserver.onCompleted(); } catch (Exception e) { responseObserver.onError(Status.INTERNAL.asRuntimeException()); } }
/** */ public void rawPut( com.pingcap.tikv.kvproto.Kvrpcpb.RawPutRequest request, io.grpc.stub.StreamObserver<com.pingcap.tikv.kvproto.Kvrpcpb.RawPutResponse> responseObserver) { try { verifyContext(request.getContext()); ByteString key = request.getKey(); Kvrpcpb.RawPutResponse.Builder builder = Kvrpcpb.RawPutResponse.newBuilder(); Integer errorCode = errorMap.get(key); Errorpb.Error.Builder errBuilder = Errorpb.Error.newBuilder(); if (errorCode != null) { setErrorInfo(errorCode, errBuilder); builder.setRegionError(errBuilder.build()); //builder.setError(""); } responseObserver.onNext(builder.build()); responseObserver.onCompleted(); } catch (Exception e) { responseObserver.onError(Status.INTERNAL.asRuntimeException()); } }
/** */ public void rawDelete( com.pingcap.tikv.kvproto.Kvrpcpb.RawDeleteRequest request, io.grpc.stub.StreamObserver<com.pingcap.tikv.kvproto.Kvrpcpb.RawDeleteResponse> responseObserver) { try { verifyContext(request.getContext()); ByteString key = request.getKey(); Kvrpcpb.RawDeleteResponse.Builder builder = Kvrpcpb.RawDeleteResponse.newBuilder(); Integer errorCode = errorMap.get(key); Errorpb.Error.Builder errBuilder = Errorpb.Error.newBuilder(); if (errorCode != null) { setErrorInfo(errorCode, errBuilder); builder.setRegionError(errBuilder.build()); } responseObserver.onNext(builder.build()); responseObserver.onCompleted(); } catch (Exception e) { responseObserver.onError(Status.INTERNAL.asRuntimeException()); } }
@BeforeClass public static void startServer() throws IOException { AfricasTalking.initialize(Fixtures.USERNAME, Fixtures.API_KEY); server = new Server(new Authenticator() { @Override public boolean authenticate(String client) { return client.compareToIgnoreCase(TEST_CLIENT_ID) == 0; } }); server.addSipCredentials("test", "secret", "sip://at.dev"); server.start(certFile, privateKeyFile, TEST_PORT); ManagedChannel ch = NettyChannelBuilder.forAddress("localhost", TEST_PORT) .sslContext(GrpcSslContexts.forClient().trustManager(certFile).build()) .build(); client = SdkServerServiceGrpc.newBlockingStub(ch) .withCallCredentials(new CallCredentials(){ @Override public void applyRequestMetadata(MethodDescriptor<?, ?> method, Attributes attrs, Executor appExecutor, final MetadataApplier applier) { appExecutor.execute(new Runnable(){ @Override public void run() { try { Metadata headers = new Metadata(); Metadata.Key<String> clientIdKey = Metadata.Key.of("X-Client-Id", Metadata.ASCII_STRING_MARSHALLER); headers.put(clientIdKey, TEST_CLIENT_ID); applier.apply(headers); } catch(Throwable ex) { applier.fail(Status.UNAUTHENTICATED.withCause(ex)); } } }); } }); }
@Override public void getActionResult( GetActionResultRequest request, StreamObserver<ActionResult> responseObserver) { Instance instance; try { instance = instances.get(request.getInstanceName()); } catch (InstanceNotFoundException ex) { responseObserver.onError(BuildFarmInstances.toStatusException(ex)); return; } ActionResult actionResult = instance.getActionResult(request.getActionDigest()); if (actionResult == null) { responseObserver.onError(new StatusException(Status.NOT_FOUND)); return; } responseObserver.onNext(actionResult); responseObserver.onCompleted(); }
@Override public void put( Operation operation, StreamObserver<com.google.rpc.Status> responseObserver) { Instance instance; try { instance = instances.getFromOperationName(operation.getName()); } catch (InstanceNotFoundException ex) { responseObserver.onError(BuildFarmInstances.toStatusException(ex)); return; } boolean ok = instance.putOperation(operation); Code code = ok ? Code.OK : Code.UNAVAILABLE; responseObserver.onNext(com.google.rpc.Status.newBuilder() .setCode(code.getNumber()) .build()); responseObserver.onCompleted(); }
@Override public void poll( PollOperationRequest request, StreamObserver<com.google.rpc.Status> responseObserver) { Instance instance; try { instance = instances.getFromOperationName( request.getOperationName()); } catch (InstanceNotFoundException ex) { responseObserver.onError(BuildFarmInstances.toStatusException(ex)); return; } boolean ok = instance.pollOperation( request.getOperationName(), request.getStage()); Code code = ok ? Code.OK : Code.UNAVAILABLE; responseObserver.onNext(com.google.rpc.Status.newBuilder() .setCode(code.getNumber()) .build()); responseObserver.onCompleted(); }
/** * Receives a terminating error from the stream. * <p> * <p>May only be called once and if called it must be the last method called. In particular if an * exception is thrown by an implementation of {@code onError} no further calls to any method are * allowed. * <p> * <p>{@code t} should be a {@link StatusException} or {@link * StatusRuntimeException}, but other {@code Throwable} types are possible. Callers should * generally convert from a {@link Status} via {@link Status#asException()} or * {@link Status#asRuntimeException()}. Implementations should generally convert to a * {@code Status} via {@link Status#fromThrowable(Throwable)}. * * @param throwable the error occurred on the stream */ @Override public void onError(final Throwable throwable) { if (DEBUG) { MyLog.w(CLS_NAME, "onError"); throwable.printStackTrace(); final Status status = Status.fromThrowable(throwable); MyLog.w(CLS_NAME, "onError: " + status.toString()); } if (doError.get()) { doError.set(false); stopListening(); listener.onError(SpeechRecognizer.ERROR_NETWORK); } }
@Override public int drainTo(OutputStream target) throws IOException { int written = 0; if (message != null) { try { byte[] bytes = serializer.serialize(message); written = bytes.length; target.write(bytes); message = null; } catch (TException e) { throw Status.INTERNAL.withDescription("failed to serialize thrift message") .withCause(e).asRuntimeException(); } } else if (partial != null) { written = (int) ByteStreams.copy(partial, target); partial = null; } else { written = 0; } return written; }
@Override public int read() throws IOException { if (message != null) { try { partial = new ByteArrayInputStream(serializer.serialize(message)); message = null; } catch (TException e) { throw Status.INTERNAL.withDescription("failed to serialize thrift message") .withCause(e).asRuntimeException(); } } if (partial != null) { return partial.read(); } return -1; }
@Override public int available() throws IOException { if (message != null) { try { partial = new ByteArrayInputStream(serializer.serialize(message)); message = null; return partial.available(); } catch (TException e) { throw Status.INTERNAL.withDescription("failed to serialize thrift message") .withCause(e).asRuntimeException(); } } else if (partial != null) { return partial.available(); } return 0; }
@Override public Mono<UserProto> updateUser(Mono<UserProto> request) { return request .doOnSuccess(userProto -> log.debug("gRPC request to update User : {}", userProto)) .filter(userProto -> !userRepository .findOneByEmailIgnoreCase(userProto.getEmail()) .map(User::getId) .filter(id -> !id.equals(userProto.getId())) .isPresent() ) .switchIfEmpty(Mono.error(Status.ALREADY_EXISTS.withDescription("Email already in use").asRuntimeException())) .filter(userProto -> !userRepository .findOneByLogin(userProto.getLogin().toLowerCase()) .map(User::getId) .filter(id -> !id.equals(userProto.getId())) .isPresent() ) .switchIfEmpty(Mono.error(Status.ALREADY_EXISTS.withDescription("Login already in use").asRuntimeException())) .map(userProtoMapper::userProtoToUserDTO) .map(user -> userService.updateUser(user).orElseThrow(Status.NOT_FOUND::asRuntimeException)) .map(userProtoMapper::userDTOToUserProto); }
private static Throwable prepareError(Throwable throwable) { if (throwable instanceof StatusException || throwable instanceof StatusRuntimeException) { return throwable; } else { return Status.fromThrowable(throwable).asException(); } }
@Override public void onError(Throwable t) { if (t instanceof StatusException) { if (((StatusException) t).getStatus().getCode() == Status.Code.CANCELLED) { onCanceledHandler.run(); } } if (t instanceof StatusRuntimeException) { if (((StatusRuntimeException) t).getStatus().getCode() == Status.Code.CANCELLED) { onCanceledHandler.run(); } } delegate.onError(t); }
public Publisher<TResponse> getRxConsumer() { try { beforeStartCalled.await(); } catch (InterruptedException e) { throw Status.INTERNAL.withCause(e).asRuntimeException(); } return rxConsumer; }
@Override public void onNext(Object value) { try { Object respPojo = value; Message respProtoBufer = SerializerUtil.pojo2Protobuf(respPojo); streamObserver.onNext(respProtoBufer); } catch (ProtobufException e) { String stackTrace = ThrowableUtil.stackTraceToString(e); StatusRuntimeException statusException = Status.UNAVAILABLE.withDescription(stackTrace).asRuntimeException(); streamObserver.onError(statusException); } }
@Test public void testFinishPasswordResetPasswordTooSmall() { try { stub.finishPasswordReset(KeyAndPassword.newBuilder() .setNewPassword("foo") .setKey("reset key").build() ); failBecauseExceptionWasNotThrown(StatusRuntimeException.class); } catch (StatusRuntimeException e) { assertThat(e.getStatus().getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); } }
@Override public void onMessage(Response message) { if (firstResponseReceived && !streamingResponse) { throw Status.INTERNAL .withDescription("More than one responses received for unary or client-streaming call") .asRuntimeException(); } firstResponseReceived = true; observer.onNext(message); if (streamingResponse && adapter.isAutoFlowControlEnabled()) { adapter.request(1); } }
@Override public void onClose(Status status, Metadata trailers) { if (status.isOk()) { observer.onCompleted(); } else { observer.onError(status.asRuntimeException(trailers)); } }
@Override public void onMessage(Response message) { if (this.response != null && !enabledRetry) { throw Status.INTERNAL.withDescription("More than one value received for unary call") .asRuntimeException(); } this.response = message; }
@Override public void onClose(Status status, Metadata trailers) { try { SocketAddress remoteServer = clientCall.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR); callOptions.getOption(GrpcCallOptions.CALLOPTIONS_CUSTOME_KEY) .put(GrpcCallOptions.GRPC_CURRENT_ADDR_KEY, remoteServer); } finally { if (status.isOk()) { statusOk(trailers); } else { statusError(status, trailers); } } }
/** * If all subchannels are TRANSIENT_FAILURE, return the Status associated with an arbitrary * subchannel otherwise, return null. */ @Nullable private Status getAggregatedError() { Status status = null; for (Subchannel subchannel : getSubchannels()) { ConnectivityStateInfo stateInfo = getSubchannelStateInfoRef(subchannel).get(); if (stateInfo.getState() != TRANSIENT_FAILURE) { return null; } status = stateInfo.getStatus(); } return status; }
@Override @PreAuthorize("hasRole('USER')") public void fibonacci(FibonacciRequest request, StreamObserver<FibonacciResponse> responseObserver) { if (request.getValue() < 0) { responseObserver.onError(Status.INVALID_ARGUMENT.withDescription("Number cannot be negative").asRuntimeException()); return; } FibonacciResponse response = FibonacciResponse.newBuilder() .setValue(numberService.fibonacci(request.getValue())) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); }
@Override @PreAuthorize("hasRole('VIEWER')") public void factorial(FactorialRequest request, StreamObserver<FactorialResponse> responseObserver) { if (request.getValue() < 0) { responseObserver.onError(Status.INVALID_ARGUMENT.withDescription("Number cannot be negative").asRuntimeException()); return; } FactorialResponse response = FactorialResponse.newBuilder() .setValue(numberService.factorial(request.getValue())) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); }
private URI removePort(URI uri) throws StatusException { try { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), -1 /* port */, uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw Status.UNAUTHENTICATED .withDescription("Unable to construct service URI after removing port") .withCause(e).asException(); } }