Search in sources :

Example 41 with CallOptions

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

the class FaultFilter method buildClientInterceptor.

@Nullable
@Override
public ClientInterceptor buildClientInterceptor(FilterConfig config, @Nullable FilterConfig overrideConfig, PickSubchannelArgs args, final ScheduledExecutorService scheduler) {
    checkNotNull(config, "config");
    if (overrideConfig != null) {
        config = overrideConfig;
    }
    FaultConfig faultConfig = (FaultConfig) config;
    Long delayNanos = null;
    Status abortStatus = null;
    if (faultConfig.maxActiveFaults() == null || activeFaultCounter.get() < faultConfig.maxActiveFaults()) {
        Metadata headers = args.getHeaders();
        if (faultConfig.faultDelay() != null) {
            delayNanos = determineFaultDelayNanos(faultConfig.faultDelay(), headers);
        }
        if (faultConfig.faultAbort() != null) {
            abortStatus = determineFaultAbortStatus(faultConfig.faultAbort(), headers);
        }
    }
    if (delayNanos == null && abortStatus == null) {
        return null;
    }
    final Long finalDelayNanos = delayNanos;
    final Status finalAbortStatus = getAbortStatusWithDescription(abortStatus);
    final class FaultInjectionInterceptor implements ClientInterceptor {

        @Override
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method, final CallOptions callOptions, final Channel next) {
            Executor callExecutor = callOptions.getExecutor();
            if (callExecutor == null) {
                // This should never happen in practice because
                // ManagedChannelImpl.ConfigSelectingClientCall always provides CallOptions with
                // a callExecutor.
                // TODO(https://github.com/grpc/grpc-java/issues/7868)
                callExecutor = MoreExecutors.directExecutor();
            }
            if (finalDelayNanos != null) {
                Supplier<? extends ClientCall<ReqT, RespT>> callSupplier;
                if (finalAbortStatus != null) {
                    callSupplier = Suppliers.ofInstance(new FailingClientCall<ReqT, RespT>(finalAbortStatus, callExecutor));
                } else {
                    callSupplier = new Supplier<ClientCall<ReqT, RespT>>() {

                        @Override
                        public ClientCall<ReqT, RespT> get() {
                            return next.newCall(method, callOptions);
                        }
                    };
                }
                final DelayInjectedCall<ReqT, RespT> delayInjectedCall = new DelayInjectedCall<>(finalDelayNanos, callExecutor, scheduler, callOptions.getDeadline(), callSupplier);
                final class DeadlineInsightForwardingCall extends ForwardingClientCall<ReqT, RespT> {

                    @Override
                    protected ClientCall<ReqT, RespT> delegate() {
                        return delayInjectedCall;
                    }

                    @Override
                    public void start(Listener<RespT> listener, Metadata headers) {
                        Listener<RespT> finalListener = new SimpleForwardingClientCallListener<RespT>(listener) {

                            @Override
                            public void onClose(Status status, Metadata trailers) {
                                if (status.getCode().equals(Code.DEADLINE_EXCEEDED)) {
                                    // TODO(zdapeng:) check effective deadline locally, and
                                    // do the following only if the local deadline is exceeded.
                                    // (If the server sends DEADLINE_EXCEEDED for its own deadline, then the
                                    // injected delay does not contribute to the error, because the request is
                                    // only sent out after the delay. There could be a race between local and
                                    // remote, but it is rather rare.)
                                    String description = String.format("Deadline exceeded after up to %d ns of fault-injected delay", finalDelayNanos);
                                    if (status.getDescription() != null) {
                                        description = description + ": " + status.getDescription();
                                    }
                                    status = Status.DEADLINE_EXCEEDED.withDescription(description).withCause(status.getCause());
                                    // Replace trailers to prevent mixing sources of status and trailers.
                                    trailers = new Metadata();
                                }
                                delegate().onClose(status, trailers);
                            }
                        };
                        delegate().start(finalListener, headers);
                    }
                }
                return new DeadlineInsightForwardingCall();
            } else {
                return new FailingClientCall<>(finalAbortStatus, callExecutor);
            }
        }
    }
    return new FaultInjectionInterceptor();
}
Also used : SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) ForwardingClientCall(io.grpc.ForwardingClientCall) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) Executor(java.util.concurrent.Executor) DelayedClientCall(io.grpc.internal.DelayedClientCall) ClientCall(io.grpc.ClientCall) ForwardingClientCall(io.grpc.ForwardingClientCall) ClientInterceptor(io.grpc.ClientInterceptor) Status(io.grpc.Status) Channel(io.grpc.Channel) MethodDescriptor(io.grpc.MethodDescriptor) AtomicLong(java.util.concurrent.atomic.AtomicLong) SimpleForwardingClientCallListener(io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener) Nullable(javax.annotation.Nullable)

Example 42 with CallOptions

use of io.grpc.CallOptions 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 43 with CallOptions

use of io.grpc.CallOptions in project dubbo by alibaba.

the class GrpcProtocol method protocolBindingRefer.

@Override
protected <T> Invoker<T> protocolBindingRefer(final Class<T> type, final URL url) throws RpcException {
    Class<?> enclosingClass = type.getEnclosingClass();
    if (enclosingClass == null) {
        throw new IllegalArgumentException(type.getName() + " must be declared inside protobuf generated classes, " + "should be something like ServiceNameGrpc.IServiceName.");
    }
    final Method dubboStubMethod;
    try {
        dubboStubMethod = enclosingClass.getDeclaredMethod("getDubboStub", Channel.class, CallOptions.class, URL.class, ReferenceConfigBase.class);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException("Does not find getDubboStub in " + enclosingClass.getName() + ", please use the customized protoc-gen-dubbo-java to update the generated classes.");
    }
    // Channel
    ReferenceCountManagedChannel channel = getSharedChannel(url);
    // CallOptions
    try {
        @SuppressWarnings("unchecked") final T stub = (T) dubboStubMethod.invoke(null, channel, GrpcOptionsUtils.buildCallOptions(url), url, ApplicationModel.getConsumerModel(url.getServiceKey()).getReferenceConfig());
        final Invoker<T> target = proxyFactory.getInvoker(stub, type, url);
        GrpcInvoker<T> grpcInvoker = new GrpcInvoker<>(type, url, target, channel);
        invokers.add(grpcInvoker);
        return grpcInvoker;
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new IllegalStateException("Could not create stub through reflection.", e);
    }
}
Also used : ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) Method(java.lang.reflect.Method) CallOptions(io.grpc.CallOptions) URL(org.apache.dubbo.common.URL) InvocationTargetException(java.lang.reflect.InvocationTargetException) ReferenceConfigBase(org.apache.dubbo.config.ReferenceConfigBase)

Example 44 with CallOptions

use of io.grpc.CallOptions 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 45 with CallOptions

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

CallOptions (io.grpc.CallOptions)81 Test (org.junit.Test)61 Metadata (io.grpc.Metadata)50 Channel (io.grpc.Channel)36 MethodDescriptor (io.grpc.MethodDescriptor)28 ClientInterceptor (io.grpc.ClientInterceptor)23 ManagedChannel (io.grpc.ManagedChannel)18 ClientStreamTracer (io.grpc.ClientStreamTracer)17 ClientCall (io.grpc.ClientCall)15 PickSubchannelArgs (io.grpc.LoadBalancer.PickSubchannelArgs)11 Status (io.grpc.Status)11 Context (io.grpc.Context)10 Subchannel (io.grpc.LoadBalancer.Subchannel)10 MockClientTransportInfo (io.grpc.internal.TestUtils.MockClientTransportInfo)10 ForwardingSubchannel (io.grpc.util.ForwardingSubchannel)9 SimpleForwardingClientCall (io.grpc.ForwardingClientCall.SimpleForwardingClientCall)8 NoopClientCall (io.grpc.internal.NoopClientCall)8 SocketAddress (java.net.SocketAddress)8 SimpleForwardingClientCallListener (io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener)7 ByteString (com.google.protobuf.ByteString)6