Search in sources :

Example 6 with SimpleForwardingClientCall

use of io.grpc.ForwardingClientCall.SimpleForwardingClientCall in project brave by openzipkin.

the class TracingClientInterceptor method interceptCall.

/**
 * This sets as span in scope both for the interception and for the start of the request. It does
 * not set a span in scope during the response listener as it is unexpected it would be used at
 * that fine granularity. If users want access to the span in a response listener, they will need
 * to wrap the executor with one that's aware of the current context.
 */
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method, final CallOptions callOptions, final Channel next) {
    Span span = tracer.nextSpan();
    try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
        return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {

            @Override
            public void start(Listener<RespT> responseListener, Metadata headers) {
                injector.inject(span.context(), headers);
                span.kind(Span.Kind.CLIENT).start();
                try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
                    parser.onStart(method, callOptions, headers, span.customizer());
                    super.start(new SimpleForwardingClientCallListener<RespT>(responseListener) {

                        @Override
                        public void onMessage(RespT message) {
                            try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
                                parser.onMessageReceived(message, span.customizer());
                                delegate().onMessage(message);
                            }
                        }

                        @Override
                        public void onClose(Status status, Metadata trailers) {
                            try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
                                super.onClose(status, trailers);
                                parser.onClose(status, trailers, span.customizer());
                            } finally {
                                span.finish();
                            }
                        }
                    }, headers);
                }
            }

            @Override
            public void sendMessage(ReqT message) {
                try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
                    super.sendMessage(message);
                    parser.onMessageSent(message, span.customizer());
                }
            }
        };
    } catch (RuntimeException | Error e) {
        parser.onError(e, span.customizer());
        span.finish();
        throw e;
    }
}
Also used : Status(io.grpc.Status) SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) Tracer(brave.Tracer) Metadata(io.grpc.Metadata) Span(brave.Span) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall)

Example 7 with SimpleForwardingClientCall

use of io.grpc.ForwardingClientCall.SimpleForwardingClientCall in project jetcd by coreos.

the class ClientConnectionManager method defaultChannelBuilder.

@SuppressWarnings("rawtypes")
ManagedChannelBuilder<?> defaultChannelBuilder(String target) {
    if (target == null) {
        throw new IllegalArgumentException("At least one endpoint should be provided");
    }
    final Vertx vertx = Vertx.vertx();
    final VertxChannelBuilder channelBuilder = VertxChannelBuilder.forTarget(vertx, target);
    if (builder.authority() != null) {
        channelBuilder.overrideAuthority(builder.authority());
    }
    if (builder.maxInboundMessageSize() != null) {
        channelBuilder.maxInboundMessageSize(builder.maxInboundMessageSize());
    }
    if (builder.sslContext() != null) {
        channelBuilder.nettyBuilder().negotiationType(NegotiationType.TLS);
        channelBuilder.nettyBuilder().sslContext(builder.sslContext());
    } else {
        channelBuilder.nettyBuilder().negotiationType(NegotiationType.PLAINTEXT);
    }
    if (builder.keepaliveTime() != null) {
        channelBuilder.keepAliveTime(builder.keepaliveTime().toMillis(), TimeUnit.MILLISECONDS);
    }
    if (builder.keepaliveTimeout() != null) {
        channelBuilder.keepAliveTimeout(builder.keepaliveTimeout().toMillis(), TimeUnit.MILLISECONDS);
    }
    if (builder.keepaliveWithoutCalls() != null) {
        channelBuilder.keepAliveWithoutCalls(builder.keepaliveWithoutCalls());
    }
    if (builder.connectTimeout() != null) {
        channelBuilder.nettyBuilder().withOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) builder.connectTimeout().toMillis());
    }
    if (builder.loadBalancerPolicy() != null) {
        channelBuilder.defaultLoadBalancingPolicy(builder.loadBalancerPolicy());
    } else {
        channelBuilder.defaultLoadBalancingPolicy("pick_first");
    }
    if (builder.headers() != null) {
        channelBuilder.intercept(new ClientInterceptor() {

            @Override
            public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
                return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {

                    @Override
                    public void start(Listener<RespT> responseListener, Metadata headers) {
                        builder.headers().forEach((BiConsumer<Metadata.Key, Object>) headers::put);
                        super.start(responseListener, headers);
                    }
                };
            }
        });
    }
    if (builder.interceptors() != null) {
        channelBuilder.intercept(builder.interceptors());
    }
    return channelBuilder;
}
Also used : ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) Vertx(io.vertx.core.Vertx) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall) ClientCall(io.grpc.ClientCall) ClientInterceptor(io.grpc.ClientInterceptor) VertxChannelBuilder(io.vertx.grpc.VertxChannelBuilder) BiConsumer(java.util.function.BiConsumer)

Example 8 with SimpleForwardingClientCall

use of io.grpc.ForwardingClientCall.SimpleForwardingClientCall in project grpc-java by grpc.

the class BinlogHelper method getClientInterceptor.

public ClientInterceptor getClientInterceptor(final long callId) {
    return new ClientInterceptor() {

        boolean trailersOnlyResponse = true;

        @Override
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
            final AtomicLong seq = new AtomicLong(1);
            final String methodName = method.getFullMethodName();
            final String authority = next.authority();
            // The timeout should reflect the time remaining when the call is started, so do not
            // compute remaining time here.
            final Deadline deadline = min(callOptions.getDeadline(), Context.current().getDeadline());
            return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {

                @Override
                public void start(final ClientCall.Listener<RespT> responseListener, Metadata headers) {
                    final Duration timeout = deadline == null ? null : Durations.fromNanos(deadline.timeRemaining(TimeUnit.NANOSECONDS));
                    writer.logClientHeader(seq.getAndIncrement(), methodName, authority, timeout, headers, GrpcLogEntry.Logger.LOGGER_CLIENT, callId, /*peerAddress=*/
                    null);
                    ClientCall.Listener<RespT> wListener = new SimpleForwardingClientCallListener<RespT>(responseListener) {

                        @Override
                        public void onMessage(RespT message) {
                            writer.logRpcMessage(seq.getAndIncrement(), EventType.EVENT_TYPE_SERVER_MESSAGE, method.getResponseMarshaller(), message, GrpcLogEntry.Logger.LOGGER_CLIENT, callId);
                            super.onMessage(message);
                        }

                        @Override
                        public void onHeaders(Metadata headers) {
                            trailersOnlyResponse = false;
                            writer.logServerHeader(seq.getAndIncrement(), headers, GrpcLogEntry.Logger.LOGGER_CLIENT, callId, getPeerSocket(getAttributes()));
                            super.onHeaders(headers);
                        }

                        @Override
                        public void onClose(Status status, Metadata trailers) {
                            SocketAddress peer = trailersOnlyResponse ? getPeerSocket(getAttributes()) : null;
                            writer.logTrailer(seq.getAndIncrement(), status, trailers, GrpcLogEntry.Logger.LOGGER_CLIENT, callId, peer);
                            super.onClose(status, trailers);
                        }
                    };
                    super.start(wListener, headers);
                }

                @Override
                public void sendMessage(ReqT message) {
                    writer.logRpcMessage(seq.getAndIncrement(), EventType.EVENT_TYPE_CLIENT_MESSAGE, method.getRequestMarshaller(), message, GrpcLogEntry.Logger.LOGGER_CLIENT, callId);
                    super.sendMessage(message);
                }

                @Override
                public void halfClose() {
                    writer.logHalfClose(seq.getAndIncrement(), GrpcLogEntry.Logger.LOGGER_CLIENT, callId);
                    super.halfClose();
                }

                @Override
                public void cancel(String message, Throwable cause) {
                    writer.logCancel(seq.getAndIncrement(), GrpcLogEntry.Logger.LOGGER_CLIENT, callId);
                    super.cancel(message, cause);
                }
            };
        }
    };
}
Also used : Status(io.grpc.Status) SimpleForwardingServerCallListener(io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener) SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) Channel(io.grpc.Channel) Deadline(io.grpc.Deadline) Metadata(io.grpc.Metadata) InternalMetadata(io.grpc.InternalMetadata) Duration(com.google.protobuf.Duration) CallOptions(io.grpc.CallOptions) ByteString(com.google.protobuf.ByteString) MethodDescriptor(io.grpc.MethodDescriptor) AtomicLong(java.util.concurrent.atomic.AtomicLong) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall) ClientCall(io.grpc.ClientCall) ClientInterceptor(io.grpc.ClientInterceptor) SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall)

Example 9 with SimpleForwardingClientCall

use of io.grpc.ForwardingClientCall.SimpleForwardingClientCall in project grpc-java by grpc.

the class HeaderServerInterceptorTest method serverHeaderDeliveredToClient.

@Test
public void serverHeaderDeliveredToClient() {
    class SpyingClientInterceptor implements ClientInterceptor {

        ClientCall.Listener<?> spyListener;

        @Override
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
            return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {

                @Override
                public void start(Listener<RespT> responseListener, Metadata headers) {
                    spyListener = responseListener = mock(ClientCall.Listener.class, delegatesTo(responseListener));
                    super.start(responseListener, headers);
                }
            };
        }
    }
    SpyingClientInterceptor clientInterceptor = new SpyingClientInterceptor();
    GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel).withInterceptors(clientInterceptor);
    ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
    blockingStub.sayHello(HelloRequest.getDefaultInstance());
    assertNotNull(clientInterceptor.spyListener);
    verify(clientInterceptor.spyListener).onHeaders(metadataCaptor.capture());
    assertEquals("customRespondValue", metadataCaptor.getValue().get(HeaderServerInterceptor.CUSTOM_HEADER_KEY));
}
Also used : GreeterBlockingStub(io.grpc.examples.helloworld.GreeterGrpc.GreeterBlockingStub) Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) MethodDescriptor(io.grpc.MethodDescriptor) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall) ClientCall(io.grpc.ClientCall) ClientInterceptor(io.grpc.ClientInterceptor) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall) Test(org.junit.Test)

Example 10 with SimpleForwardingClientCall

use of io.grpc.ForwardingClientCall.SimpleForwardingClientCall in project motan by weibocom.

the class GrpcClient method request.

@SuppressWarnings({ "unchecked", "rawtypes" })
public <ReqT, RespT> Response request(final Request request) {
    MethodDescriptor<ReqT, RespT> methodDesc = methodDescMap.get(request.getMethodName());
    if (methodDesc == null) {
        throw new MotanServiceException("request method grpc descriptornot found.method:" + request.getMethodName());
    }
    int timeout = url.getMethodParameter(request.getMethodName(), request.getParamtersDesc(), URLParamType.requestTimeout.getName(), URLParamType.requestTimeout.getIntValue());
    if (timeout < 0) {
        throw new MotanServiceException("request timeout invalid.method timeout:" + timeout);
    }
    ClientCall<ReqT, RespT> call = new SimpleForwardingClientCall(channel.newCall(methodDesc, callOption.withDeadlineAfter(timeout, TimeUnit.MILLISECONDS))) {

        public void start(Listener responseListener, Metadata headers) {
            Map<String, String> attachments = request.getAttachments();
            if (attachments != null && !attachments.isEmpty()) {
                for (Entry<String, String> entry : attachments.entrySet()) {
                    headers.put(Metadata.Key.of(entry.getKey(), Metadata.ASCII_STRING_MARSHALLER), entry.getValue());
                }
            }
            super.start(responseListener, headers);
        }
    };
    GrpcResponseFuture<RespT> responseFuture = new GrpcResponseFuture<RespT>(request, timeout, url, call);
    MethodType methodType = methodDesc.getType();
    switch(methodType) {
        case UNARY:
            ClientCalls.asyncUnaryCall(call, (ReqT) request.getArguments()[0], responseFuture);
            break;
        case SERVER_STREAMING:
            ClientCalls.asyncServerStreamingCall(call, (ReqT) request.getArguments()[0], (io.grpc.stub.StreamObserver<RespT>) request.getArguments()[1]);
            responseFuture.onCompleted();
            break;
        case CLIENT_STREAMING:
            StreamObserver<ReqT> clientObserver = ClientCalls.asyncClientStreamingCall(call, (io.grpc.stub.StreamObserver<RespT>) request.getArguments()[0]);
            responseFuture.onNext(clientObserver);
            responseFuture.onCompleted();
            break;
        case BIDI_STREAMING:
            StreamObserver<ReqT> biObserver = ClientCalls.asyncBidiStreamingCall(call, (io.grpc.stub.StreamObserver<RespT>) request.getArguments()[0]);
            responseFuture.onNext(biObserver);
            responseFuture.onCompleted();
            break;
        default:
            throw new MotanServiceException("unknown grpc method type:" + methodType);
    }
    return responseFuture;
}
Also used : MethodType(io.grpc.MethodDescriptor.MethodType) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall)

Aggregations

SimpleForwardingClientCall (io.grpc.ForwardingClientCall.SimpleForwardingClientCall)10 Metadata (io.grpc.Metadata)9 CallOptions (io.grpc.CallOptions)8 Channel (io.grpc.Channel)8 ClientInterceptor (io.grpc.ClientInterceptor)8 ClientCall (io.grpc.ClientCall)6 ManagedChannel (io.grpc.ManagedChannel)6 MethodDescriptor (io.grpc.MethodDescriptor)5 SimpleForwardingClientCallListener (io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener)4 Test (org.junit.Test)4 Status (io.grpc.Status)3 AtomicLong (java.util.concurrent.atomic.AtomicLong)2 Span (zipkin2.Span)2 CurrentSpanCustomizer (brave.CurrentSpanCustomizer)1 Span (brave.Span)1 SpanCustomizer (brave.SpanCustomizer)1 Tracer (brave.Tracer)1 TopicAdminClient (com.google.cloud.pubsub.spi.v1.TopicAdminClient)1 ByteString (com.google.protobuf.ByteString)1 Duration (com.google.protobuf.Duration)1