org.springframework.boot.web.embedded.undertow.UndertowWebServer Maven / Gradle / Ivy
/*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.web.embedded.undertow;
import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.GracefulShutdownHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xnio.channels.BoundChannel;
import org.springframework.boot.web.server.GracefulShutdownCallback;
import org.springframework.boot.web.server.GracefulShutdownResult;
import org.springframework.boot.web.server.PortInUseException;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.server.WebServerException;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
* {@link WebServer} that can be used to control an Undertow web server. Usually this
* class should be created using the {@link UndertowReactiveWebServerFactory} and not
* directly.
*
* @author Ivan Sopov
* @author Andy Wilkinson
* @author Eddú Meléndez
* @author Christoph Dreis
* @author Brian Clozel
* @since 2.0.0
*/
public class UndertowWebServer implements WebServer {
private static final Log logger = LogFactory.getLog(UndertowWebServer.class);
private final AtomicReference gracefulShutdownCallback = new AtomicReference<>();
private final Object monitor = new Object();
private final Undertow.Builder builder;
private final Iterable httpHandlerFactories;
private final boolean autoStart;
private Undertow undertow;
private volatile boolean started = false;
private volatile GracefulShutdownHandler gracefulShutdown;
private volatile List closeables;
/**
* Create a new {@link UndertowWebServer} instance.
* @param builder the builder
* @param autoStart if the server should be started
*/
public UndertowWebServer(Undertow.Builder builder, boolean autoStart) {
this(builder, Collections.singleton(new CloseableHttpHandlerFactory(null)), autoStart);
}
/**
* Create a new {@link UndertowWebServer} instance.
* @param builder the builder
* @param httpHandlerFactories the handler factories
* @param autoStart if the server should be started
* @since 2.3.0
*/
public UndertowWebServer(Undertow.Builder builder, Iterable httpHandlerFactories,
boolean autoStart) {
this.builder = builder;
this.httpHandlerFactories = httpHandlerFactories;
this.autoStart = autoStart;
}
@Override
public void start() throws WebServerException {
synchronized (this.monitor) {
if (this.started) {
return;
}
try {
if (!this.autoStart) {
return;
}
if (this.undertow == null) {
this.undertow = createUndertowServer();
}
this.undertow.start();
this.started = true;
String message = getStartLogMessage();
logger.info(message);
}
catch (Exception ex) {
try {
PortInUseException.ifPortBindingException(ex, (bindException) -> {
List failedPorts = getConfiguredPorts();
failedPorts.removeAll(getActualPorts());
if (failedPorts.size() == 1) {
throw new PortInUseException(failedPorts.get(0).getNumber());
}
});
throw new WebServerException("Unable to start embedded Undertow", ex);
}
finally {
stopSilently();
}
}
}
}
private void stopSilently() {
try {
if (this.undertow != null) {
this.undertow.stop();
this.closeables.forEach(this::closeSilently);
}
}
catch (Exception ex) {
// Ignore
}
}
private void closeSilently(Closeable closeable) {
try {
closeable.close();
}
catch (Exception ex) {
}
}
private Undertow createUndertowServer() {
this.closeables = new ArrayList<>();
this.gracefulShutdown = null;
HttpHandler handler = createHttpHandler();
this.builder.setHandler(handler);
return this.builder.build();
}
protected HttpHandler createHttpHandler() {
HttpHandler handler = null;
for (HttpHandlerFactory factory : this.httpHandlerFactories) {
handler = factory.getHandler(handler);
if (handler instanceof Closeable) {
this.closeables.add((Closeable) handler);
}
if (handler instanceof GracefulShutdownHandler) {
Assert.isNull(this.gracefulShutdown, "Only a single GracefulShutdownHandler can be defined");
this.gracefulShutdown = (GracefulShutdownHandler) handler;
}
}
return handler;
}
private String getPortsDescription() {
List ports = getActualPorts();
if (!ports.isEmpty()) {
return StringUtils.collectionToDelimitedString(ports, " ");
}
return "unknown";
}
private List getActualPorts() {
List ports = new ArrayList<>();
try {
if (!this.autoStart) {
ports.add(new Port(-1, "unknown"));
}
else {
for (BoundChannel channel : extractChannels()) {
ports.add(getPortFromChannel(channel));
}
}
}
catch (Exception ex) {
// Continue
}
return ports;
}
@SuppressWarnings("unchecked")
private List extractChannels() {
Field channelsField = ReflectionUtils.findField(Undertow.class, "channels");
ReflectionUtils.makeAccessible(channelsField);
return (List) ReflectionUtils.getField(channelsField, this.undertow);
}
private UndertowWebServer.Port getPortFromChannel(BoundChannel channel) {
SocketAddress socketAddress = channel.getLocalAddress();
if (socketAddress instanceof InetSocketAddress) {
Field sslField = ReflectionUtils.findField(channel.getClass(), "ssl");
String protocol = (sslField != null) ? "https" : "http";
return new UndertowWebServer.Port(((InetSocketAddress) socketAddress).getPort(), protocol);
}
return null;
}
private List getConfiguredPorts() {
List ports = new ArrayList<>();
for (Object listener : extractListeners()) {
try {
Port port = getPortFromListener(listener);
if (port.getNumber() != 0) {
ports.add(port);
}
}
catch (Exception ex) {
// Continue
}
}
return ports;
}
@SuppressWarnings("unchecked")
private List