Search in sources :

Example 1 with SimpleResponse

use of io.grpc.testing.integration.Messages.SimpleResponse in project grpc-java by grpc.

the class CascadingTest method testCascadingCancellationViaOuterContextCancellation.

/**
 * Test {@link Context} cancellation propagates from the first node in the call chain all the way
 * to the last.
 */
@Test
public void testCascadingCancellationViaOuterContextCancellation() throws Exception {
    observedCancellations = new CountDownLatch(2);
    receivedCancellations = new CountDownLatch(3);
    Future<?> chainReady = startChainingServer(3);
    CancellableContext context = Context.current().withCancellation();
    Future<SimpleResponse> future;
    Context prevContext = context.attach();
    try {
        future = futureStub.unaryCall(SimpleRequest.getDefaultInstance());
    } finally {
        context.detach(prevContext);
    }
    chainReady.get(5, TimeUnit.SECONDS);
    context.cancel(null);
    try {
        future.get(5, TimeUnit.SECONDS);
        fail("Expected cancellation");
    } catch (ExecutionException ex) {
        Status status = Status.fromThrowable(ex);
        assertEquals(Status.Code.CANCELLED, status.getCode());
        // Should have observed 2 cancellations responses from downstream servers
        if (!observedCancellations.await(5, TimeUnit.SECONDS)) {
            fail("Expected number of cancellations not observed by clients");
        }
        if (!receivedCancellations.await(5, TimeUnit.SECONDS)) {
            fail("Expected number of cancellations to be received by servers not observed");
        }
    }
}
Also used : Context(io.grpc.Context) CancellableContext(io.grpc.Context.CancellableContext) Status(io.grpc.Status) CancellableContext(io.grpc.Context.CancellableContext) SimpleResponse(io.grpc.testing.integration.Messages.SimpleResponse) CountDownLatch(java.util.concurrent.CountDownLatch) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Example 2 with SimpleResponse

use of io.grpc.testing.integration.Messages.SimpleResponse 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 3 with SimpleResponse

use of io.grpc.testing.integration.Messages.SimpleResponse in project grpc-java by grpc.

the class CascadingTest method testCascadingCancellationViaRpcCancel.

/**
 * Test that cancellation via call cancellation propagates down the call.
 */
@Test
public void testCascadingCancellationViaRpcCancel() throws Exception {
    observedCancellations = new CountDownLatch(2);
    receivedCancellations = new CountDownLatch(3);
    Future<?> chainReady = startChainingServer(3);
    Future<SimpleResponse> future = futureStub.unaryCall(SimpleRequest.getDefaultInstance());
    chainReady.get(5, TimeUnit.SECONDS);
    future.cancel(true);
    assertTrue(future.isCancelled());
    if (!observedCancellations.await(5, TimeUnit.SECONDS)) {
        fail("Expected number of cancellations not observed by clients");
    }
    if (!receivedCancellations.await(5, TimeUnit.SECONDS)) {
        fail("Expected number of cancellations to be received by servers not observed");
    }
}
Also used : SimpleResponse(io.grpc.testing.integration.Messages.SimpleResponse) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 4 with SimpleResponse

use of io.grpc.testing.integration.Messages.SimpleResponse in project grpc-java by grpc.

the class TransportCompressionTest method compresses.

@Test
public void compresses() {
    expectFzip = true;
    final SimpleRequest request = SimpleRequest.newBuilder().setResponseSize(314159).setResponseCompressed(BoolValue.newBuilder().setValue(true)).setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[271828]))).build();
    final SimpleResponse goldenResponse = SimpleResponse.newBuilder().setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[314159]))).build();
    assertEquals(goldenResponse, blockingStub.unaryCall(request));
    // Assert that compression took place
    assertTrue(FZIPPER.anyRead);
    assertTrue(FZIPPER.anyWritten);
}
Also used : SimpleResponse(io.grpc.testing.integration.Messages.SimpleResponse) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest) Test(org.junit.Test)

Example 5 with SimpleResponse

use of io.grpc.testing.integration.Messages.SimpleResponse in project grpc-java by grpc.

the class LongLivedChannel method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    int requestSize = 1234;
    int responseSize = 5678;
    SimpleRequest request = SimpleRequest.newBuilder().setResponseSize(responseSize).setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[requestSize]))).build();
    TestServiceGrpc.TestServiceBlockingStub blockingStub = TestServiceGrpc.newBlockingStub(channel);
    SimpleResponse simpleResponse = blockingStub.unaryCall(request);
    resp.setContentType("text/plain");
    if (simpleResponse.getPayload().getBody().size() == responseSize) {
        resp.setStatus(200);
        resp.getWriter().println("PASS!");
    } else {
        resp.setStatus(500);
        resp.getWriter().println("FAILED!");
    }
}
Also used : SimpleResponse(io.grpc.testing.integration.Messages.SimpleResponse) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest)

Aggregations

SimpleResponse (io.grpc.testing.integration.Messages.SimpleResponse)24 SimpleRequest (io.grpc.testing.integration.Messages.SimpleRequest)21 Test (org.junit.Test)8 StatusRuntimeException (io.grpc.StatusRuntimeException)4 ByteString (com.google.protobuf.ByteString)3 ManagedChannel (io.grpc.ManagedChannel)3 Metadata (io.grpc.Metadata)3 Status (io.grpc.Status)3 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)2 Channel (io.grpc.Channel)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 AccessToken (com.google.auth.oauth2.AccessToken)1 ComputeEngineCredentials (com.google.auth.oauth2.ComputeEngineCredentials)1 OAuth2Credentials (com.google.auth.oauth2.OAuth2Credentials)1 ServiceAccountCredentials (com.google.auth.oauth2.ServiceAccountCredentials)1 CallOptions (io.grpc.CallOptions)1 ClientCall (io.grpc.ClientCall)1 ClientInterceptor (io.grpc.ClientInterceptor)1 Context (io.grpc.Context)1