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();
}
}
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();
}
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");
}
}
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();
}
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");
}
Aggregations