Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More concise port and TLS configuration #1051

Merged
merged 1 commit into from
Mar 6, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
More concise port and TLS configuration
Motivation:

- A user currently has to specify SessionProtocol when adding a port,
  which increases the chance of specifying incorrect SessionProtocol.
- sslContext() builder methods require SessionProtocol which is
  practically unncessary.
- It would be confusing if Server serves plaintext HTTP when a user
  configured TLS even if he or she did not specify a port. More sensible
  behavior would be serving HTTPS when no port is specified in this case.

Modifications:

- Add http() and https() which supercede most port() methods.
- Add tls() which supercede sslContext() methods.
- Serve HTTPS by default when a user called tls() and no port was
  specified.
- Add log messages that indicates the protocol and local address.
- Deprecate the old methods.
- Update documentation.
- Miscellaneous:
  - Remove redundant `port(0, HTTP)` calls
  - Add `@Nullable` where necessary

Result:

- Fixes #1050
- More user-friendliness
  • Loading branch information
trustin committed Mar 6, 2018
commit 8df57d6d3f04d5020cd6d622743df0a3767e1b88
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ String uriText() {
@Setup
public void startServer() throws Exception {
server = new ServerBuilder()
.port(0, HTTP)
.service("/empty", ((ctx, req) -> HttpResponse.of(HttpStatus.OK)))
.defaultRequestTimeout(Duration.ZERO)
.meterRegistry(NoopMeterRegistry.get())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ protected GithubServiceFutureStub normalFutureClient() {
@Override
protected void setUp() throws Exception {
server = new ServerBuilder()
.port(0, HTTP)
.serviceUnder("/", new GrpcServiceBuilder().addService(new GithubApiService()).build())
.build();
server.start().join();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ public class LargePayloadBenchmark {
@Setup
public void setUp() {
server = new ServerBuilder()
.port(0, HTTP)
.serviceUnder("/", new GrpcServiceBuilder().addService(
new BinaryProxyImplBase() {
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@ public void onComplete() {
@Setup
public void startServer() throws Exception {
ServerBuilder sb = new ServerBuilder()
.port(0, HTTP)
.service("/a", THttpService.of(
(AsyncIface) (name, resultHandler) ->
resultHandler.onComplete(RESPONSE))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import java.util.List;
import java.util.function.Function;

import javax.annotation.Nullable;
import javax.net.ssl.SSLException;

import org.slf4j.Logger;
Expand Down Expand Up @@ -119,7 +120,9 @@ abstract class AbstractVirtualHostBuilder<B extends AbstractVirtualHostBuilder>
private final String defaultHostname;
private final String hostnamePattern;
private final List<ServiceConfig> services = new ArrayList<>();
@Nullable
private SslContext sslContext;
@Nullable
private Function<Service<HttpRequest, HttpResponse>, Service<HttpRequest, HttpResponse>> decorator;

/**
Expand Down Expand Up @@ -162,17 +165,54 @@ abstract class AbstractVirtualHostBuilder<B extends AbstractVirtualHostBuilder>
}

/**
* Sets the {@link SslContext} of this {@link VirtualHost}.
* Configures SSL or TLS of this {@link VirtualHost} with the specified {@link SslContext}.
*/
public B sslContext(SslContext sslContext) {
public B tls(SslContext sslContext) {
this.sslContext = VirtualHost.validateSslContext(requireNonNull(sslContext, "sslContext"));
return self();
}

/**
* Configures SSL or TLS of this {@link VirtualHost} with the specified {@code keyCertChainFile}
* and cleartext {@code keyFile}.
*/
public B tls(File keyCertChainFile, File keyFile) throws SSLException {
tls(keyCertChainFile, keyFile, null);
return self();
}

/**
* Configures SSL or TLS of this {@link VirtualHost} with the specified {@code keyCertChainFile},
* {@code keyFile} and {@code keyPassword}.
*/
public B tls(File keyCertChainFile, File keyFile, @Nullable String keyPassword) throws SSLException {
final SslContextBuilder builder = SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword);

builder.sslProvider(Flags.useOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK);
builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE);
builder.applicationProtocolConfig(HTTPS_ALPN_CFG);

tls(builder.build());
return self();
}

/**
* Sets the {@link SslContext} of this {@link VirtualHost}.
*
* @deprecated Use {@link #tls(SslContext)}.
*/
@Deprecated
public B sslContext(SslContext sslContext) {
return tls(sslContext);
}

/**
* Sets the {@link SslContext} of this {@link VirtualHost} from the specified {@link SessionProtocol},
* {@code keyCertChainFile} and cleartext {@code keyFile}.
*
* @deprecated Use {@link #tls(File, File)}.
*/
@Deprecated
public B sslContext(
SessionProtocol protocol, File keyCertChainFile, File keyFile) throws SSLException {
sslContext(protocol, keyCertChainFile, keyFile, null);
Expand All @@ -182,23 +222,19 @@ public B sslContext(
/**
* Sets the {@link SslContext} of this {@link VirtualHost} from the specified {@link SessionProtocol},
* {@code keyCertChainFile}, {@code keyFile} and {@code keyPassword}.
*
* @deprecated Use {@link #tls(File, File, String)}.
*/
@Deprecated
public B sslContext(
SessionProtocol protocol,
File keyCertChainFile, File keyFile, String keyPassword) throws SSLException {
File keyCertChainFile, File keyFile, @Nullable String keyPassword) throws SSLException {

if (requireNonNull(protocol, "protocol") != SessionProtocol.HTTPS) {
throw new IllegalArgumentException("unsupported protocol: " + protocol);
}

final SslContextBuilder builder = SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword);

builder.sslProvider(Flags.useOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK);
builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE);
builder.applicationProtocolConfig(HTTPS_ALPN_CFG);

sslContext(builder.build());
return self();
return tls(keyCertChainFile, keyFile, keyPassword);
}

/**
Expand Down
43 changes: 15 additions & 28 deletions core/src/main/java/com/linecorp/armeria/server/Server.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@
import io.netty.channel.EventLoopGroup;
import io.netty.handler.ssl.SslContext;
import io.netty.util.DomainNameMapping;
import io.netty.util.DomainNameMappingBuilder;
import io.netty.util.concurrent.FastThreadLocalThread;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GlobalEventExecutor;
Expand All @@ -80,6 +79,7 @@ public final class Server implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(Server.class);

private final ServerConfig config;
@Nullable
private final DomainNameMapping<SslContext> sslContexts;

private final StateManager stateManager = new StateManager();
Expand All @@ -92,6 +92,7 @@ public final class Server implements AutoCloseable {

private final ConnectionLimitingHandler connectionLimitingHandler;

@Nullable
private volatile ServerPort primaryActivePort;

/**
Expand All @@ -100,34 +101,11 @@ public final class Server implements AutoCloseable {
*/
private volatile GracefulShutdownSupport gracefulShutdownSupport = GracefulShutdownSupport.disabled();

Server(ServerConfig config) {
Server(ServerConfig config, @Nullable DomainNameMapping<SslContext> sslContexts) {
this.config = requireNonNull(config, "config");
config.setServer(this);

// Pre-populate the domain name mapping for later matching.
SslContext lastSslContext = null;
for (VirtualHost h: config.virtualHosts()) {
lastSslContext = h.sslContext();
}
this.sslContexts = sslContexts;

if (lastSslContext == null) {
sslContexts = null;
for (ServerPort p: config.ports()) {
if (p.protocol().isTls()) {
throw new IllegalArgumentException("no SSL context specified");
}
}
} else {
final DomainNameMappingBuilder<SslContext>
mappingBuilder = new DomainNameMappingBuilder<>(lastSslContext);
for (VirtualHost h : config.virtualHosts()) {
final SslContext sslCtx = h.sslContext();
if (sslCtx != null) {
mappingBuilder.add(h.hostnamePattern(), sslCtx);
}
}
sslContexts = mappingBuilder.build();
}
config.setServer(this);

// Invoke the serviceAdded() method in Service so that it can keep the reference to this Server or
// add a listener to it.
Expand Down Expand Up @@ -489,7 +467,7 @@ static final class State {
final StateType type;
final CompletableFuture<Void> future;

State(StateType type, CompletableFuture<Void> future) {
State(StateType type, @Nullable CompletableFuture<Void> future) {
this.type = type;
this.future = future;
}
Expand Down Expand Up @@ -653,6 +631,15 @@ public void operationComplete(ChannelFuture f) throws Exception {
primaryActivePort = actualPort;
}

if (localAddress.getAddress().isAnyLocalAddress() ||
localAddress.getAddress().isLoopbackAddress()) {
logger.info("Serving {} at {} - {}://127.0.0.1:{}/",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good change :) FWIW, it might be considered a breaking change as it will result in double-logging for production users of armeria who almost certainly are doing the logging themselves.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious if we should log at DEBUG level.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me just leave this as it is for the sake of beginners' convenience. :-)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I think it's good to use INFO but should probably mention in the release notes.

port.protocol().name(), localAddress,
port.protocol().uriText(), localAddress.getPort());
} else {
logger.info("Serving {} at {}", port.protocol().name(), localAddress);
}

if (remainingPorts.decrementAndGet() == 0) {
completeFuture(startFuture);
}
Expand Down
Loading