Search in sources :

Example 1 with SimpleForwardingClientCall

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

the class ITTracingServerInterceptor method usesExistingTraceId.

@Test
public void usesExistingTraceId() throws Exception {
    final String traceId = "463ac35c9f6413ad";
    final String parentId = traceId;
    final String spanId = "48485a3953bb6124";
    Channel channel = ClientInterceptors.intercept(client, 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) {
                    headers.put(Key.of("X-B3-TraceId", ASCII_STRING_MARSHALLER), traceId);
                    headers.put(Key.of("X-B3-ParentSpanId", ASCII_STRING_MARSHALLER), parentId);
                    headers.put(Key.of("X-B3-SpanId", ASCII_STRING_MARSHALLER), spanId);
                    headers.put(Key.of("X-B3-Sampled", ASCII_STRING_MARSHALLER), "1");
                    super.start(responseListener, headers);
                }
            };
        }
    });
    GreeterGrpc.newBlockingStub(channel).sayHello(HELLO_REQUEST);
    Span span = spans.take();
    assertThat(span.traceId()).isEqualTo(traceId);
    assertThat(span.parentId()).isEqualTo(parentId);
    assertThat(span.id()).isEqualTo(spanId);
    assertThat(span.shared()).isTrue();
}
Also used : ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) Span(zipkin2.Span) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall) ClientCall(io.grpc.ClientCall) ClientInterceptor(io.grpc.ClientInterceptor) Test(org.junit.Test)

Example 2 with SimpleForwardingClientCall

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

the class ITTracingServerInterceptor method createsChildWhenJoinDisabled.

@Test
public void createsChildWhenJoinDisabled() throws Exception {
    grpcTracing = GrpcTracing.create(tracingBuilder(NEVER_SAMPLE).supportsJoin(false).build());
    init();
    final String traceId = "463ac35c9f6413ad";
    final String parentId = traceId;
    final String spanId = "48485a3953bb6124";
    Channel channel = ClientInterceptors.intercept(client, 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) {
                    headers.put(Key.of("X-B3-TraceId", ASCII_STRING_MARSHALLER), traceId);
                    headers.put(Key.of("X-B3-ParentSpanId", ASCII_STRING_MARSHALLER), parentId);
                    headers.put(Key.of("X-B3-SpanId", ASCII_STRING_MARSHALLER), spanId);
                    headers.put(Key.of("X-B3-Sampled", ASCII_STRING_MARSHALLER), "1");
                    super.start(responseListener, headers);
                }
            };
        }
    });
    GreeterGrpc.newBlockingStub(channel).sayHello(HELLO_REQUEST);
    Span span = spans.take();
    assertThat(span.traceId()).isEqualTo(traceId);
    assertThat(span.parentId()).isEqualTo(spanId);
    assertThat(span.id()).isNotEqualTo(spanId);
    assertThat(span.shared()).isNull();
}
Also used : ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) Span(zipkin2.Span) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall) ClientCall(io.grpc.ClientCall) ClientInterceptor(io.grpc.ClientInterceptor) Test(org.junit.Test)

Example 3 with SimpleForwardingClientCall

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

the class XdsTestClient method runQps.

private void runQps() throws InterruptedException, ExecutionException {
    final SettableFuture<Void> failure = SettableFuture.create();
    final class PeriodicRpc implements Runnable {

        @Override
        public void run() {
            List<RpcConfig> configs = rpcConfigs;
            for (RpcConfig cfg : configs) {
                makeRpc(cfg);
            }
        }

        private void makeRpc(final RpcConfig config) {
            final long requestId;
            final Set<XdsStatsWatcher> savedWatchers = new HashSet<>();
            synchronized (lock) {
                currentRequestId += 1;
                requestId = currentRequestId;
                savedWatchers.addAll(watchers);
            }
            ManagedChannel channel = channels.get((int) (requestId % channels.size()));
            TestServiceGrpc.TestServiceStub stub = TestServiceGrpc.newStub(channel);
            final AtomicReference<ClientCall<?, ?>> clientCallRef = new AtomicReference<>();
            final AtomicReference<String> hostnameRef = new AtomicReference<>();
            stub = stub.withDeadlineAfter(config.timeoutSec, TimeUnit.SECONDS).withInterceptors(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);
                    clientCallRef.set(call);
                    return new SimpleForwardingClientCall<ReqT, RespT>(call) {

                        @Override
                        public void start(Listener<RespT> responseListener, Metadata headers) {
                            headers.merge(config.metadata);
                            super.start(new SimpleForwardingClientCallListener<RespT>(responseListener) {

                                @Override
                                public void onHeaders(Metadata headers) {
                                    hostnameRef.set(headers.get(XdsTestServer.HOSTNAME_KEY));
                                    super.onHeaders(headers);
                                }
                            }, headers);
                        }
                    };
                }
            });
            if (config.rpcType == RpcType.EMPTY_CALL) {
                stub.emptyCall(EmptyProtos.Empty.getDefaultInstance(), new StreamObserver<EmptyProtos.Empty>() {

                    @Override
                    public void onCompleted() {
                        handleRpcCompleted(requestId, config.rpcType, hostnameRef.get(), savedWatchers);
                    }

                    @Override
                    public void onError(Throwable t) {
                        handleRpcError(requestId, config.rpcType, Status.fromThrowable(t), savedWatchers);
                    }

                    @Override
                    public void onNext(EmptyProtos.Empty response) {
                    }
                });
            } else if (config.rpcType == RpcType.UNARY_CALL) {
                SimpleRequest request = SimpleRequest.newBuilder().setFillServerId(true).build();
                stub.unaryCall(request, new StreamObserver<SimpleResponse>() {

                    @Override
                    public void onCompleted() {
                        handleRpcCompleted(requestId, config.rpcType, hostnameRef.get(), savedWatchers);
                    }

                    @Override
                    public void onError(Throwable t) {
                        if (printResponse) {
                            logger.log(Level.WARNING, "Rpc failed", t);
                        }
                        handleRpcError(requestId, config.rpcType, Status.fromThrowable(t), savedWatchers);
                    }

                    @Override
                    public void onNext(SimpleResponse response) {
                        // service and rely on parsing stdout.
                        if (printResponse) {
                            System.out.println("Greeting: Hello world, this is " + response.getHostname() + ", from " + clientCallRef.get().getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR));
                        }
                        // TODO(ericgribkoff) Delete when server is deployed that sets metadata value.
                        if (hostnameRef.get() == null) {
                            hostnameRef.set(response.getHostname());
                        }
                    }
                });
            } else {
                throw new AssertionError("Unknown RPC type: " + config.rpcType);
            }
            statsAccumulator.recordRpcStarted(config.rpcType);
        }

        private void handleRpcCompleted(long requestId, RpcType rpcType, String hostname, Set<XdsStatsWatcher> watchers) {
            statsAccumulator.recordRpcFinished(rpcType, Status.OK);
            notifyWatchers(watchers, rpcType, requestId, hostname);
        }

        private void handleRpcError(long requestId, RpcType rpcType, Status status, Set<XdsStatsWatcher> watchers) {
            statsAccumulator.recordRpcFinished(rpcType, status);
            notifyWatchers(watchers, rpcType, requestId, null);
        }
    }
    long nanosPerQuery = TimeUnit.SECONDS.toNanos(1) / qps;
    ListenableScheduledFuture<?> future = exec.scheduleAtFixedRate(new PeriodicRpc(), 0, nanosPerQuery, TimeUnit.NANOSECONDS);
    Futures.addCallback(future, new FutureCallback<Object>() {

        @Override
        public void onFailure(Throwable t) {
            failure.setException(t);
        }

        @Override
        public void onSuccess(Object o) {
        }
    }, MoreExecutors.directExecutor());
    failure.get();
}
Also used : SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) Set(java.util.Set) HashSet(java.util.HashSet) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall) ClientCall(io.grpc.ClientCall) SimpleResponse(io.grpc.testing.integration.Messages.SimpleResponse) ClientInterceptor(io.grpc.ClientInterceptor) ManagedChannel(io.grpc.ManagedChannel) HashSet(java.util.HashSet) StreamObserver(io.grpc.stub.StreamObserver) Status(io.grpc.Status) ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) RpcType(io.grpc.testing.integration.Messages.ClientConfigureRequest.RpcType) AtomicReference(java.util.concurrent.atomic.AtomicReference) MethodDescriptor(io.grpc.MethodDescriptor) SimpleForwardingClientCall(io.grpc.ForwardingClientCall.SimpleForwardingClientCall)

Example 4 with SimpleForwardingClientCall

use of io.grpc.ForwardingClientCall.SimpleForwardingClientCall 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 5 with SimpleForwardingClientCall

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

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