Search in sources :

Example 1 with ProxyHandler

use of io.undertow.server.handlers.proxy.ProxyHandler in project runwar by cfmlprojects.

the class Start method main.

public static void main(String[] args) throws Exception {
    System.setProperty("log4j.configuration", "log4j.filelog.xml");
    ServerOptions serverOptions = CommandLineHandler.parseLogArguments(args);
    LoggerFactory.init(serverOptions);
    if (args.length == 0) {
        if (new File("server.json").exists()) {
            serverOptions = new ConfigParser(new File("server.json")).getServerOptions();
        } else {
            // print usage
            serverOptions = CommandLineHandler.parseArguments(args);
        }
    } else {
        serverOptions = CommandLineHandler.parseArguments(args);
    }
    if (serverOptions.getLoadBalance() != null && serverOptions.getLoadBalance().length > 0) {
        final List<String> balanceHosts = new ArrayList<String>();
        RunwarLogger.LOG.info("Initializing...");
        final LoadBalancingProxyClient loadBalancer = new LoadBalancingProxyClient();
        for (String balanceHost : serverOptions.getLoadBalance()) {
            if (serverOptions.getWarFile() != null) {
                RunwarLogger.LOG.info("Starting instance of " + serverOptions.getWarFile().getParent() + "...");
                launchServer(balanceHost, serverOptions);
            }
            loadBalancer.addHost(new URI(balanceHost));
            balanceHosts.add(balanceHost);
            RunwarLogger.LOG.info("Added balanced host: " + balanceHost);
            Thread.sleep(3000);
        }
        int port = serverOptions.getPortNumber();
        loadBalancer.setConnectionsPerThread(20);
        RunwarLogger.LOG.info("Hosts loaded");
        RunwarLogger.LOG.info("Starting load balancer on 127.0.0.1 port " + port + "...");
        ProxyHandler proxyHandler = ProxyHandler.builder().setProxyClient(loadBalancer).setMaxRequestTime(30000).setNext(ResponseCodeHandler.HANDLE_404).build();
        Undertow reverseProxy = Undertow.builder().addHttpListener(port, "localhost").setIoThreads(4).setHandler(proxyHandler).build();
        reverseProxy.start();
        RunwarLogger.LOG.info("View balancer admin on http://127.0.0.1:9080");
        Undertow adminServer = Undertow.builder().addHttpListener(9080, "localhost").setHandler(new HttpHandler() {

            @Override
            public void handleRequest(final HttpServerExchange exchange) throws Exception {
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
                if (exchange.getQueryParameters().get("addHost") != null) {
                    String balanceHost = URLDecoder.decode(exchange.getQueryParameters().get("addHost").toString(), "UTF-8");
                    balanceHost = balanceHost.replaceAll("]|\\[", "");
                    loadBalancer.addHost(new URI(balanceHost));
                    balanceHosts.add(balanceHost);
                }
                if (exchange.getQueryParameters().get("removeHost") != null) {
                    String balanceHost = URLDecoder.decode(exchange.getQueryParameters().get("removeHost").toString(), "UTF-8");
                    balanceHost = balanceHost.replaceAll("]|\\[", "");
                    loadBalancer.removeHost(new URI(balanceHost));
                    balanceHosts.remove(balanceHost);
                }
                String response = "";
                // response += URLDecoder.decode(exchange.getQueryString(),"UTF-8");
                for (String balanceHost : balanceHosts) {
                    String[] schemeHostAndPort = balanceHost.split(":");
                    String host = schemeHostAndPort[1].replaceAll("^//", "");
                    int port = schemeHostAndPort.length > 2 ? Integer.parseInt(schemeHostAndPort[2]) : 80;
                    response += balanceHost + " <a href='?removeHost=" + balanceHost + "'>remove</a> Listening: " + serverListening(host, port) + "<br/>";
                }
                exchange.getResponseSender().send("<h3>Balanced Hosts</h3><form action='?'> Add Host:<input type='text' name='addHost' placeholder='http://127.0.0.1:7070'><input type='submit'></form>" + response);
            }
        }).build();
        adminServer.start();
        RunwarLogger.LOG.info("Started load balancer.");
    } else {
        Server server = new Server();
        try {
            server.startServer(serverOptions);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
Also used : HttpHandler(io.undertow.server.HttpHandler) ProxyHandler(io.undertow.server.handlers.proxy.ProxyHandler) ArrayList(java.util.ArrayList) ConfigParser(runwar.options.ConfigParser) URI(java.net.URI) LoadBalancingProxyClient(io.undertow.server.handlers.proxy.LoadBalancingProxyClient) HttpServerExchange(io.undertow.server.HttpServerExchange) ServerOptions(runwar.options.ServerOptions) File(java.io.File) Undertow(io.undertow.Undertow)

Example 2 with ProxyHandler

use of io.undertow.server.handlers.proxy.ProxyHandler in project undertow by undertow-io.

the class DefaultServer method runInternal.

private static void runInternal(final RunNotifier notifier) {
    if (openssl && OPENSSL_FAILURE != null) {
        throw new RuntimeException(OPENSSL_FAILURE);
    }
    if (first) {
        first = false;
        xnio = Xnio.getInstance("nio", DefaultServer.class.getClassLoader());
        try {
            worker = xnio.createWorker(OptionMap.builder().set(Options.WORKER_IO_THREADS, 8).set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, 30).set(Options.WORKER_TASK_MAX_THREADS, 30).set(Options.TCP_NODELAY, true).set(Options.CORK, true).getMap());
            serverOptions = OptionMap.builder().set(Options.TCP_NODELAY, true).set(Options.BACKLOG, 1000).set(Options.REUSE_ADDRESSES, true).set(Options.BALANCING_TOKENS, 1).set(Options.BALANCING_CONNECTIONS, 2).getMap();
            final SSLContext serverContext = createSSLContext(loadKeyStore(SERVER_KEY_STORE), loadKeyStore(SERVER_TRUST_STORE), false);
            UndertowXnioSsl ssl = new UndertowXnioSsl(worker.getXnio(), OptionMap.EMPTY, SSL_BUFFER_POOL, serverContext);
            if (ajp) {
                openListener = new AjpOpenListener(pool);
                acceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(openListener));
                if (apache) {
                    int port = 8888;
                    server = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), port), acceptListener, serverOptions);
                } else {
                    server = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), 7777 + PROXY_OFFSET), acceptListener, serverOptions);
                    proxyOpenListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.BUFFER_PIPELINED_DATA, true));
                    proxyAcceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(proxyOpenListener));
                    proxyServer = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), proxyAcceptListener, serverOptions);
                    proxyOpenListener.setRootHandler(new ProxyHandler(loadBalancingProxyClient = new LoadBalancingProxyClient(GSSAPIAuthenticationMechanism.EXCLUSIVITY_CHECKER).addHost(new URI("ajp", null, getHostAddress(DEFAULT), getHostPort(DEFAULT) + PROXY_OFFSET, "/", null, null)), 120000, HANDLE_404));
                    proxyServer.resumeAccepts();
                }
            } else if (h2 && isAlpnEnabled()) {
                openListener = new Http2OpenListener(pool, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true, UndertowOptions.HTTP2_PADDING_SIZE, 10));
                acceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(new AlpnOpenListener(pool).addProtocol(Http2OpenListener.HTTP2, (io.undertow.server.DelegateOpenListener) openListener, 10)));
                SSLContext clientContext = createSSLContext(loadKeyStore(CLIENT_KEY_STORE), loadKeyStore(CLIENT_TRUST_STORE), true);
                server = ssl.createSslConnectionServer(worker, new InetSocketAddress(getHostAddress("default"), 7777 + PROXY_OFFSET), acceptListener, serverOptions);
                server.resumeAccepts();
                proxyOpenListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.BUFFER_PIPELINED_DATA, true));
                proxyAcceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(proxyOpenListener));
                proxyServer = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), proxyAcceptListener, serverOptions);
                ProxyHandler proxyHandler = new ProxyHandler(loadBalancingProxyClient = new LoadBalancingProxyClient(GSSAPIAuthenticationMechanism.EXCLUSIVITY_CHECKER).addHost(new URI("h2", null, getHostAddress(DEFAULT), getHostPort(DEFAULT) + PROXY_OFFSET, "/", null, null), null, new UndertowXnioSsl(xnio, OptionMap.EMPTY, SSL_BUFFER_POOL, clientContext), OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)), 120000, HANDLE_404);
                setupProxyHandlerForSSL(proxyHandler);
                proxyOpenListener.setRootHandler(proxyHandler);
                proxyServer.resumeAccepts();
            } else if (h2c || h2cUpgrade) {
                openListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true, UndertowOptions.HTTP2_PADDING_SIZE, 10));
                acceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(openListener));
                InetSocketAddress targetAddress = new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT) + PROXY_OFFSET);
                server = worker.createStreamConnectionServer(targetAddress, acceptListener, serverOptions);
                proxyOpenListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.BUFFER_PIPELINED_DATA, true));
                proxyAcceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(proxyOpenListener));
                proxyServer = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), proxyAcceptListener, serverOptions);
                ProxyHandler proxyHandler = new ProxyHandler(loadBalancingProxyClient = new LoadBalancingProxyClient(GSSAPIAuthenticationMechanism.EXCLUSIVITY_CHECKER).addHost(new URI(h2cUpgrade ? "http" : "h2c-prior", null, getHostAddress(DEFAULT), getHostPort(DEFAULT) + PROXY_OFFSET, "/", null, null), null, null, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)), 30000, HANDLE_404);
                setupProxyHandlerForSSL(proxyHandler);
                proxyOpenListener.setRootHandler(proxyHandler);
                proxyServer.resumeAccepts();
            } else if (https) {
                XnioSsl clientSsl = new UndertowXnioSsl(xnio, OptionMap.EMPTY, SSL_BUFFER_POOL, createClientSslContext());
                openListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.BUFFER_PIPELINED_DATA, true));
                acceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(openListener));
                server = ssl.createSslConnectionServer(worker, new InetSocketAddress(getHostAddress("default"), 7777 + PROXY_OFFSET), acceptListener, serverOptions);
                server.getAcceptSetter().set(acceptListener);
                server.resumeAccepts();
                proxyOpenListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.BUFFER_PIPELINED_DATA, true));
                proxyAcceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(proxyOpenListener));
                proxyServer = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), proxyAcceptListener, serverOptions);
                ProxyHandler proxyHandler = new ProxyHandler(loadBalancingProxyClient = new LoadBalancingProxyClient(GSSAPIAuthenticationMechanism.EXCLUSIVITY_CHECKER).addHost(new URI("https", null, getHostAddress(DEFAULT), getHostPort(DEFAULT) + PROXY_OFFSET, "/", null, null), clientSsl), 30000, HANDLE_404);
                setupProxyHandlerForSSL(proxyHandler);
                proxyOpenListener.setRootHandler(proxyHandler);
                proxyServer.resumeAccepts();
            } else {
                if (h2) {
                    UndertowLogger.ROOT_LOGGER.error("HTTP2 selected but Netty ALPN was not on the boot class path");
                }
                openListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.BUFFER_PIPELINED_DATA, true, UndertowOptions.ENABLE_CONNECTOR_STATISTICS, true));
                acceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(openListener));
                if (!proxy) {
                    server = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), acceptListener, serverOptions);
                } else {
                    InetSocketAddress targetAddress = new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT) + PROXY_OFFSET);
                    server = worker.createStreamConnectionServer(targetAddress, acceptListener, serverOptions);
                    proxyOpenListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.BUFFER_PIPELINED_DATA, true));
                    proxyAcceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(proxyOpenListener));
                    proxyServer = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), proxyAcceptListener, serverOptions);
                    ProxyHandler proxyHandler = new ProxyHandler(loadBalancingProxyClient = new LoadBalancingProxyClient(GSSAPIAuthenticationMechanism.EXCLUSIVITY_CHECKER).addHost(new URI("http", null, getHostAddress(DEFAULT), getHostPort(DEFAULT) + PROXY_OFFSET, "/", null, null)), 30000, HANDLE_404);
                    setupProxyHandlerForSSL(proxyHandler);
                    proxyOpenListener.setRootHandler(proxyHandler);
                    proxyServer.resumeAccepts();
                }
            }
            if (h2cUpgrade) {
                openListener.setRootHandler(new Http2UpgradeHandler(rootHandler));
            } else {
                openListener.setRootHandler(rootHandler);
            }
            server.resumeAccepts();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        notifier.addListener(new RunListener() {

            @Override
            public void testRunFinished(final Result result) throws Exception {
                server.close();
                stopSSLServer();
                worker.shutdown();
            }
        });
    }
}
Also used : AlpnOpenListener(io.undertow.server.protocol.http.AlpnOpenListener) XnioSsl(org.xnio.ssl.XnioSsl) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) Http2UpgradeHandler(io.undertow.server.protocol.http2.Http2UpgradeHandler) ProxyHandler(io.undertow.server.handlers.proxy.ProxyHandler) InetSocketAddress(java.net.InetSocketAddress) Xnio(org.xnio.Xnio) SSLContext(javax.net.ssl.SSLContext) Http2OpenListener(io.undertow.server.protocol.http2.Http2OpenListener) URI(java.net.URI) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) LoadBalancingProxyClient(io.undertow.server.handlers.proxy.LoadBalancingProxyClient) RunListener(org.junit.runner.notification.RunListener) Result(org.junit.runner.Result) AjpOpenListener(io.undertow.server.protocol.ajp.AjpOpenListener) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) HttpOpenListener(io.undertow.server.protocol.http.HttpOpenListener)

Example 3 with ProxyHandler

use of io.undertow.server.handlers.proxy.ProxyHandler in project runwar by cfmlprojects.

the class Server method startServer.

public synchronized void startServer(final ServerOptions options) throws Exception {
    serverOptions = (ServerOptionsImpl) options;
    LoggerFactory.init(serverOptions);
    serverState = ServerState.STARTING;
    if (serverOptions.getAction().equals("stop")) {
        Stop.stopServer(serverOptions, true);
    }
    serverName = serverOptions.getServerName();
    portNumber = serverOptions.getPortNumber();
    socketNumber = serverOptions.getSocketNumber();
    String cfengine = serverOptions.getCFEngineName();
    String processName = serverOptions.getProcessName();
    String contextPath = serverOptions.getContextPath();
    String host = serverOptions.getHost();
    File warFile = serverOptions.getWarFile();
    if (serverOptions.getStatusFile() != null) {
        statusFile = serverOptions.getStatusFile();
    }
    String warPath = serverOptions.getWarPath();
    char[] stoppassword = serverOptions.getStopPassword();
    boolean ignoreWelcomePages = false;
    boolean ignoreRestMappings = false;
    LOG.info("Starting RunWAR " + getVersion());
    // unset this so thing that reconfigure will find theirs
    System.setProperty("log4j.configuration", "");
    ensureJavaVersion();
    securityManager = new SecurityManager();
    if (serverOptions.isBackground()) {
        setServerState(ServerState.STARTING_BACKGROUND);
        // this will eventually system.exit();
        LaunchUtil.relaunchAsBackgroundProcess(serverOptions.setBackground(false), true);
        setServerState(ServerState.STARTED_BACKGROUND);
        // just in case
        Thread.sleep(200);
        System.exit(0);
    }
    // if the war is archived, unpack it to system temp
    if (warFile.exists() && !warFile.isDirectory()) {
        URL zipResource = warFile.toURI().toURL();
        String warDir = warFile.getName().toLowerCase().replace(".war", "");
        warFile = new File(warFile.getParentFile(), warDir);
        if (!warFile.exists()) {
            warFile.mkdir();
            LOG.debug("Exploding compressed WAR to " + warFile.getAbsolutePath());
            LaunchUtil.unzipResource(zipResource, warFile, false);
        } else {
            LOG.debug("Using already exploded WAR in " + warFile.getAbsolutePath());
        }
        warPath = warFile.getAbsolutePath();
        if (serverOptions.getWarFile().getAbsolutePath().equals(serverOptions.getCfmlDirs())) {
            serverOptions.setCfmlDirs(warFile.getAbsolutePath());
        }
    }
    if (!warFile.exists()) {
        throw new RuntimeException("war does not exist: " + warFile.getAbsolutePath());
    }
    File webinf = serverOptions.getWebInfDir();
    File webXmlFile = serverOptions.getWebXmlFile();
    String libDirs = serverOptions.getLibDirs();
    URL jarURL = serverOptions.getJarURL();
    // If this folder is a proper war, add its WEB-INF/lib folder to the passed libDirs
    if (warFile.isDirectory() && webXmlFile != null && webXmlFile.exists()) {
        if (libDirs == null) {
            libDirs = "";
        } else if (libDirs.length() > 0) {
            libDirs = libDirs + ",";
        }
        libDirs = libDirs + webinf.getAbsolutePath() + "/lib";
        LOG.info("Adding additional lib dir of: " + webinf.getAbsolutePath() + "/lib");
    }
    List<URL> cp = new ArrayList<URL>();
    // cp.add(Server.class.getProtectionDomain().getCodeSource().getLocation());
    if (libDirs != null)
        cp.addAll(getJarList(libDirs));
    if (jarURL != null)
        cp.add(jarURL);
    if (serverOptions.getMariaDB4jImportSQLFile() != null) {
        System.out.println("ADDN" + serverOptions.getMariaDB4jImportSQLFile().toURI().toURL());
        cp.add(serverOptions.getMariaDB4jImportSQLFile().toURI().toURL());
    }
    cp.addAll(getClassesList(new File(webinf, "/classes")));
    initClassLoader(cp);
    serverMode = Mode.WAR;
    if (!webinf.exists()) {
        serverMode = Mode.DEFAULT;
        if (getCFMLServletClass(cfengine) != null) {
            serverMode = Mode.SERVLET;
        }
    }
    LOG.debugf("Server Mode: %s", serverMode);
    sysOutTee = null;
    sysErrTee = null;
    String osName = System.getProperties().getProperty("os.name");
    String iconPNG = System.getProperty("cfml.server.trayicon");
    if (iconPNG != null && iconPNG.length() > 0) {
        serverOptions.setIconImage(iconPNG);
    }
    String dockIconPath = System.getProperty("cfml.server.dockicon");
    if (dockIconPath == null || dockIconPath.length() == 0) {
        dockIconPath = serverOptions.getIconImage();
    }
    if (osName != null && osName.startsWith("Mac OS X")) {
        Image dockIcon = Tray.getIconImage(dockIconPath);
        System.setProperty("com.apple.mrj.application.apple.menu.about.name", processName);
        System.setProperty("com.apple.mrj.application.growbox.intrudes", "false");
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        System.setProperty("-Xdock:name", processName);
        try {
            Class<?> appClass = Class.forName("com.apple.eawt.Application");
            Method getAppMethod = appClass.getMethod("getApplication");
            Object appInstance = getAppMethod.invoke(null);
            Method dockMethod = appInstance.getClass().getMethod("setDockIconImage", java.awt.Image.class);
            dockMethod.invoke(appInstance, dockIcon);
        } catch (Exception e) {
            LOG.warn("error setting dock icon image", e);
        }
    }
    LOG.info(bar);
    LOG.info("Starting - port:" + portNumber + " stop-port:" + socketNumber + " warpath:" + warPath);
    LOG.info("context: " + contextPath + "  -  version: " + getVersion());
    String cfmlDirs = serverOptions.getCfmlDirs();
    if (cfmlDirs.length() > 0) {
        LOG.info("web-dirs: " + cfmlDirs);
    }
    LOG.info("Log Directory: " + serverOptions.getLogDir().getAbsolutePath());
    LOG.info(bar);
    addShutDownHook();
    portNumber = getPortOrErrorOut(portNumber, host);
    socketNumber = getPortOrErrorOut(socketNumber, host);
    LOG.info("Adding mariadb manager");
    mariadb4jManager = new MariaDB4jManager(_classLoader);
    if (serverOptions.getWelcomeFiles() != null && serverOptions.getWelcomeFiles().length > 0) {
        ignoreWelcomePages = true;
    } else {
        serverOptions.setWelcomeFiles(defaultWelcomeFiles);
    }
    if (serverOptions.getServletRestMappings() != null && serverOptions.getServletRestMappings().length > 0) {
        ignoreRestMappings = true;
    }
    LOG.debug("Transfer Min Size: " + serverOptions.getTransferMinSize());
    xnio = Xnio.getInstance("nio", Server.class.getClassLoader());
    worker = xnio.createWorker(OptionMap.builder().set(Options.WORKER_IO_THREADS, 8).set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, 30).set(Options.WORKER_TASK_MAX_THREADS, 30).set(Options.TCP_NODELAY, true).set(Options.CORK, true).getMap());
    final DeploymentInfo servletBuilder = deployment().setContextPath(contextPath.equals("/") ? "" : contextPath).setTempDir(new File(System.getProperty("java.io.tmpdir"))).setDeploymentName(warPath).setServerName("WildFly / Undertow");
    // hack to prevent . being picked up as the system path (jacob.x.dll)
    if (System.getProperty("java.library.path") == null) {
        if (webXmlFile != null) {
            System.setProperty("java.library.path", getThisJarLocation().getPath() + ':' + new File(webXmlFile.getParentFile(), "lib").getPath());
        } else {
            System.setProperty("java.library.path", getThisJarLocation().getPath() + ':' + new File(warFile, "/WEB-INF/lib/").getPath());
        }
    } else {
        System.setProperty("java.library.path", getThisJarLocation().getPath() + System.getProperty("path.separator") + System.getProperty("java.library.path"));
    }
    LOG.trace("java.library.path:" + System.getProperty("java.library.path"));
    final SessionCookieConfig sessionConfig = new SessionCookieConfig();
    final SessionAttachmentHandler sessionAttachmentHandler = new SessionAttachmentHandler(new InMemorySessionManager("", 1, true), sessionConfig);
    configureServerResourceHandler(servletBuilder, sessionConfig, warFile, webinf, webXmlFile, cfmlDirs, cfengine, ignoreWelcomePages, ignoreRestMappings);
    if (cfengine.equals("adobe")) {
        String cfclassesDir = (String) servletBuilder.getServletContextAttributes().get("coldfusion.compiler.outputDir");
        if (cfclassesDir == null || cfclassesDir.startsWith("/WEB-INF")) {
            // TODO: figure out why adobe needs the absolute path, vs. /WEB-INF/cfclasses
            File cfclassesDirFile = new File(webinf, "/cfclasses");
            cfclassesDir = cfclassesDirFile.getAbsolutePath();
            LOG.debug("ADOBE - coldfusion.compiler.outputDir set to " + cfclassesDir);
            if (!cfclassesDirFile.exists()) {
                cfclassesDirFile.mkdir();
            }
            servletBuilder.addServletContextAttribute("coldfusion.compiler.outputDir", cfclassesDir);
        }
    }
    if (serverOptions.isEnableBasicAuth()) {
        securityManager.configureAuth(servletBuilder, serverOptions);
    }
    configureURLRewrite(servletBuilder, webinf);
    configurePathInfoFilter(servletBuilder);
    if (serverOptions.isCacheEnabled()) {
        addCacheHandler(servletBuilder);
    } else {
        LOG.debug("File cache is disabled");
    }
    if (serverOptions.isCustomHTTPStatusEnabled()) {
        servletBuilder.setSendCustomReasonPhraseOnError(true);
    }
    if (serverOptions.getErrorPages() != null) {
        for (Integer errorCode : serverOptions.getErrorPages().keySet()) {
            String location = serverOptions.getErrorPages().get(errorCode);
            if (errorCode == 1) {
                servletBuilder.addErrorPage(new ErrorPage(location));
                LOG.debug("Adding default error location: " + location);
            } else {
                servletBuilder.addErrorPage(new ErrorPage(location, errorCode));
                LOG.debug("Adding " + errorCode + " error code location: " + location);
            }
        }
    }
    // someday we may wanna listen for changes
    /*
        servletBuilder.getResourceManager().registerResourceChangeListener(new ResourceChangeListener() {
            @Override
            public void handleChanges(Collection<ResourceChangeEvent> changes) {
                for(ResourceChangeEvent change : changes) {
                    RunwarLogger.ROOT_LOGGER.info("CHANGE");
                    RunwarLogger.ROOT_LOGGER.info(change.getResource());
                    RunwarLogger.ROOT_LOGGER.info(change.getType().name());
                    manager.getDeployment().getServletPaths().invalidate();
                }
            }
        });
        */
    // this prevents us from having to use our own ResourceHandler (directory listing, welcome files, see below) and error handler for now
    servletBuilder.addServlet(new ServletInfo(io.undertow.servlet.handlers.ServletPathMatches.DEFAULT_SERVLET_NAME, DefaultServlet.class).addInitParam("directory-listing", Boolean.toString(serverOptions.isDirectoryListingEnabled())));
    // servletBuilder.setExceptionHandler(LoggingExceptionHandler.DEFAULT);
    List<?> welcomePages = servletBuilder.getWelcomePages();
    if (ignoreWelcomePages) {
        LOG.debug("Ignoring web.xml welcome file, so adding server options welcome files to deployment manager.");
        servletBuilder.addWelcomePages(serverOptions.getWelcomeFiles());
    } else if (welcomePages.size() == 0) {
        LOG.debug("No welcome pages set yet, so adding defaults to deployment manager.");
        servletBuilder.addWelcomePages(defaultWelcomeFiles);
    }
    LOG.info("welcome pages in deployment manager: " + servletBuilder.getWelcomePages());
    if (ignoreRestMappings) {
        LOG.info("Overriding web.xml rest mappings with " + Arrays.toString(serverOptions.getServletRestMappings()));
        Iterator<Entry<String, ServletInfo>> it = servletBuilder.getServlets().entrySet().iterator();
        while (it.hasNext()) {
            ServletInfo restServlet = it.next().getValue();
            LOG.trace("Checking servelet named: " + restServlet.getName() + "to see if it's a REST servlet.");
            if (restServlet.getName().toLowerCase().equals("restservlet") || restServlet.getName().toLowerCase().equals("cfrestservlet")) {
                for (String path : serverOptions.getServletRestMappings()) {
                    restServlet.addMapping(path);
                    LOG.info("Added rest mapping: " + path + " to " + restServlet.getName());
                }
            }
        }
    }
    // TODO: probably best to create a new worker for websockets, if we want fastness, but for now we share
    // TODO: add buffer pool size (maybe-- direct is best at 16k), enable/disable be good I reckon tho
    servletBuilder.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, new WebSocketDeploymentInfo().setBuffers(new DefaultByteBufferPool(true, 1024 * 16)).setWorker(worker));
    LOG.debug("Added websocket context");
    manager = defaultContainer().addDeployment(servletBuilder);
    manager.deploy();
    HttpHandler servletHandler = manager.start();
    LOG.debug("started servlet deployment manager");
    /*
        List welcomePages =  manager.getDeployment().getDeploymentInfo().getWelcomePages();
        CFMLResourceHandler resourceHandler = new CFMLResourceHandler(servletBuilder.getResourceManager(), servletHandler, welcomePages);
        resourceHandler.setDirectoryListingEnabled(directoryListingEnabled);
        PathHandler pathHandler = Handlers.path(Handlers.redirect(contextPath))
                .addPrefixPath(contextPath, resourceHandler);
        HttpHandler errPageHandler = new SimpleErrorPageHandler(pathHandler);
        Builder serverBuilder = Undertow.builder().addHttpListener(portNumber, host).setHandler(errPageHandler);
*/
    Builder serverBuilder = Undertow.builder();
    if (serverOptions.isEnableHTTP()) {
        serverBuilder.addHttpListener(portNumber, host);
    }
    if (serverOptions.isHTTP2Enabled()) {
        LOG.info("Enabling HTTP2 protocol");
        LaunchUtil.assertJavaVersion8();
        if (!serverOptions.isEnableSSL()) {
            LOG.warn("SSL is required for HTTP2.  Enabling default SSL server.");
            serverOptions.setEnableSSL(true);
        }
        serverOptions.setSSLPort(serverOptions.getSSLPort() + 1);
        serverBuilder.setServerOption(UndertowOptions.ENABLE_HTTP2, true);
    // serverBuilder.setSocketOption(Options.REUSE_ADDRESSES, true);
    }
    if (serverOptions.isEnableSSL()) {
        int sslPort = serverOptions.getSSLPort();
        serverOptions.setDirectBuffers(true);
        LOG.info("Enabling SSL protocol on port " + sslPort);
        try {
            if (serverOptions.getSSLCertificate() != null) {
                File certfile = serverOptions.getSSLCertificate();
                File keyfile = serverOptions.getSSLKey();
                char[] keypass = serverOptions.getSSLKeyPass();
                String[] sslAddCerts = serverOptions.getSSLAddCerts();
                sslContext = SSLUtil.createSSLContext(certfile, keyfile, keypass, sslAddCerts);
                if (keypass != null)
                    Arrays.fill(keypass, '*');
            } else {
                sslContext = SSLUtil.createSSLContext();
            }
            serverBuilder.addHttpsListener(sslPort, host, sslContext);
        } catch (Exception e) {
            LOG.error("Unable to start SSL:" + e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }
    if (serverOptions.isEnableAJP()) {
        LOG.info("Enabling AJP protocol on port " + serverOptions.getAJPPort());
        serverBuilder.addAjpListener(serverOptions.getAJPPort(), host);
    }
    if (serverOptions.getBufferSize() != 0) {
        LOG.info("Buffer Size: " + serverOptions.getBufferSize());
        serverBuilder.setBufferSize(serverOptions.getBufferSize());
    }
    if (serverOptions.getIoThreads() != 0) {
        LOG.info("IO Threads: " + serverOptions.getIoThreads());
        serverBuilder.setIoThreads(serverOptions.getIoThreads());
    }
    if (serverOptions.getWorkerThreads() != 0) {
        LOG.info("Worker threads: " + serverOptions.getWorkerThreads());
        serverBuilder.setWorkerThreads(serverOptions.getWorkerThreads());
    }
    LOG.info("Direct Buffers: " + serverOptions.isDirectBuffers());
    serverBuilder.setDirectBuffers(serverOptions.isDirectBuffers());
    final PathHandler pathHandler = new PathHandler(Handlers.redirect(contextPath)) {

        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            // sessionConfig.setSessionId(exchange, ""); // TODO: see if this suppresses jsessionid
            if (exchange.getRequestPath().endsWith(".svgz")) {
                exchange.getResponseHeaders().put(Headers.CONTENT_ENCODING, "gzip");
            }
            // clear any welcome-file info cached after initial request *NOT THREAD SAFE*
            if (serverOptions.isDirectoryListingRefreshEnabled() && exchange.getRequestPath().endsWith("/")) {
                // RunwarLogger.ROOT_LOGGER.trace("*** Resetting servlet path info");
                manager.getDeployment().getServletPaths().invalidate();
            }
            if (serverOptions.isDebug() && exchange.getRequestPath().endsWith("/dumprunwarrequest")) {
                new RequestDumper().handleRequest(exchange);
            } else {
                super.handleRequest(exchange);
            }
        }
    };
    pathHandler.addPrefixPath(contextPath, servletHandler);
    if (serverOptions.isSecureCookies()) {
        sessionConfig.setHttpOnly(true);
        sessionConfig.setSecure(true);
    }
    sessionAttachmentHandler.setNext(pathHandler);
    HttpHandler errPageHandler;
    if (serverOptions.isGzipEnabled()) {
        final EncodingHandler handler = new EncodingHandler(new ContentEncodingRepository().addEncodingHandler("gzip", new GzipEncodingProvider(), 50, Predicates.parse("max-content-size[5]"))).setNext(pathHandler);
        errPageHandler = new ErrorHandler(handler);
    } else {
        errPageHandler = new ErrorHandler(pathHandler);
    }
    if (serverOptions.logAccessEnable()) {
        // final String PATTERN = "cs-uri cs(test-header) x-O(aa) x-H(secure)";
        DefaultAccessLogReceiver accessLogReceiver = DefaultAccessLogReceiver.builder().setLogWriteExecutor(worker).setOutputDirectory(options.getLogAccessDir().toPath()).setLogBaseName(options.getLogAccessBaseFileName()).build();
        LOG.info("Logging combined access to " + options.getLogAccessDir());
        // errPageHandler = new AccessLogHandler(errPageHandler, logReceiver, PATTERN, new ExtendedAccessLogParser( Server.class.getClassLoader()).parse(PATTERN));
        // errPageHandler = new AccessLogHandler(errPageHandler, logReceiver,"common", Server.class.getClassLoader());
        errPageHandler = new AccessLogHandler(errPageHandler, accessLogReceiver, "combined", Server.class.getClassLoader());
    }
    if (serverOptions.logRequestsEnable()) {
        LOG.error("Request log output currently goes to server.log");
        LOG.debug("Enabling request dumper");
        DefaultAccessLogReceiver requestsLogReceiver = DefaultAccessLogReceiver.builder().setLogWriteExecutor(worker).setOutputDirectory(options.getLogRequestsDir().toPath()).setLogBaseName(options.getLogRequestsBaseFileName()).build();
        errPageHandler = new RequestDebugHandler(errPageHandler, requestsLogReceiver);
    }
    if (serverOptions.isProxyPeerAddressEnabled()) {
        LOG.debug("Enabling Proxy Peer Address handling");
        errPageHandler = new SSLHeaderHandler(new ProxyPeerAddressHandler(errPageHandler));
    }
    Undertow reverseProxy = null;
    if (serverOptions.isHTTP2Enabled()) {
        LOG.debug("Enabling HTTP2 Upgrade and LearningPushHandler");
        /**
         * To not be dependent on java9 or crazy requirements, we set up a proxy to enable http2, and swap it with the actual SSL server (thus the port++/port--)
         */
        errPageHandler = new Http2UpgradeHandler(errPageHandler);
        errPageHandler = Handlers.header(predicate(secure(), errPageHandler, new HttpHandler() {

            @Override
            public void handleRequest(HttpServerExchange exchange) throws Exception {
                exchange.getResponseHeaders().add(Headers.LOCATION, "https://" + exchange.getHostName() + ":" + (serverOptions.getSSLPort() - 1) + exchange.getRelativePath());
                exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
            }
        }), "x-undertow-transport", ExchangeAttributes.transportProtocol());
        errPageHandler = new SessionAttachmentHandler(new LearningPushHandler(100, -1, errPageHandler), new InMemorySessionManager("runwarsessions"), new SessionCookieConfig());
        LoadBalancingProxyClient proxy = new LoadBalancingProxyClient().addHost(new URI("https://localhost:" + serverOptions.getSSLPort()), null, new UndertowXnioSsl(Xnio.getInstance(), OptionMap.EMPTY, SSLUtil.createClientSSLContext()), OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).setConnectionsPerThread(20);
        ProxyHandler proxyHandler = ProxyHandler.builder().setProxyClient(proxy).setMaxRequestTime(30000).setNext(ResponseCodeHandler.HANDLE_404).build();
        reverseProxy = Undertow.builder().setServerOption(UndertowOptions.ENABLE_HTTP2, true).addHttpsListener(serverOptions.getSSLPort() - 1, serverOptions.getHost(), sslContext).setHandler(proxyHandler).build();
    }
    if (serverOptions.isEnableBasicAuth()) {
        securityManager.configureAuth(errPageHandler, serverBuilder, options);
    // serverBuilder.setHandler(errPageHandler);
    } else {
        serverBuilder.setHandler(errPageHandler);
    }
    try {
        PID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
        String pidFile = serverOptions.getPidFile();
        if (pidFile != null && pidFile.length() > 0) {
            File file = new File(pidFile);
            file.deleteOnExit();
            PrintWriter writer = new PrintWriter(file);
            writer.print(PID);
            writer.close();
        }
    } catch (Exception e) {
        LOG.error("Unable to get PID:" + e.getMessage());
    }
    serverBuilder.setWorker(worker);
    undertow = serverBuilder.build();
    // start the stop monitor thread
    assert monitor == null;
    monitor = new MonitorThread(stoppassword);
    monitor.start();
    LOG.debug("started stop monitor");
    if (serverOptions.isTrayEnabled()) {
        try {
            Tray.hookTray(this);
            LOG.debug("hooked system tray");
        } catch (Throwable e) {
            LOG.error("system tray hook failed", e);
        }
    } else {
        LOG.debug("System tray integration disabled");
    }
    if (serverOptions.isOpenbrowser()) {
        LOG.debug("Starting open browser action");
        new Server(3);
    }
    // if this println changes be sure to update the LaunchUtil so it will know success
    String sslInfo = serverOptions.isEnableSSL() ? " https-port:" + serverOptions.getSSLPort() : "";
    String msg = "Server is up - http-port:" + portNumber + sslInfo + " stop-port:" + socketNumber + " PID:" + PID + " version " + getVersion();
    LOG.info(msg);
    System.out.println(msg);
    if (serverOptions.isTrayEnabled()) {
        LaunchUtil.displayMessage("info", msg);
    }
    setServerState(ServerState.STARTED);
    if (serverOptions.isMariaDB4jEnabled()) {
        try {
            mariadb4jManager.start(serverOptions.getMariaDB4jPort(), serverOptions.getMariaDB4jBaseDir(), serverOptions.getMariaDB4jDataDir(), serverOptions.getMariaDB4jImportSQLFile());
        } catch (Exception dbStartException) {
            LOG.error("Could not start MariaDB4j", dbStartException);
            System.out.println("Error starting MariaDB4j: " + dbStartException.getMessage());
        }
    }
    try {
        undertow.start();
        if (serverOptions.isHTTP2Enabled()) {
            LOG.debug("Starting HTTP2 proxy");
            reverseProxy.start();
        }
    } catch (Exception any) {
        if (any.getCause() instanceof java.net.SocketException && any.getCause().getMessage().equals("Permission denied")) {
            System.err.println("You need to be root or Administrator to bind to a port below 1024!");
        } else {
            any.printStackTrace();
        }
        System.exit(1);
    }
}
Also used : ErrorPage(io.undertow.servlet.api.ErrorPage) Builder(io.undertow.Undertow.Builder) ArrayList(java.util.ArrayList) PathHandler(io.undertow.server.handlers.PathHandler) DefaultAccessLogReceiver(io.undertow.server.handlers.accesslog.DefaultAccessLogReceiver) Image(java.awt.Image) LearningPushHandler(io.undertow.server.handlers.LearningPushHandler) ServletInfo(io.undertow.servlet.api.ServletInfo) ProxyPeerAddressHandler(io.undertow.server.handlers.ProxyPeerAddressHandler) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) HttpHandler(io.undertow.server.HttpHandler) DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) ProxyHandler(io.undertow.server.handlers.proxy.ProxyHandler) SSLHeaderHandler(io.undertow.server.handlers.SSLHeaderHandler) Method(java.lang.reflect.Method) LoadBalancingProxyClient(io.undertow.server.handlers.proxy.LoadBalancingProxyClient) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) File(java.io.File) Undertow(io.undertow.Undertow) SecurityManager(runwar.security.SecurityManager) RequestDebugHandler(runwar.undertow.RequestDebugHandler) ContentEncodingRepository(io.undertow.server.handlers.encoding.ContentEncodingRepository) RequestDumper(runwar.util.RequestDumper) EncodingHandler(io.undertow.server.handlers.encoding.EncodingHandler) URI(java.net.URI) URL(java.net.URL) GzipEncodingProvider(io.undertow.server.handlers.encoding.GzipEncodingProvider) HttpServerExchange(io.undertow.server.HttpServerExchange) Entry(java.util.Map.Entry) SessionCookieConfig(io.undertow.server.session.SessionCookieConfig) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) PrintWriter(java.io.PrintWriter) MariaDB4jManager(runwar.mariadb4j.MariaDB4jManager) Http2UpgradeHandler(io.undertow.server.protocol.http2.Http2UpgradeHandler) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException) AccessLogHandler(io.undertow.server.handlers.accesslog.AccessLogHandler) SessionAttachmentHandler(io.undertow.server.session.SessionAttachmentHandler)

Example 4 with ProxyHandler

use of io.undertow.server.handlers.proxy.ProxyHandler in project wildfly-swarm by wildfly-swarm.

the class TopologyProxyService method updateProxyHosts.

private void updateProxyHosts(String serviceName, List<Topology.Entry> entries) {
    HttpHandler proxyHandler = proxyHandlerMap.get(serviceName).getOptionalValue();
    if (proxyHandler == null) {
        // Service has been shutdown
        proxyHandlerMap.remove(serviceName);
        return;
    }
    LoadBalancingProxyClient proxyClient = null;
    // which then wraps the next handler in the chain
    if (proxyHandler instanceof GlobalRequestControllerHandler) {
        // next in the chain of handlers
        ProxyHandler proxy = (ProxyHandler) ((GlobalRequestControllerHandler) proxyHandler).getNext();
        proxyClient = (LoadBalancingProxyClient) proxy.getProxyClient();
    } else {
        proxyClient = (LoadBalancingProxyClient) ((ProxyHandler) proxyHandler).getProxyClient();
    }
    List<Topology.Entry> oldEntries = proxyEntries.get(serviceName);
    List<Topology.Entry> entriesToRemove = new ArrayList<>();
    List<Topology.Entry> entriesToAdd = new ArrayList<>();
    if (oldEntries == null) {
        entriesToAdd.addAll(entries);
    } else {
        for (Topology.Entry oldEntry : oldEntries) {
            if (!entries.contains(oldEntry)) {
                entriesToRemove.add(oldEntry);
            }
        }
        for (Topology.Entry entry : entries) {
            if (!oldEntries.contains(entry)) {
                entriesToAdd.add(entry);
            }
        }
    }
    for (Topology.Entry entry : entriesToRemove) {
        try {
            proxyClient.removeHost(entryToURI(entry));
        } catch (URISyntaxException ex) {
            log.log(Level.WARNING, "Error converting topology entry to URI", ex);
        }
    }
    for (Topology.Entry entry : entriesToAdd) {
        try {
            proxyClient.addHost(entryToURI(entry));
        } catch (URISyntaxException ex) {
            log.log(Level.WARNING, "Error converting topology entry to URI", ex);
        }
    }
    proxyEntries.put(serviceName, entries);
}
Also used : HttpHandler(io.undertow.server.HttpHandler) GlobalRequestControllerHandler(org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler) ProxyHandler(io.undertow.server.handlers.proxy.ProxyHandler) ArrayList(java.util.ArrayList) Topology(org.wildfly.swarm.topology.Topology) URISyntaxException(java.net.URISyntaxException) LoadBalancingProxyClient(io.undertow.server.handlers.proxy.LoadBalancingProxyClient)

Example 5 with ProxyHandler

use of io.undertow.server.handlers.proxy.ProxyHandler in project undertow by undertow-io.

the class DefaultServer method startServer.

/**
 * Starts the server if it is not up, and initiates the static fields in this class. This method is invoked
 * automatically once before your tests are triggered when using {@code DefaultServer} as a {@code Runner}.
 * After this method executes, getter methods can be invoked safely.
 * <p>
 * To perform an action in your test before the server starts, such as {@link #setServerOptions(OptionMap)},
 * use {@link BeforeServerStarts @BeforeServerStarts} methods. To perform an action precisely after the server
 * starts and before the test method runs, use {@code @BeforeClass} or {@code @Before} methods.
 */
public static boolean startServer() {
    if (openssl && OPENSSL_FAILURE != null) {
        throw new RuntimeException(OPENSSL_FAILURE);
    }
    if (server != null) {
        return false;
    }
    Xnio xnio = Xnio.getInstance("nio", DefaultServer.class.getClassLoader());
    try {
        worker = xnio.createWorker(OptionMap.builder().set(Options.WORKER_IO_THREADS, 8).set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, 30).set(Options.WORKER_TASK_MAX_THREADS, 30).set(Options.TCP_NODELAY, true).set(Options.CORK, true).getMap());
        serverOptions = serverOptionMapBuilder.set(Options.TCP_NODELAY, true).set(Options.BACKLOG, 1000).set(Options.REUSE_ADDRESSES, true).set(Options.BALANCING_TOKENS, 1).set(Options.BALANCING_CONNECTIONS, 2).getMap();
        final SSLContext serverContext = createSSLContext(loadKeyStore(SERVER_KEY_STORE), loadKeyStore(SERVER_TRUST_STORE), false);
        UndertowXnioSsl ssl = new UndertowXnioSsl(worker.getXnio(), OptionMap.EMPTY, SSL_BUFFER_POOL, serverContext);
        if (ajp) {
            openListener = new AjpOpenListener(pool);
            acceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(openListener));
            if (apache) {
                int port = 8888;
                server = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), port), acceptListener, serverOptions);
            } else {
                server = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), 7777 + PROXY_OFFSET), acceptListener, serverOptions);
                proxyOpenListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.BUFFER_PIPELINED_DATA, true));
                proxyAcceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(proxyOpenListener));
                proxyServer = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), proxyAcceptListener, serverOptions);
                loadBalancingProxyClient = new LoadBalancingProxyClient(GSSAPIAuthenticationMechanism.EXCLUSIVITY_CHECKER).addHost(new URI("ajp", null, getHostAddress(DEFAULT), getHostPort(DEFAULT) + PROXY_OFFSET, "/", null, null));
                ProxyHandler proxyHandler = ProxyHandler.builder().setProxyClient(loadBalancingProxyClient).setMaxRequestTime(120000).setNext(HANDLE_404).setReuseXForwarded(true).build();
                proxyOpenListener.setRootHandler(proxyHandler);
                proxyServer.resumeAccepts();
            }
        } else if (h2 && isAlpnEnabled()) {
            openListener = new Http2OpenListener(pool, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true, UndertowOptions.HTTP2_PADDING_SIZE, 10));
            acceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(new AlpnOpenListener(pool).addProtocol(Http2OpenListener.HTTP2, (io.undertow.server.DelegateOpenListener) openListener, 10)));
            SSLContext clientContext = createSSLContext(loadKeyStore(CLIENT_KEY_STORE), loadKeyStore(CLIENT_TRUST_STORE), true);
            server = ssl.createSslConnectionServer(worker, new InetSocketAddress(getHostAddress("default"), 7777 + PROXY_OFFSET), acceptListener, serverOptions);
            server.resumeAccepts();
            proxyOpenListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.BUFFER_PIPELINED_DATA, true));
            proxyAcceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(proxyOpenListener));
            proxyServer = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), proxyAcceptListener, serverOptions);
            loadBalancingProxyClient = new LoadBalancingProxyClient(GSSAPIAuthenticationMechanism.EXCLUSIVITY_CHECKER).addHost(new URI("h2", null, getHostAddress(DEFAULT), getHostPort(DEFAULT) + PROXY_OFFSET, "/", null, null), null, new UndertowXnioSsl(xnio, OptionMap.EMPTY, SSL_BUFFER_POOL, clientContext), OptionMap.create(UndertowOptions.ENABLE_HTTP2, true));
            ProxyHandler proxyHandler = ProxyHandler.builder().setProxyClient(loadBalancingProxyClient).setMaxRequestTime(120000).setNext(HANDLE_404).setReuseXForwarded(true).build();
            setupProxyHandlerForSSL(proxyHandler);
            proxyOpenListener.setRootHandler(proxyHandler);
            proxyServer.resumeAccepts();
        } else if (h2c || h2cUpgrade) {
            openListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true, UndertowOptions.HTTP2_PADDING_SIZE, 10));
            acceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(openListener));
            InetSocketAddress targetAddress = new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT) + PROXY_OFFSET);
            server = worker.createStreamConnectionServer(targetAddress, acceptListener, serverOptions);
            proxyOpenListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.BUFFER_PIPELINED_DATA, true));
            proxyAcceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(proxyOpenListener));
            proxyServer = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), proxyAcceptListener, serverOptions);
            loadBalancingProxyClient = new LoadBalancingProxyClient(GSSAPIAuthenticationMechanism.EXCLUSIVITY_CHECKER).addHost(new URI(h2cUpgrade ? "http" : "h2c-prior", null, getHostAddress(DEFAULT), getHostPort(DEFAULT) + PROXY_OFFSET, "/", null, null), null, null, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true));
            ProxyHandler proxyHandler = ProxyHandler.builder().setProxyClient(loadBalancingProxyClient).setMaxRequestTime(30000).setNext(HANDLE_404).setReuseXForwarded(true).build();
            setupProxyHandlerForSSL(proxyHandler);
            proxyOpenListener.setRootHandler(proxyHandler);
            proxyServer.resumeAccepts();
        } else if (https) {
            XnioSsl clientSsl = new UndertowXnioSsl(xnio, OptionMap.EMPTY, SSL_BUFFER_POOL, createClientSslContext());
            openListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.BUFFER_PIPELINED_DATA, true));
            acceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(openListener));
            server = ssl.createSslConnectionServer(worker, new InetSocketAddress(getHostAddress("default"), 7777 + PROXY_OFFSET), acceptListener, serverOptions);
            server.getAcceptSetter().set(acceptListener);
            server.resumeAccepts();
            proxyOpenListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.BUFFER_PIPELINED_DATA, true));
            proxyAcceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(proxyOpenListener));
            proxyServer = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), proxyAcceptListener, serverOptions);
            loadBalancingProxyClient = new LoadBalancingProxyClient(GSSAPIAuthenticationMechanism.EXCLUSIVITY_CHECKER).addHost(new URI("https", null, getHostAddress(DEFAULT), getHostPort(DEFAULT) + PROXY_OFFSET, "/", null, null), clientSsl);
            ProxyHandler proxyHandler = ProxyHandler.builder().setProxyClient(loadBalancingProxyClient).setMaxRequestTime(30000).setNext(HANDLE_404).setReuseXForwarded(true).build();
            setupProxyHandlerForSSL(proxyHandler);
            proxyOpenListener.setRootHandler(proxyHandler);
            proxyServer.resumeAccepts();
        } else {
            if (h2) {
                UndertowLogger.ROOT_LOGGER.error("HTTP2 selected but Netty ALPN was not on the boot class path");
            }
            openListener = new HttpOpenListener(pool, OptionMap.builder().set(UndertowOptions.BUFFER_PIPELINED_DATA, true).set(UndertowOptions.ENABLE_CONNECTOR_STATISTICS, true).set(UndertowOptions.REQUIRE_HOST_HTTP11, true).getMap());
            acceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(openListener));
            if (!proxy) {
                server = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), acceptListener, serverOptions);
            } else {
                InetSocketAddress targetAddress = new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT) + PROXY_OFFSET);
                server = worker.createStreamConnectionServer(targetAddress, acceptListener, serverOptions);
                proxyOpenListener = new HttpOpenListener(pool, OptionMap.create(UndertowOptions.BUFFER_PIPELINED_DATA, true));
                proxyAcceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(proxyOpenListener));
                proxyServer = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(getHostAddress(DEFAULT)), getHostPort(DEFAULT)), proxyAcceptListener, serverOptions);
                loadBalancingProxyClient = new LoadBalancingProxyClient(GSSAPIAuthenticationMechanism.EXCLUSIVITY_CHECKER).addHost(new URI("http", null, getHostAddress(DEFAULT), getHostPort(DEFAULT) + PROXY_OFFSET, "/", null, null));
                ProxyHandler proxyHandler = ProxyHandler.builder().setProxyClient(loadBalancingProxyClient).setMaxRequestTime(30000).setNext(HANDLE_404).setReuseXForwarded(true).build();
                setupProxyHandlerForSSL(proxyHandler);
                proxyOpenListener.setRootHandler(proxyHandler);
                proxyServer.resumeAccepts();
            }
        }
        if (h2cUpgrade) {
            openListener.setRootHandler(new Http2UpgradeHandler(rootHandler));
        } else {
            openListener.setRootHandler(rootHandler);
        }
        server.resumeAccepts();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return true;
}
Also used : AlpnOpenListener(io.undertow.server.protocol.http.AlpnOpenListener) XnioSsl(org.xnio.ssl.XnioSsl) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) Http2UpgradeHandler(io.undertow.server.protocol.http2.Http2UpgradeHandler) ProxyHandler(io.undertow.server.handlers.proxy.ProxyHandler) InetSocketAddress(java.net.InetSocketAddress) Xnio(org.xnio.Xnio) SSLContext(javax.net.ssl.SSLContext) SNISSLContext(io.undertow.protocols.ssl.SNISSLContext) Http2OpenListener(io.undertow.server.protocol.http2.Http2OpenListener) URI(java.net.URI) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) LoadBalancingProxyClient(io.undertow.server.handlers.proxy.LoadBalancingProxyClient) AjpOpenListener(io.undertow.server.protocol.ajp.AjpOpenListener) Xnio(org.xnio.Xnio) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) HttpOpenListener(io.undertow.server.protocol.http.HttpOpenListener)

Aggregations

ProxyHandler (io.undertow.server.handlers.proxy.ProxyHandler)6 LoadBalancingProxyClient (io.undertow.server.handlers.proxy.LoadBalancingProxyClient)5 HttpHandler (io.undertow.server.HttpHandler)4 URI (java.net.URI)4 UndertowXnioSsl (io.undertow.protocols.ssl.UndertowXnioSsl)3 Http2UpgradeHandler (io.undertow.server.protocol.http2.Http2UpgradeHandler)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 Undertow (io.undertow.Undertow)2 HttpServerExchange (io.undertow.server.HttpServerExchange)2 AjpOpenListener (io.undertow.server.protocol.ajp.AjpOpenListener)2 AlpnOpenListener (io.undertow.server.protocol.http.AlpnOpenListener)2 HttpOpenListener (io.undertow.server.protocol.http.HttpOpenListener)2 Http2OpenListener (io.undertow.server.protocol.http2.Http2OpenListener)2 InetSocketAddress (java.net.InetSocketAddress)2 KeyManagementException (java.security.KeyManagementException)2 KeyStoreException (java.security.KeyStoreException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 UnrecoverableKeyException (java.security.UnrecoverableKeyException)2 CertificateException (java.security.cert.CertificateException)2