Search in sources :

Example 21 with ClientInterceptor

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ClientInterceptor in project jetcd by coreos.

the class ClientConnectionManagerTest method testHeaders.

@Test
public void testHeaders() throws InterruptedException, ExecutionException {
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientBuilder builder = TestUtil.client(cluster).header("MyHeader1", "MyHeaderVal1").header("MyHeader2", "MyHeaderVal2").interceptor(new ClientInterceptor() {

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

                @Override
                public void start(Listener<RespT> responseListener, Metadata headers) {
                    super.start(responseListener, headers);
                    assertThat(headers.get(Metadata.Key.of("MyHeader1", Metadata.ASCII_STRING_MARSHALLER))).isEqualTo("MyHeaderVal1");
                    assertThat(headers.get(Metadata.Key.of("MyHeader2", Metadata.ASCII_STRING_MARSHALLER))).isEqualTo("MyHeaderVal2");
                    latch.countDown();
                }
            };
        }
    });
    try (Client client = builder.build()) {
        CompletableFuture<PutResponse> future = client.getKVClient().put(bytesOf("sample_key"), bytesOf("sample_key"));
        latch.await(1, TimeUnit.MINUTES);
        future.get();
    }
}
Also used : Channel(io.grpc.Channel) ForwardingClientCall(io.grpc.ForwardingClientCall) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) CountDownLatch(java.util.concurrent.CountDownLatch) PutResponse(io.etcd.jetcd.kv.PutResponse) ClientCall(io.grpc.ClientCall) ForwardingClientCall(io.grpc.ForwardingClientCall) ClientInterceptor(io.grpc.ClientInterceptor) Client(io.etcd.jetcd.Client) ClientBuilder(io.etcd.jetcd.ClientBuilder) Test(org.junit.jupiter.api.Test)

Example 22 with ClientInterceptor

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ClientInterceptor in project toolkit by googleapis.

the class Pubsub method gapic.

private static void gapic(final Settings settings) throws Exception {
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    // In real clients, InstantiatingChannelProvider is responsible for adding interceptors.
    // We can't use it here because InstantiatingChannelProvider doesn't have sslContext method.
    // Instead, we imitate HeaderInterceptor.
    ClientInterceptor headerInterceptor = new ClientInterceptor() {

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

                @Override
                public void start(ClientCall.Listener<RespT> responseListener, Metadata headers) {
                    headers.put(X_GOOG_HEADER_KEY, X_GOOG_HEADER_VALUE);
                    super.start(responseListener, headers);
                }
            };
        }
    };
    ManagedChannel channel = NettyChannelBuilder.forTarget(settings.endpoint()).executor(executor).sslContext(GrpcSslContexts.forClient().trustManager(new File(settings.cert())).build()).intercept(headerInterceptor).build();
    final Semaphore semaphore = new Semaphore(settings.numWorkers());
    final TopicAdminClient client = TopicAdminClient.create(TopicAdminSettings.defaultBuilder().setChannelProvider(FixedChannelProvider.create(channel)).setExecutorProvider(FixedExecutorProvider.create(executor)).build());
    final AtomicLong resetTime = new AtomicLong();
    final AtomicLong numCalls = new AtomicLong();
    final AtomicLong numErrs = new AtomicLong();
    long endTime = System.nanoTime() + settings.warmDurNano() + settings.targetDurNano();
    Thread resetter = new Thread(() -> {
        try {
            Thread.sleep(settings.warmDurNano() / MILLION);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        numCalls.set(0);
        numErrs.set(0);
        resetTime.set(System.nanoTime());
    });
    resetter.start();
    while (System.nanoTime() < endTime) {
        semaphore.acquire(1);
        ApiFutures.addCallback(client.getTopicCallable().futureCall(GetTopicRequest.newBuilder().setTopicWithTopicName(TOPIC_NAME_RESOURCE).build()), new ApiFutureCallback<Topic>() {

            @Override
            public void onSuccess(Topic topic) {
                if (!topic.getName().equals(TOPIC_NAME_STRING)) {
                    numErrs.incrementAndGet();
                }
                both();
            }

            @Override
            public void onFailure(Throwable t) {
                numErrs.incrementAndGet();
                both();
            }

            void both() {
                numCalls.incrementAndGet();
                semaphore.release(1);
            }
        });
    }
    long nCalls = numCalls.get();
    long nErrs = numErrs.get();
    long runDurNano = System.nanoTime() - resetTime.get();
    System.out.println("errors: " + nErrs);
    System.out.println("calls: " + nCalls);
    System.out.println("time per call (ns): " + (runDurNano / nCalls));
    System.out.println("QPS: " + (nCalls * BILLION / runDurNano));
    client.close();
    channel.shutdown().awaitTermination(10, TimeUnit.SECONDS);
    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.SECONDS);
}
Also used : ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) Semaphore(java.util.concurrent.Semaphore) MethodDescriptor(io.grpc.MethodDescriptor) AtomicLong(java.util.concurrent.atomic.AtomicLong) TopicAdminClient(com.google.cloud.pubsub.spi.v1.TopicAdminClient) ClientInterceptor(io.grpc.ClientInterceptor) ManagedChannel(io.grpc.ManagedChannel) Topic(com.google.pubsub.v1.Topic) File(java.io.File) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall)

Example 23 with ClientInterceptor

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ClientInterceptor in project brave by openzipkin.

the class BaseITTracingClientInterceptor method initMessageTaggingClient.

void initMessageTaggingClient() {
    SpanCustomizer customizer = CurrentSpanCustomizer.create(tracing);
    AtomicInteger sends = new AtomicInteger(1);
    AtomicInteger recvs = new AtomicInteger(1);
    closeClient(client);
    client = newClient(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) {
                    super.start(new SimpleForwardingClientCallListener<RespT>(responseListener) {

                        @Override
                        public void onMessage(RespT message) {
                            customizer.tag("grpc.message_recv." + recvs.getAndIncrement(), message.toString());
                            delegate().onMessage(message);
                        }
                    }, headers);
                }

                @Override
                public void sendMessage(ReqT message) {
                    customizer.tag("grpc.message_send." + sends.getAndIncrement(), message.toString());
                    delegate().sendMessage(message);
                }
            };
        }
    }, grpcTracing.newClientInterceptor());
}
Also used : SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) MethodDescriptor(io.grpc.MethodDescriptor) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ClientInterceptor(io.grpc.ClientInterceptor) CurrentSpanCustomizer(brave.CurrentSpanCustomizer) SpanCustomizer(brave.SpanCustomizer) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall)

Example 24 with ClientInterceptor

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ClientInterceptor in project pravega by pravega.

the class RPCTracingHelpersTest method testInterceptors.

@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testInterceptors() {
    String requestDescriptor = "createStream-myScope-myStream";
    long requestId = 1234L;
    ClientInterceptor clientInterceptor = RPCTracingHelpers.getClientInterceptor();
    RequestTracker requestTracker = new RequestTracker(true);
    // Mocking RPC elements.
    MethodDescriptor.Marshaller<Object> mockMarshaller = Mockito.mock(MethodDescriptor.Marshaller.class);
    ClientCall.Listener<Object> listener = Mockito.mock(ClientCall.Listener.class);
    ServerCall serverCall = Mockito.mock(ServerCall.class);
    ServerCallHandler serverCallHandler = Mockito.mock(ServerCallHandler.class);
    @Cleanup("shutdown") ManagedChannel channel = NettyChannelBuilder.forTarget("localhost").build();
    MethodDescriptor method = MethodDescriptor.newBuilder().setFullMethodName("createStream").setType(MethodDescriptor.MethodType.UNARY).setRequestMarshaller(mockMarshaller).setResponseMarshaller(mockMarshaller).build();
    Mockito.when(serverCall.getMethodDescriptor()).thenReturn(method);
    // Actual elements to work with.
    CallOptions callOptions = CallOptions.DEFAULT;
    Metadata headers = new Metadata();
    // Test that headers do not contain tracing-related key/values, as call options are not set.
    clientInterceptor.interceptCall(method, callOptions, channel).start(listener, headers);
    assertFalse(headers.containsKey(RPCTracingHelpers.DESCRIPTOR_HEADER));
    assertFalse(headers.containsKey(RPCTracingHelpers.ID_HEADER));
    // Check that the server interceptor handles clients not sending tracing headers and that the cache remains clean.
    ServerInterceptor serverInterceptor = RPCTracingHelpers.getServerInterceptor(requestTracker);
    serverInterceptor.interceptCall(serverCall, headers, serverCallHandler);
    assertEquals(0, requestTracker.getNumDescriptors());
    // Add call options and check that headers are correctly set.
    callOptions = callOptions.withOption(RPCTracingHelpers.REQUEST_DESCRIPTOR_CALL_OPTION, requestDescriptor).withOption(RPCTracingHelpers.REQUEST_ID_CALL_OPTION, String.valueOf(requestId));
    clientInterceptor.interceptCall(method, callOptions, channel).start(listener, headers);
    assertEquals(requestDescriptor, headers.get(RPCTracingHelpers.DESCRIPTOR_HEADER));
    assertEquals(requestId, Long.parseLong(headers.get(RPCTracingHelpers.ID_HEADER)));
    // Test that the server interceptor correctly sets these headers in the cache for further tracking.
    serverInterceptor.interceptCall(serverCall, headers, serverCallHandler);
    assertEquals(1, requestTracker.getNumDescriptors());
    assertEquals(requestId, requestTracker.getRequestIdFor(requestDescriptor));
}
Also used : ServerCallHandler(io.grpc.ServerCallHandler) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) RequestTracker(io.pravega.common.tracing.RequestTracker) MethodDescriptor(io.grpc.MethodDescriptor) Cleanup(lombok.Cleanup) ServerCall(io.grpc.ServerCall) ClientCall(io.grpc.ClientCall) ServerInterceptor(io.grpc.ServerInterceptor) ClientInterceptor(io.grpc.ClientInterceptor) ManagedChannel(io.grpc.ManagedChannel) Test(org.junit.Test)

Example 25 with ClientInterceptor

use of org.apache.beam.vendor.grpc.v1p43p2.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)

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