Search in sources :

Example 21 with ServerCredentials

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

the class AbstractBenchmark method setup.

/**
 * Initialize the environment for the executor.
 */
public void setup(ExecutorType clientExecutor, ExecutorType serverExecutor, MessageSize requestSize, MessageSize responseSize, FlowWindowSize windowSize, ChannelType channelType, int maxConcurrentStreams, int channelCount) throws Exception {
    ServerCredentials serverCreds = InsecureServerCredentials.create();
    NettyServerBuilder serverBuilder;
    NettyChannelBuilder channelBuilder;
    if (channelType == ChannelType.LOCAL) {
        LocalAddress address = new LocalAddress("netty-e2e-benchmark");
        serverBuilder = NettyServerBuilder.forAddress(address, serverCreds);
        serverBuilder.channelType(LocalServerChannel.class);
        channelBuilder = NettyChannelBuilder.forAddress(address);
        channelBuilder.channelType(LocalChannel.class);
    } else {
        ServerSocket sock = new ServerSocket();
        // Pick a port using an ephemeral socket.
        sock.bind(new InetSocketAddress(BENCHMARK_ADDR, 0));
        SocketAddress address = sock.getLocalSocketAddress();
        sock.close();
        serverBuilder = NettyServerBuilder.forAddress(address, serverCreds).channelType(NioServerSocketChannel.class);
        channelBuilder = NettyChannelBuilder.forAddress(address).channelType(NioSocketChannel.class);
    }
    if (serverExecutor == ExecutorType.DIRECT) {
        serverBuilder.directExecutor();
    }
    if (clientExecutor == ExecutorType.DIRECT) {
        channelBuilder.directExecutor();
    }
    // Always use a different worker group from the client.
    ThreadFactory serverThreadFactory = new DefaultThreadFactory("STF pool", true);
    serverBuilder.workerEventLoopGroup(new NioEventLoopGroup(0, serverThreadFactory));
    serverBuilder.bossEventLoopGroup(new NioEventLoopGroup(1, serverThreadFactory));
    // Always set connection and stream window size to same value
    serverBuilder.flowControlWindow(windowSize.bytes());
    channelBuilder.flowControlWindow(windowSize.bytes());
    channelBuilder.negotiationType(NegotiationType.PLAINTEXT);
    serverBuilder.maxConcurrentCallsPerConnection(maxConcurrentStreams);
    // Create buffers of the desired size for requests and responses.
    PooledByteBufAllocator alloc = PooledByteBufAllocator.DEFAULT;
    // Use a heap buffer for now, since MessageFramer doesn't know how to directly convert this
    // into a WritableBuffer
    // TODO(carl-mastrangelo): convert this into a regular buffer() call.  See
    // https://github.com/grpc/grpc-java/issues/2062#issuecomment-234646216
    request = alloc.heapBuffer(requestSize.bytes());
    request.writerIndex(request.capacity() - 1);
    response = alloc.heapBuffer(responseSize.bytes());
    response.writerIndex(response.capacity() - 1);
    // Simple method that sends and receives NettyByteBuf
    unaryMethod = MethodDescriptor.<ByteBuf, ByteBuf>newBuilder().setType(MethodType.UNARY).setFullMethodName("benchmark/unary").setRequestMarshaller(new ByteBufOutputMarshaller()).setResponseMarshaller(new ByteBufOutputMarshaller()).build();
    pingPongMethod = unaryMethod.toBuilder().setType(MethodType.BIDI_STREAMING).setFullMethodName("benchmark/pingPong").build();
    flowControlledStreaming = pingPongMethod.toBuilder().setFullMethodName("benchmark/flowControlledStreaming").build();
    // Server implementation of unary & streaming methods
    serverBuilder.addService(ServerServiceDefinition.builder(new ServiceDescriptor("benchmark", unaryMethod, pingPongMethod, flowControlledStreaming)).addMethod(unaryMethod, new ServerCallHandler<ByteBuf, ByteBuf>() {

        @Override
        public ServerCall.Listener<ByteBuf> startCall(final ServerCall<ByteBuf, ByteBuf> call, Metadata headers) {
            call.sendHeaders(new Metadata());
            call.request(1);
            return new ServerCall.Listener<ByteBuf>() {

                @Override
                public void onMessage(ByteBuf message) {
                    // no-op
                    message.release();
                    call.sendMessage(response.slice());
                }

                @Override
                public void onHalfClose() {
                    call.close(Status.OK, new Metadata());
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onComplete() {
                }
            };
        }
    }).addMethod(pingPongMethod, new ServerCallHandler<ByteBuf, ByteBuf>() {

        @Override
        public ServerCall.Listener<ByteBuf> startCall(final ServerCall<ByteBuf, ByteBuf> call, Metadata headers) {
            call.sendHeaders(new Metadata());
            call.request(1);
            return new ServerCall.Listener<ByteBuf>() {

                @Override
                public void onMessage(ByteBuf message) {
                    message.release();
                    call.sendMessage(response.slice());
                    // Request next message
                    call.request(1);
                }

                @Override
                public void onHalfClose() {
                    call.close(Status.OK, new Metadata());
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onComplete() {
                }
            };
        }
    }).addMethod(flowControlledStreaming, new ServerCallHandler<ByteBuf, ByteBuf>() {

        @Override
        public ServerCall.Listener<ByteBuf> startCall(final ServerCall<ByteBuf, ByteBuf> call, Metadata headers) {
            call.sendHeaders(new Metadata());
            call.request(1);
            return new ServerCall.Listener<ByteBuf>() {

                @Override
                public void onMessage(ByteBuf message) {
                    message.release();
                    while (call.isReady()) {
                        call.sendMessage(response.slice());
                    }
                    // Request next message
                    call.request(1);
                }

                @Override
                public void onHalfClose() {
                    call.close(Status.OK, new Metadata());
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onComplete() {
                }

                @Override
                public void onReady() {
                    while (call.isReady()) {
                        call.sendMessage(response.slice());
                    }
                }
            };
        }
    }).build());
    // Build and start the clients and servers
    server = serverBuilder.build();
    server.start();
    channels = new ManagedChannel[channelCount];
    ThreadFactory clientThreadFactory = new DefaultThreadFactory("CTF pool", true);
    for (int i = 0; i < channelCount; i++) {
        // Use a dedicated event-loop for each channel
        channels[i] = channelBuilder.eventLoopGroup(new NioEventLoopGroup(1, clientThreadFactory)).build();
    }
}
Also used : DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) ThreadFactory(java.util.concurrent.ThreadFactory) ServerCallHandler(io.grpc.ServerCallHandler) InetSocketAddress(java.net.InetSocketAddress) Metadata(io.grpc.Metadata) ByteBuf(io.netty.buffer.ByteBuf) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) ServiceDescriptor(io.grpc.ServiceDescriptor) ServerCall(io.grpc.ServerCall) NettyChannelBuilder(io.grpc.netty.NettyChannelBuilder) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NettyServerBuilder(io.grpc.netty.NettyServerBuilder) LocalAddress(io.netty.channel.local.LocalAddress) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerCredentials(io.grpc.ServerCredentials) InsecureServerCredentials(io.grpc.InsecureServerCredentials) ServerSocket(java.net.ServerSocket) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ByteBufOutputMarshaller(io.grpc.benchmarks.ByteBufOutputMarshaller)

Example 22 with ServerCredentials

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

the class XdsHelloWorldServer method main.

public static void main(String[] args) throws IOException, InterruptedException {
    int port = 50051;
    String hostname = null;
    ServerCredentials credentials = InsecureServerCredentials.create();
    if (args.length >= 1 && "--xds-creds".equals(args[0])) {
        // The xDS credentials use the security configured by the xDS server when available. When xDS
        // is not used or when xDS does not provide security configuration, the xDS credentials fall
        // back to other credentials (in this case, InsecureServerCredentials).
        credentials = XdsServerCredentials.create(InsecureServerCredentials.create());
        args = Arrays.copyOfRange(args, 1, args.length);
    }
    if (args.length >= 1) {
        try {
            port = Integer.parseInt(args[0]);
        } catch (NumberFormatException ex) {
            System.err.println("Usage: [--xds-creds] [PORT [HOSTNAME]]");
            System.err.println("");
            System.err.println("  --xds-creds  Use credentials provided by xDS. Defaults to insecure");
            System.err.println("");
            System.err.println("  PORT      The listen port. Defaults to " + port);
            System.err.println("  HOSTNAME  The name clients will see in greet responses. ");
            System.err.println("            Defaults to the machine's hostname");
            System.exit(1);
        }
    }
    if (args.length >= 2) {
        hostname = args[1];
    }
    // Since the main server may be using TLS, we start a second server just for plaintext health
    // checks
    int healthPort = port + 1;
    final HealthStatusManager health = new HealthStatusManager();
    final Server server = XdsServerBuilder.forPort(port, credentials).addService(new HostnameGreeter(hostname)).addService(// convenient for command line tools
    ProtoReflectionService.newInstance()).addService(// allow management servers to monitor health
    health.getHealthService()).build().start();
    final Server healthServer = XdsServerBuilder.forPort(healthPort, InsecureServerCredentials.create()).addService(// allow management servers to monitor health
    health.getHealthService()).build().start();
    System.out.println("Listening on port " + port);
    System.out.println("Plaintext health service listening on port " + healthPort);
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            health.setStatus("", ServingStatus.NOT_SERVING);
            // Start graceful shutdown
            server.shutdown();
            try {
                // Wait for RPCs to complete processing
                if (!server.awaitTermination(30, TimeUnit.SECONDS)) {
                    // That was plenty of time. Let's cancel the remaining RPCs
                    server.shutdownNow();
                    // shutdownNow isn't instantaneous, so give a bit of time to clean resources up
                    // gracefully. Normally this will be well under a second.
                    server.awaitTermination(5, TimeUnit.SECONDS);
                }
                healthServer.shutdownNow();
                healthServer.awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                server.shutdownNow();
                healthServer.shutdownNow();
            }
        }
    });
    // This would normally be tied to the service's dependencies. For example, if HostnameGreeter
    // used a Channel to contact a required service, then when 'channel.getState() ==
    // TRANSIENT_FAILURE' we'd want to set NOT_SERVING. But HostnameGreeter has no dependencies, so
    // hard-coding SERVING is appropriate.
    health.setStatus("", ServingStatus.SERVING);
    server.awaitTermination();
}
Also used : HealthStatusManager(io.grpc.services.HealthStatusManager) Server(io.grpc.Server) ServerCredentials(io.grpc.ServerCredentials) InsecureServerCredentials(io.grpc.InsecureServerCredentials) XdsServerCredentials(io.grpc.xds.XdsServerCredentials)

Example 23 with ServerCredentials

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

the class ProtocolNegotiatorsTest method from_tls_clientAuthRequire_noClientCert.

@Test
public void from_tls_clientAuthRequire_noClientCert() throws Exception {
    ServerCredentials serverCreds = TlsServerCredentials.newBuilder().keyManager(server1Cert, server1Key).trustManager(caCert).clientAuth(TlsServerCredentials.ClientAuth.REQUIRE).build();
    ChannelCredentials channelCreds = TlsChannelCredentials.newBuilder().trustManager(caCert).build();
    Status status = expectFailedHandshake(channelCreds, serverCreds);
    assertEquals(Status.Code.UNAVAILABLE, status.getCode());
    StatusException sre = status.asException();
    // because of netty/netty#11604 we need to check for both TLSv1.2 and v1.3 behaviors
    if (sre.getCause() instanceof SSLHandshakeException) {
        assertThat(sre).hasCauseThat().isInstanceOf(SSLHandshakeException.class);
        assertThat(sre).hasCauseThat().hasMessageThat().contains("SSLV3_ALERT_HANDSHAKE_FAILURE");
    } else {
        // Client cert verification is after handshake in TLSv1.3
        assertThat(sre).hasCauseThat().hasCauseThat().isInstanceOf(SSLException.class);
        assertThat(sre).hasCauseThat().hasMessageThat().contains("CERTIFICATE_REQUIRED");
    }
}
Also used : Status(io.grpc.Status) StatusException(io.grpc.StatusException) InsecureServerCredentials(io.grpc.InsecureServerCredentials) TlsServerCredentials(io.grpc.TlsServerCredentials) ChoiceServerCredentials(io.grpc.ChoiceServerCredentials) ServerCredentials(io.grpc.ServerCredentials) ChoiceChannelCredentials(io.grpc.ChoiceChannelCredentials) TlsChannelCredentials(io.grpc.TlsChannelCredentials) InsecureChannelCredentials(io.grpc.InsecureChannelCredentials) ChannelCredentials(io.grpc.ChannelCredentials) CompositeChannelCredentials(io.grpc.CompositeChannelCredentials) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Test(org.junit.Test)

Example 24 with ServerCredentials

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

the class ProtocolNegotiatorsTest method from_tls_managers.

@Test
public void from_tls_managers() throws Exception {
    SelfSignedCertificate cert = new SelfSignedCertificate(TestUtils.TEST_SERVER_HOST);
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null);
    keyStore.setKeyEntry("mykey", cert.key(), new char[0], new Certificate[] { cert.cert() });
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, new char[0]);
    KeyStore certStore = KeyStore.getInstance(KeyStore.getDefaultType());
    certStore.load(null);
    certStore.setCertificateEntry("mycert", cert.cert());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(certStore);
    ServerCredentials serverCreds = TlsServerCredentials.newBuilder().keyManager(keyManagerFactory.getKeyManagers()).trustManager(trustManagerFactory.getTrustManagers()).clientAuth(TlsServerCredentials.ClientAuth.REQUIRE).build();
    ChannelCredentials channelCreds = TlsChannelCredentials.newBuilder().keyManager(keyManagerFactory.getKeyManagers()).trustManager(trustManagerFactory.getTrustManagers()).build();
    InternalChannelz.Tls tls = expectSuccessfulHandshake(channelCreds, serverCreds);
    assertThat(((X509Certificate) tls.remoteCert).getSubjectX500Principal().getName()).isEqualTo("CN=" + TestUtils.TEST_SERVER_HOST);
    cert.delete();
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) InsecureServerCredentials(io.grpc.InsecureServerCredentials) TlsServerCredentials(io.grpc.TlsServerCredentials) ChoiceServerCredentials(io.grpc.ChoiceServerCredentials) ServerCredentials(io.grpc.ServerCredentials) ChoiceChannelCredentials(io.grpc.ChoiceChannelCredentials) TlsChannelCredentials(io.grpc.TlsChannelCredentials) InsecureChannelCredentials(io.grpc.InsecureChannelCredentials) ChannelCredentials(io.grpc.ChannelCredentials) CompositeChannelCredentials(io.grpc.CompositeChannelCredentials) InternalChannelz(io.grpc.InternalChannelz) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) KeyStore(java.security.KeyStore) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) Test(org.junit.Test)

Example 25 with ServerCredentials

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

the class ProtocolNegotiatorsTest method from_tls_clientAuthRequire_clientCert.

@Test
public void from_tls_clientAuthRequire_clientCert() throws Exception {
    ServerCredentials serverCreds = TlsServerCredentials.newBuilder().keyManager(server1Cert, server1Key).trustManager(caCert).clientAuth(TlsServerCredentials.ClientAuth.REQUIRE).build();
    ChannelCredentials channelCreds = TlsChannelCredentials.newBuilder().keyManager(server1Cert, server1Key).trustManager(caCert).build();
    InternalChannelz.Tls tls = expectSuccessfulHandshake(channelCreds, serverCreds);
    assertThat(((X509Certificate) tls.remoteCert).getSubjectX500Principal().getName()).contains("CN=*.test.google.com");
}
Also used : InsecureServerCredentials(io.grpc.InsecureServerCredentials) TlsServerCredentials(io.grpc.TlsServerCredentials) ChoiceServerCredentials(io.grpc.ChoiceServerCredentials) ServerCredentials(io.grpc.ServerCredentials) ChoiceChannelCredentials(io.grpc.ChoiceChannelCredentials) TlsChannelCredentials(io.grpc.TlsChannelCredentials) InsecureChannelCredentials(io.grpc.InsecureChannelCredentials) ChannelCredentials(io.grpc.ChannelCredentials) CompositeChannelCredentials(io.grpc.CompositeChannelCredentials) InternalChannelz(io.grpc.InternalChannelz) Test(org.junit.Test)

Aggregations

ServerCredentials (io.grpc.ServerCredentials)27 TlsServerCredentials (io.grpc.TlsServerCredentials)21 InsecureServerCredentials (io.grpc.InsecureServerCredentials)16 Test (org.junit.Test)16 ChannelCredentials (io.grpc.ChannelCredentials)14 TlsChannelCredentials (io.grpc.TlsChannelCredentials)13 ChoiceServerCredentials (io.grpc.ChoiceServerCredentials)10 InsecureChannelCredentials (io.grpc.InsecureChannelCredentials)8 ChoiceChannelCredentials (io.grpc.ChoiceChannelCredentials)7 CompositeChannelCredentials (io.grpc.CompositeChannelCredentials)7 StatusRuntimeException (io.grpc.StatusRuntimeException)7 InternalChannelz (io.grpc.InternalChannelz)6 SimpleServiceGrpc (io.grpc.testing.protobuf.SimpleServiceGrpc)6 AdvancedTlsX509KeyManager (io.grpc.util.AdvancedTlsX509KeyManager)5 AdvancedTlsX509TrustManager (io.grpc.util.AdvancedTlsX509TrustManager)5 NettyServerBuilder (io.grpc.netty.NettyServerBuilder)4 InternalNettyServerBuilder (io.grpc.netty.InternalNettyServerBuilder)3 AltsServerCredentials (io.grpc.alts.AltsServerCredentials)2 SslSocketAndEnginePeerVerifier (io.grpc.util.AdvancedTlsX509TrustManager.SslSocketAndEnginePeerVerifier)2 LocalAddress (io.netty.channel.local.LocalAddress)2