Search in sources :

Example 31 with ClientInterceptor

use of io.grpc.ClientInterceptor 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 32 with ClientInterceptor

use of io.grpc.ClientInterceptor 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 33 with ClientInterceptor

use of io.grpc.ClientInterceptor in project grpc-java by grpc.

the class LoggingChannelProviderTest method newChannelBuilder_interceptorCalled.

@Test
public void newChannelBuilder_interceptorCalled() {
    ClientInterceptor interceptor = mock(ClientInterceptor.class, delegatesTo(new NoopInterceptor()));
    InternalLoggingChannelInterceptor.Factory factory = mock(InternalLoggingChannelInterceptor.Factory.class);
    when(factory.create()).thenReturn(interceptor);
    LoggingChannelProvider.init(factory);
    ManagedChannelBuilder<?> builder = Grpc.newChannelBuilder("localhost", TlsChannelCredentials.create());
    ManagedChannel channel = builder.build();
    CallOptions callOptions = CallOptions.DEFAULT;
    ClientCall<Void, Void> unused = channel.newCall(method, callOptions);
    verify(interceptor).interceptCall(same(method), same(callOptions), ArgumentMatchers.<Channel>any());
    channel.shutdownNow();
    LoggingChannelProvider.finish();
}
Also used : InternalLoggingChannelInterceptor(io.grpc.observability.interceptors.InternalLoggingChannelInterceptor) ClientInterceptor(io.grpc.ClientInterceptor) ManagedChannel(io.grpc.ManagedChannel) CallOptions(io.grpc.CallOptions) Test(org.junit.Test)

Example 34 with ClientInterceptor

use of io.grpc.ClientInterceptor in project jetcd by coreos.

the class AuthCredential method authenticate.

private void authenticate(MetadataApplier applier) {
    checkArgument(!manager.builder().user().isEmpty(), "username can not be empty.");
    checkArgument(!manager.builder().password().isEmpty(), "password can not be empty.");
    VertxAuthGrpc.AuthVertxStub authFutureStub = VertxAuthGrpc.newVertxStub(this.manager.getChannel());
    List<ClientInterceptor> interceptorsChain = new ArrayList<>();
    if (manager.builder().authHeaders() != null) {
        Metadata metadata = new Metadata();
        manager.builder().authHeaders().forEach((BiConsumer<Metadata.Key, Object>) metadata::put);
        interceptorsChain.add(MetadataUtils.newAttachHeadersInterceptor(metadata));
    }
    if (manager.builder().authInterceptors() != null) {
        interceptorsChain.addAll(manager.builder().authInterceptors());
    }
    if (!interceptorsChain.isEmpty()) {
        authFutureStub = authFutureStub.withInterceptors(interceptorsChain.toArray(new ClientInterceptor[0]));
    }
    final ByteString user = ByteString.copyFrom(this.manager.builder().user().getBytes());
    final ByteString pass = ByteString.copyFrom(this.manager.builder().password().getBytes());
    AuthenticateRequest request = AuthenticateRequest.newBuilder().setNameBytes(user).setPasswordBytes(pass).build();
    try {
        authFutureStub.authenticate(request).onFailure(t -> {
            applier.fail(Status.UNAUTHENTICATED.withCause(t));
        }).onSuccess(h -> {
            Metadata meta = new Metadata();
            meta.put(TOKEN, h.getToken());
            this.meta = meta;
            applier.apply(this.meta);
        });
    } catch (Exception e) {
        applier.fail(Status.UNAUTHENTICATED.withCause(e));
    }
}
Also used : CallCredentials(io.grpc.CallCredentials) AuthenticateRequest(io.etcd.jetcd.api.AuthenticateRequest) Executor(java.util.concurrent.Executor) ClientInterceptor(io.grpc.ClientInterceptor) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) List(java.util.List) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) MetadataUtils(io.grpc.stub.MetadataUtils) BiConsumer(java.util.function.BiConsumer) VertxAuthGrpc(io.etcd.jetcd.api.VertxAuthGrpc) Metadata(io.grpc.Metadata) Status(io.grpc.Status) AuthenticateRequest(io.etcd.jetcd.api.AuthenticateRequest) ByteString(com.google.protobuf.ByteString) ClientInterceptor(io.grpc.ClientInterceptor) ArrayList(java.util.ArrayList) Metadata(io.grpc.Metadata) VertxAuthGrpc(io.etcd.jetcd.api.VertxAuthGrpc)

Example 35 with ClientInterceptor

use of io.grpc.ClientInterceptor 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)

Aggregations

ClientInterceptor (io.grpc.ClientInterceptor)34 CallOptions (io.grpc.CallOptions)23 Metadata (io.grpc.Metadata)22 Channel (io.grpc.Channel)18 MethodDescriptor (io.grpc.MethodDescriptor)15 ManagedChannel (io.grpc.ManagedChannel)14 Test (org.junit.Test)13 ClientCall (io.grpc.ClientCall)11 SimpleForwardingClientCall (io.grpc.ForwardingClientCall.SimpleForwardingClientCall)8 ChannelFactoryBuilder (com.navercorp.pinpoint.grpc.client.ChannelFactoryBuilder)5 DefaultChannelFactoryBuilder (com.navercorp.pinpoint.grpc.client.DefaultChannelFactoryBuilder)5 UnaryCallDeadlineInterceptor (com.navercorp.pinpoint.grpc.client.UnaryCallDeadlineInterceptor)5 ClientOption (com.navercorp.pinpoint.grpc.client.config.ClientOption)5 Status (io.grpc.Status)5 SslOption (com.navercorp.pinpoint.grpc.client.config.SslOption)4 ForwardingClientCall (io.grpc.ForwardingClientCall)4 SimpleForwardingClientCallListener (io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener)4 PickSubchannelArgs (io.grpc.LoadBalancer.PickSubchannelArgs)4 SocketAddress (java.net.SocketAddress)4 AtomicLong (java.util.concurrent.atomic.AtomicLong)4