Search in sources :

Example 16 with XnioWorker

use of org.xnio.XnioWorker in project wildfly by wildfly.

the class ServletContainerAdd method installRuntimeServices.

void installRuntimeServices(OperationContext context, ModelNode model, String name) throws OperationFailedException {
    final ModelNode fullModel = Resource.Tools.readModel(context.readResource(PathAddress.EMPTY_ADDRESS), 2);
    final SessionCookieConfig config = SessionCookieDefinition.INSTANCE.getConfig(context, fullModel.get(SessionCookieDefinition.INSTANCE.getPathElement().getKeyValuePair()));
    final CrawlerSessionManagerConfig crawlerSessionManagerConfig = CrawlerSessionManagementDefinition.INSTANCE.getConfig(context, fullModel.get(CrawlerSessionManagementDefinition.INSTANCE.getPathElement().getKeyValuePair()));
    final boolean persistentSessions = PersistentSessionsDefinition.isEnabled(context, fullModel.get(PersistentSessionsDefinition.INSTANCE.getPathElement().getKeyValuePair()));
    final boolean allowNonStandardWrappers = ServletContainerDefinition.ALLOW_NON_STANDARD_WRAPPERS.resolveModelAttribute(context, model).asBoolean();
    final boolean proactiveAuth = ServletContainerDefinition.PROACTIVE_AUTHENTICATION.resolveModelAttribute(context, model).asBoolean();
    final String bufferCache = ServletContainerDefinition.DEFAULT_BUFFER_CACHE.resolveModelAttribute(context, model).asString();
    final boolean disableFileWatchService = ServletContainerDefinition.DISABLE_FILE_WATCH_SERVICE.resolveModelAttribute(context, model).asBoolean();
    final boolean disableSessionIdReususe = ServletContainerDefinition.DISABLE_SESSION_ID_REUSE.resolveModelAttribute(context, model).asBoolean();
    JSPConfig jspConfig = JspDefinition.INSTANCE.getConfig(context, fullModel.get(JspDefinition.INSTANCE.getPathElement().getKeyValuePair()));
    final String stackTracesString = ServletContainerDefinition.STACK_TRACE_ON_ERROR.resolveModelAttribute(context, model).asString();
    final ModelNode defaultEncodingValue = ServletContainerDefinition.DEFAULT_ENCODING.resolveModelAttribute(context, model);
    final String defaultEncoding = defaultEncodingValue.isDefined() ? defaultEncodingValue.asString() : null;
    final boolean useListenerEncoding = ServletContainerDefinition.USE_LISTENER_ENCODING.resolveModelAttribute(context, model).asBoolean();
    final boolean ignoreFlush = ServletContainerDefinition.IGNORE_FLUSH.resolveModelAttribute(context, model).asBoolean();
    final boolean eagerFilterInit = ServletContainerDefinition.EAGER_FILTER_INIT.resolveModelAttribute(context, model).asBoolean();
    final boolean disableCachingForSecuredPages = ServletContainerDefinition.DISABLE_CACHING_FOR_SECURED_PAGES.resolveModelAttribute(context, model).asBoolean();
    final int sessionIdLength = ServletContainerDefinition.SESSION_ID_LENGTH.resolveModelAttribute(context, model).asInt();
    final int fileCacheMetadataSize = ServletContainerDefinition.FILE_CACHE_METADATA_SIZE.resolveModelAttribute(context, model).asInt();
    final int fileCacheMaxFileSize = ServletContainerDefinition.FILE_CACHE_MAX_FILE_SIZE.resolveModelAttribute(context, model).asInt();
    final ModelNode fileCacheTtlNode = ServletContainerDefinition.FILE_CACHE_TIME_TO_LIVE.resolveModelAttribute(context, model);
    final Integer fileCacheTimeToLive = fileCacheTtlNode.isDefined() ? fileCacheTtlNode.asInt() : null;
    final int defaultCookieVersion = ServletContainerDefinition.DEFAULT_COOKIE_VERSION.resolveModelAttribute(context, model).asInt();
    final boolean preservePathOnForward = ServletContainerDefinition.PRESERVE_PATH_ON_FORWARD.resolveModelAttribute(context, model).asBoolean();
    Boolean directoryListingEnabled = null;
    if (model.hasDefined(Constants.DIRECTORY_LISTING)) {
        directoryListingEnabled = ServletContainerDefinition.DIRECTORY_LISTING.resolveModelAttribute(context, model).asBoolean();
    }
    Integer maxSessions = null;
    if (model.hasDefined(Constants.MAX_SESSIONS)) {
        maxSessions = ServletContainerDefinition.MAX_SESSIONS.resolveModelAttribute(context, model).asInt();
    }
    final int sessionTimeout = ServletContainerDefinition.DEFAULT_SESSION_TIMEOUT.resolveModelAttribute(context, model).asInt();
    WebsocketsDefinition.WebSocketInfo webSocketInfo = WebsocketsDefinition.INSTANCE.getConfig(context, fullModel.get(WebsocketsDefinition.INSTANCE.getPathElement().getKeyValuePair()));
    final Map<String, String> mimeMappings = new HashMap<>();
    if (fullModel.hasDefined(Constants.MIME_MAPPING)) {
        for (final Property mapping : fullModel.get(Constants.MIME_MAPPING).asPropertyList()) {
            mimeMappings.put(mapping.getName(), MimeMappingDefinition.VALUE.resolveModelAttribute(context, mapping.getValue()).asString());
        }
    }
    List<String> welcomeFiles = new ArrayList<>();
    if (fullModel.hasDefined(Constants.WELCOME_FILE)) {
        for (final Property welcome : fullModel.get(Constants.WELCOME_FILE).asPropertyList()) {
            welcomeFiles.add(welcome.getName());
        }
    }
    final CapabilityServiceBuilder<?> sb = context.getCapabilityServiceTarget().addCapability(ServletContainerDefinition.SERVLET_CONTAINER_CAPABILITY);
    final Consumer<ServletContainerService> sConsumer = sb.provides(ServletContainerDefinition.SERVLET_CONTAINER_CAPABILITY, UndertowService.SERVLET_CONTAINER.append(name));
    final Supplier<SessionPersistenceManager> spmSupplier = persistentSessions ? sb.requires(AbstractPersistentSessionManager.SERVICE_NAME) : null;
    final Supplier<DirectBufferCache> bcSupplier = bufferCache != null ? sb.requires(BufferCacheService.SERVICE_NAME.append(bufferCache)) : null;
    final Supplier<ByteBufferPool> bbpSupplier = webSocketInfo != null ? sb.requiresCapability(Capabilities.CAPABILITY_BYTE_BUFFER_POOL, ByteBufferPool.class, webSocketInfo.getBufferPool()) : null;
    final Supplier<XnioWorker> xwSupplier = webSocketInfo != null ? sb.requiresCapability(Capabilities.REF_IO_WORKER, XnioWorker.class, webSocketInfo.getWorker()) : null;
    final ServletContainerService container = new ServletContainerService(sConsumer, spmSupplier, bcSupplier, bbpSupplier, xwSupplier, allowNonStandardWrappers, ServletStackTraces.valueOf(stackTracesString.toUpperCase().replace('-', '_')), config, jspConfig, defaultEncoding, useListenerEncoding, ignoreFlush, eagerFilterInit, sessionTimeout, disableCachingForSecuredPages, webSocketInfo != null, webSocketInfo != null && webSocketInfo.isDispatchToWorker(), webSocketInfo != null && webSocketInfo.isPerMessageDeflate(), webSocketInfo == null ? -1 : webSocketInfo.getDeflaterLevel(), mimeMappings, welcomeFiles, directoryListingEnabled, proactiveAuth, sessionIdLength, maxSessions, crawlerSessionManagerConfig, disableFileWatchService, disableSessionIdReususe, fileCacheMetadataSize, fileCacheMaxFileSize, fileCacheTimeToLive, defaultCookieVersion, preservePathOnForward);
    sb.setInstance(container);
    sb.setInitialMode(ServiceController.Mode.ON_DEMAND);
    sb.install();
}
Also used : ByteBufferPool(io.undertow.connector.ByteBufferPool) HashMap(java.util.HashMap) XnioWorker(org.xnio.XnioWorker) ArrayList(java.util.ArrayList) DirectBufferCache(io.undertow.server.handlers.cache.DirectBufferCache) CrawlerSessionManagerConfig(io.undertow.servlet.api.CrawlerSessionManagerConfig) Property(org.jboss.dmr.Property) SessionPersistenceManager(io.undertow.servlet.api.SessionPersistenceManager) ModelNode(org.jboss.dmr.ModelNode)

Example 17 with XnioWorker

use of org.xnio.XnioWorker in project wildfly by wildfly.

the class AccessLogAdd method performRuntime.

@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
    final PathAddress address = context.getCurrentAddress();
    final PathAddress hostAddress = address.getParent();
    final PathAddress serverAddress = hostAddress.getParent();
    final String worker = AccessLogDefinition.WORKER.resolveModelAttribute(context, model).asString();
    final String pattern = AccessLogDefinition.PATTERN.resolveModelAttribute(context, model).asString();
    final String directory = AccessLogDefinition.DIRECTORY.resolveModelAttribute(context, model).asString();
    final String filePrefix = AccessLogDefinition.PREFIX.resolveModelAttribute(context, model).asString();
    final String fileSuffix = AccessLogDefinition.SUFFIX.resolveModelAttribute(context, model).asString();
    final boolean useServerLog = AccessLogDefinition.USE_SERVER_LOG.resolveModelAttribute(context, model).asBoolean();
    final boolean rotate = AccessLogDefinition.ROTATE.resolveModelAttribute(context, model).asBoolean();
    final boolean extended = AccessLogDefinition.EXTENDED.resolveModelAttribute(context, model).asBoolean();
    final ModelNode relativeToNode = AccessLogDefinition.RELATIVE_TO.resolveModelAttribute(context, model);
    final String relativeTo = relativeToNode.isDefined() ? relativeToNode.asString() : null;
    Predicate predicate = null;
    ModelNode predicateNode = AccessLogDefinition.PREDICATE.resolveModelAttribute(context, model);
    if (predicateNode.isDefined()) {
        predicate = Predicates.parse(predicateNode.asString(), getClass().getClassLoader());
    }
    final String serverName = serverAddress.getLastElement().getValue();
    final String hostName = hostAddress.getLastElement().getValue();
    final CapabilityServiceBuilder<?> sb = context.getCapabilityServiceTarget().addCapability(AccessLogDefinition.ACCESS_LOG_CAPABILITY);
    final Consumer<AccessLogService> sConsumer = sb.provides(AccessLogDefinition.ACCESS_LOG_CAPABILITY, UndertowService.accessLogServiceName(serverName, hostName));
    final Supplier<Host> hSupplier = sb.requiresCapability(Capabilities.CAPABILITY_HOST, Host.class, serverName, hostName);
    final Supplier<XnioWorker> wSupplier = sb.requiresCapability(Capabilities.REF_IO_WORKER, XnioWorker.class, worker);
    final Supplier<PathManager> pmSupplier = sb.requires(PathManagerService.SERVICE_NAME);
    final AccessLogService service;
    if (useServerLog) {
        service = new AccessLogService(sConsumer, hSupplier, wSupplier, pmSupplier, pattern, extended, predicate);
    } else {
        service = new AccessLogService(sConsumer, hSupplier, wSupplier, pmSupplier, pattern, directory, relativeTo, filePrefix, fileSuffix, rotate, extended, false, predicate);
    }
    sb.setInstance(service);
    sb.install();
}
Also used : PathManager(org.jboss.as.controller.services.path.PathManager) XnioWorker(org.xnio.XnioWorker) Predicate(io.undertow.predicate.Predicate) PathAddress(org.jboss.as.controller.PathAddress) ModelNode(org.jboss.dmr.ModelNode)

Example 18 with XnioWorker

use of org.xnio.XnioWorker in project wildfly by wildfly.

the class ListenerService method isShutdown.

@Override
public boolean isShutdown() {
    final DelegatingSupplier<XnioWorker> workerSupplier = getWorker();
    XnioWorker worker = workerSupplier != null ? workerSupplier.get() : null;
    return worker == null || worker.isShutdown();
}
Also used : XnioWorker(org.xnio.XnioWorker)

Example 19 with XnioWorker

use of org.xnio.XnioWorker in project undertow by undertow-io.

the class Http2EndExchangeTestCase method testHttp2EndExchangeWithBrokenConnection.

@Test
public void testHttp2EndExchangeWithBrokenConnection() throws Exception {
    int port = DefaultServer.getHostPort("default");
    final CountDownLatch requestStartedLatch = new CountDownLatch(1);
    final CompletableFuture<String> testResult = new CompletableFuture<>();
    Undertow server = Undertow.builder().addHttpsListener(port + 1, DefaultServer.getHostAddress("default"), DefaultServer.getServerSslContext()).setServerOption(UndertowOptions.ENABLE_HTTP2, true).setSocketOption(Options.REUSE_ADDRESSES, true).setHandler(new BlockingHandler(new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            if (!exchange.getProtocol().equals(Protocols.HTTP_2_0)) {
                testResult.completeExceptionally(new RuntimeException("Not HTTP/2 request"));
                return;
            }
            requestStartedLatch.countDown();
            log.debug("Received Request");
            // do some pretend work
            Thread.sleep(2000);
            if (exchange.isComplete()) {
                testResult.complete("FAILED, exchange ended in the background");
                return;
            }
            try {
                exchange.getOutputStream().write("Bogus Data".getBytes(StandardCharsets.UTF_8));
                exchange.getOutputStream().flush();
                testResult.complete("FAILED, should not have completed successfully");
                return;
            } catch (IOException expected) {
            }
            if (!exchange.isComplete()) {
                testResult.complete("Failed, should have completed the exchange");
            } else {
                testResult.complete("PASSED");
            }
        }
    })).build();
    server.start();
    try {
        ADDRESS = new URI("https://" + DefaultServer.getHostAddress() + ":" + (port + 1));
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    // Create xnio worker
    final Xnio xnio = Xnio.getInstance();
    final XnioWorker xnioWorker = xnio.createWorker(null, DEFAULT_OPTIONS);
    try {
        final UndertowClient client = createClient();
        final ClientConnection connection = client.connect(ADDRESS, xnioWorker, new UndertowXnioSsl(xnioWorker.getXnio(), OptionMap.EMPTY, DefaultServer.getClientSSLContext()), DefaultServer.getBufferPool(), OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
        try {
            connection.getIoThread().execute(new Runnable() {

                @Override
                public void run() {
                    final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(MESSAGE);
                    request.getRequestHeaders().put(Headers.HOST, DefaultServer.getHostAddress());
                    connection.sendRequest(request, new ClientCallback<ClientExchange>() {

                        @Override
                        public void completed(ClientExchange result) {
                            try {
                                log.debug("Callback invoked");
                                new Thread(new Runnable() {

                                    @Override
                                    public void run() {
                                        try {
                                            requestStartedLatch.await(10, TimeUnit.SECONDS);
                                            result.getRequestChannel().getIoThread().execute(new Runnable() {

                                                @Override
                                                public void run() {
                                                    IoUtils.safeClose(result.getConnection());
                                                    log.debug("Closed Connection");
                                                }
                                            });
                                        } catch (Exception e) {
                                            testResult.completeExceptionally(e);
                                        }
                                    }
                                }).start();
                            } catch (Exception e) {
                                testResult.completeExceptionally(e);
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            testResult.completeExceptionally(e);
                        }
                    });
                }
            });
            Assert.assertEquals("PASSED", testResult.get(10, TimeUnit.SECONDS));
        } finally {
            IoUtils.safeClose(connection);
        }
    } finally {
        stopWorker(xnioWorker);
        server.stop();
        // sleep 1 s to prevent BindException (Address already in use) when running the CI
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignore) {
        }
    }
}
Also used : ClientExchange(io.undertow.client.ClientExchange) ClientCallback(io.undertow.client.ClientCallback) XnioWorker(org.xnio.XnioWorker) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) HttpServerExchange(io.undertow.server.HttpServerExchange) CompletableFuture(java.util.concurrent.CompletableFuture) BlockingHandler(io.undertow.server.handlers.BlockingHandler) Xnio(org.xnio.Xnio) ClientConnection(io.undertow.client.ClientConnection) ClientRequest(io.undertow.client.ClientRequest) HttpHandler(io.undertow.server.HttpHandler) UndertowClient(io.undertow.client.UndertowClient) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) Undertow(io.undertow.Undertow) Test(org.junit.Test)

Example 20 with XnioWorker

use of org.xnio.XnioWorker in project undertow by undertow-io.

the class PushPromisesTestCase method setup.

@BeforeClass
public static void setup() throws Exception {
    final PathHandler root = new PathHandler();
    final ServletContainer container = ServletContainer.Factory.newInstance();
    ServletInfo s = new ServletInfo("servlet", PushServlet.class).addMappings("/index.html", "/resources/*");
    DeploymentInfo info = new DeploymentInfo().setClassLoader(PushPromisesTestCase.class.getClassLoader()).setContextPath("/push-example").setClassIntrospecter(TestClassIntrospector.INSTANCE).setDeploymentName("push-example.war").addServlet(s);
    DeploymentManager manager = container.addDeployment(info);
    manager.deploy();
    root.addPrefixPath(info.getContextPath(), manager.start());
    openListener = new Http2OpenListener(DefaultServer.getBufferPool(), OptionMap.create(UndertowOptions.ENABLE_HTTP2, true, UndertowOptions.HTTP2_PADDING_SIZE, 10));
    acceptListener = ChannelListeners.openListenerAdapter(wrapOpenListener(new AlpnOpenListener(DefaultServer.getBufferPool()).addProtocol(Http2OpenListener.HTTP2, (io.undertow.server.DelegateOpenListener) openListener, 10)));
    openListener.setRootHandler(root);
    DefaultServer.startSSLServer(OptionMap.EMPTY, acceptListener);
    final Xnio xnio = Xnio.getInstance();
    final XnioWorker xnioWorker = xnio.createWorker(null, OptionMap.builder().set(Options.WORKER_IO_THREADS, 8).set(Options.TCP_NODELAY, true).set(Options.KEEP_ALIVE, true).set(Options.WORKER_NAME, "Client").getMap());
    worker = xnioWorker;
}
Also used : AlpnOpenListener(io.undertow.server.protocol.http.AlpnOpenListener) DeploymentManager(io.undertow.servlet.api.DeploymentManager) XnioWorker(org.xnio.XnioWorker) PathHandler(io.undertow.server.handlers.PathHandler) Http2OpenListener(io.undertow.server.protocol.http2.Http2OpenListener) ServletInfo(io.undertow.servlet.api.ServletInfo) Xnio(org.xnio.Xnio) ServletContainer(io.undertow.servlet.api.ServletContainer) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) BeforeClass(org.junit.BeforeClass)

Aggregations

XnioWorker (org.xnio.XnioWorker)27 IOException (java.io.IOException)15 Xnio (org.xnio.Xnio)13 HttpHandler (io.undertow.server.HttpHandler)7 CountDownLatch (java.util.concurrent.CountDownLatch)6 HttpServerExchange (io.undertow.server.HttpServerExchange)5 PathHandler (io.undertow.server.handlers.PathHandler)5 BeforeClass (org.junit.BeforeClass)5 OptionMap (org.xnio.OptionMap)5 DefaultByteBufferPool (io.undertow.server.DefaultByteBufferPool)4 InetSocketAddress (java.net.InetSocketAddress)4 URI (java.net.URI)4 Undertow (io.undertow.Undertow)3 ByteBufferPool (io.undertow.connector.ByteBufferPool)3 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)3 ServletContainer (io.undertow.servlet.api.ServletContainer)3 Test (org.junit.Test)3 ChannelListener (org.xnio.ChannelListener)3 Predicate (io.undertow.predicate.Predicate)2 UndertowXnioSsl (io.undertow.protocols.ssl.UndertowXnioSsl)2