Search in sources :

Example 61 with ManagedChannel

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

the class Http2OkHttpTest method hostnameVerifierWithCorrectHostname.

@Test
public void hostnameVerifierWithCorrectHostname() throws Exception {
    int port = ((InetSocketAddress) getListenAddress()).getPort();
    ManagedChannel channel = createChannelBuilderPreCredentialsApi().overrideAuthority(GrpcUtil.authorityFromHostAndPort(TestUtils.TEST_SERVER_HOST, port)).hostnameVerifier(new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return false;
        }
    }).build();
    TestServiceGrpc.TestServiceBlockingStub blockingStub = TestServiceGrpc.newBlockingStub(channel);
    Throwable actualThrown = null;
    try {
        blockingStub.emptyCall(Empty.getDefaultInstance());
    } catch (Throwable t) {
        actualThrown = t;
    }
    assertNotNull("The rpc should have been failed due to hostname verification", actualThrown);
    Throwable cause = Throwables.getRootCause(actualThrown);
    assertTrue("Failed by unexpected exception: " + cause, cause instanceof SSLPeerUnverifiedException);
    channel.shutdown();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) SSLSession(javax.net.ssl.SSLSession) ManagedChannel(io.grpc.ManagedChannel) HostnameVerifier(javax.net.ssl.HostnameVerifier) Test(org.junit.Test)

Example 62 with ManagedChannel

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

the class ServerCallsTest method inprocessTransportManualFlow.

@Test
public void inprocessTransportManualFlow() throws Exception {
    final Semaphore semaphore = new Semaphore(1);
    ServerServiceDefinition service = ServerServiceDefinition.builder(new ServiceDescriptor("some", STREAMING_METHOD)).addMethod(STREAMING_METHOD, ServerCalls.asyncBidiStreamingCall(new ServerCalls.BidiStreamingMethod<Integer, Integer>() {

        int iteration;

        @Override
        public StreamObserver<Integer> invoke(StreamObserver<Integer> responseObserver) {
            final ServerCallStreamObserver<Integer> serverCallObserver = (ServerCallStreamObserver<Integer>) responseObserver;
            serverCallObserver.setOnReadyHandler(new Runnable() {

                @Override
                public void run() {
                    while (serverCallObserver.isReady()) {
                        serverCallObserver.onNext(iteration);
                    }
                    iteration++;
                    semaphore.release();
                }
            });
            return new ServerCalls.NoopStreamObserver<Integer>() {

                @Override
                public void onCompleted() {
                    serverCallObserver.onCompleted();
                }
            };
        }
    })).build();
    long tag = System.nanoTime();
    InProcessServerBuilder.forName("go-with-the-flow" + tag).addService(service).build().start();
    ManagedChannel channel = InProcessChannelBuilder.forName("go-with-the-flow" + tag).build();
    final ClientCall<Integer, Integer> clientCall = channel.newCall(STREAMING_METHOD, CallOptions.DEFAULT);
    final CountDownLatch latch = new CountDownLatch(1);
    final int[] receivedMessages = new int[6];
    clientCall.start(new ClientCall.Listener<Integer>() {

        int index;

        @Override
        public void onMessage(Integer message) {
            receivedMessages[index++] = message;
        }

        @Override
        public void onClose(Status status, Metadata trailers) {
            latch.countDown();
        }
    }, new Metadata());
    semaphore.acquire();
    clientCall.request(1);
    semaphore.acquire();
    clientCall.request(2);
    semaphore.acquire();
    clientCall.request(3);
    clientCall.halfClose();
    assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue();
    // Very that number of messages produced in each onReady handler call matches the number
    // requested by the client.
    assertArrayEquals(new int[] { 0, 1, 1, 2, 2, 2 }, receivedMessages);
}
Also used : Status(io.grpc.Status) Metadata(io.grpc.Metadata) Semaphore(java.util.concurrent.Semaphore) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServiceDescriptor(io.grpc.ServiceDescriptor) ClientCall(io.grpc.ClientCall) ServerServiceDefinition(io.grpc.ServerServiceDefinition) ManagedChannel(io.grpc.ManagedChannel) Test(org.junit.Test)

Example 63 with ManagedChannel

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

the class AltsProtocolNegotiatorTest method setup.

@Before
public void setup() throws Exception {
    ChannelHandler uncaughtExceptionHandler = new ChannelDuplexHandler() {

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            caughtException = cause;
            super.exceptionCaught(ctx, cause);
            ctx.close();
        }
    };
    TsiHandshakerFactory handshakerFactory = new DelegatingTsiHandshakerFactory(FakeTsiHandshaker.clientHandshakerFactory()) {

        @Override
        public TsiHandshaker newHandshaker(String authority, ChannelLogger logger) {
            return new DelegatingTsiHandshaker(super.newHandshaker(authority, logger)) {

                @Override
                public TsiPeer extractPeer() throws GeneralSecurityException {
                    return mockedTsiPeer;
                }

                @Override
                public Object extractPeerObject() throws GeneralSecurityException {
                    return mockedAltsContext;
                }
            };
        }
    };
    ManagedChannel fakeChannel = NettyChannelBuilder.forTarget("localhost:8080").build();
    ObjectPool<Channel> fakeChannelPool = new FixedObjectPool<Channel>(fakeChannel);
    LazyChannel lazyFakeChannel = new LazyChannel(fakeChannelPool);
    ChannelHandler altsServerHandler = new ServerAltsProtocolNegotiator(handshakerFactory, lazyFakeChannel).newHandler(grpcHandler);
    // On real server, WBAEH fires default ProtocolNegotiationEvent. KickNH provides this behavior.
    ChannelHandler handler = new KickNegotiationHandler(altsServerHandler);
    channel = new EmbeddedChannel(uncaughtExceptionHandler, handler);
}
Also used : ServerAltsProtocolNegotiator(io.grpc.alts.internal.AltsProtocolNegotiator.ServerAltsProtocolNegotiator) LazyChannel(io.grpc.alts.internal.AltsProtocolNegotiator.LazyChannel) ManagedChannel(io.grpc.ManagedChannel) Channel(io.grpc.Channel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) LazyChannel(io.grpc.alts.internal.AltsProtocolNegotiator.LazyChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ManagedChannel(io.grpc.ManagedChannel) ChannelLogger(io.grpc.ChannelLogger) NoopChannelLogger(io.grpc.internal.TestUtils.NoopChannelLogger) FixedObjectPool(io.grpc.internal.FixedObjectPool) Before(org.junit.Before)

Example 64 with ManagedChannel

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

the class LoggingServerProviderTest method serverBuilder_interceptorCalled.

@SuppressWarnings("unchecked")
private void serverBuilder_interceptorCalled(Supplier<ServerBuilder<?>> serverBuilderSupplier) throws IOException {
    ServerInterceptor interceptor = mock(ServerInterceptor.class, delegatesTo(new NoopInterceptor()));
    InternalLoggingServerInterceptor.Factory factory = mock(InternalLoggingServerInterceptor.Factory.class);
    when(factory.create()).thenReturn(interceptor);
    LoggingServerProvider.init(factory);
    Server server = serverBuilderSupplier.get().addService(new SimpleServiceImpl()).build().start();
    int port = cleanupRule.register(server).getPort();
    ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build();
    SimpleServiceGrpc.SimpleServiceBlockingStub stub = SimpleServiceGrpc.newBlockingStub(cleanupRule.register(channel));
    assertThat(unaryRpc("buddy", stub)).isEqualTo("Hello buddy");
    verify(interceptor).interceptCall(any(ServerCall.class), any(Metadata.class), anyCallHandler());
    LoggingServerProvider.finish();
}
Also used : Server(io.grpc.Server) ServerCall(io.grpc.ServerCall) ServerInterceptor(io.grpc.ServerInterceptor) InternalLoggingServerInterceptor(io.grpc.observability.interceptors.InternalLoggingServerInterceptor) Metadata(io.grpc.Metadata) ManagedChannel(io.grpc.ManagedChannel) SimpleServiceGrpc(io.grpc.testing.protobuf.SimpleServiceGrpc) InternalLoggingServerInterceptor(io.grpc.observability.interceptors.InternalLoggingServerInterceptor)

Example 65 with ManagedChannel

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

the class LoggingChannelProviderTest method forAddress_interceptorCalled.

@Test
public void forAddress_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 = ManagedChannelBuilder.forAddress("localhost", 80);
    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)

Aggregations

ManagedChannel (io.grpc.ManagedChannel)164 Test (org.junit.Test)92 CountDownLatch (java.util.concurrent.CountDownLatch)26 ManagedChannel (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ManagedChannel)26 ArrayList (java.util.ArrayList)20 Metadata (io.grpc.Metadata)18 EquivalentAddressGroup (io.grpc.EquivalentAddressGroup)15 ExecutorService (java.util.concurrent.ExecutorService)13 ByteString (com.google.protobuf.ByteString)12 Status (io.grpc.Status)12 StreamObserver (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver)11 StreamObserver (io.grpc.stub.StreamObserver)10 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)10 BeamFnApi (org.apache.beam.model.fnexecution.v1.BeamFnApi)10 CallOptions (io.grpc.CallOptions)9 Subchannel (io.grpc.LoadBalancer.Subchannel)9 SubchannelPicker (io.grpc.LoadBalancer.SubchannelPicker)9 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)9 Endpoints (org.apache.beam.model.pipeline.v1.Endpoints)9