Search in sources :

Example 6 with StreamConnection

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

the class ProgramaticAutobahnServer method run.

public void run() {
    Xnio xnio = Xnio.getInstance();
    try {
        XnioWorker worker = xnio.createWorker(OptionMap.builder().set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, 10).set(Options.WORKER_TASK_MAX_THREADS, 12).set(Options.TCP_NODELAY, true).set(Options.CORK, true).getMap());
        OptionMap serverOptions = OptionMap.builder().set(Options.TCP_NODELAY, true).set(Options.REUSE_ADDRESSES, true).getMap();
        DefaultByteBufferPool pool = new DefaultByteBufferPool(true, 8192);
        HttpOpenListener openListener = new HttpOpenListener(pool);
        ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
        AcceptingChannel<StreamConnection> server = worker.createStreamConnectionServer(new InetSocketAddress(port), acceptListener, serverOptions);
        server.resumeAccepts();
        final ServletContainer container = ServletContainer.Factory.newInstance();
        DeploymentInfo builder = new DeploymentInfo().setClassLoader(ProgramaticAutobahnServer.class.getClassLoader()).setContextPath("/").setClassIntrospecter(TestClassIntrospector.INSTANCE).setDeploymentName("servletContext.war").addFilter(new FilterInfo("filter", JsrWebSocketFilter.class)).addFilterUrlMapping("filter", "/*", DispatcherType.REQUEST).addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, new WebSocketDeploymentInfo().setBuffers(pool).setWorker(worker).setDispatchToWorkerThread(true).addEndpoint(new ServerEndpointConfigImpl(ProgramaticAutobahnEndpoint.class, "/")).addExtension(new PerMessageDeflateHandshake()));
        DeploymentManager manager = container.addDeployment(builder);
        manager.deploy();
        openListener.setRootHandler(manager.start());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : ChannelListener(org.xnio.ChannelListener) DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) DeploymentManager(io.undertow.servlet.api.DeploymentManager) XnioWorker(org.xnio.XnioWorker) InetSocketAddress(java.net.InetSocketAddress) ServerEndpointConfigImpl(io.undertow.websockets.jsr.ServerEndpointConfigImpl) StreamConnection(org.xnio.StreamConnection) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) Xnio(org.xnio.Xnio) JsrWebSocketFilter(io.undertow.websockets.jsr.JsrWebSocketFilter) OptionMap(org.xnio.OptionMap) ServletContainer(io.undertow.servlet.api.ServletContainer) PerMessageDeflateHandshake(io.undertow.websockets.extensions.PerMessageDeflateHandshake) HttpOpenListener(io.undertow.server.protocol.http.HttpOpenListener) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) FilterInfo(io.undertow.servlet.api.FilterInfo)

Example 7 with StreamConnection

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

the class HttpReadListener method exchangeComplete.

public void exchangeComplete(final HttpServerExchange exchange) {
    connection.clearChannel();
    final HttpServerConnection connection = this.connection;
    if (exchange.isPersistent() && !isUpgradeOrConnect(exchange)) {
        final StreamConnection channel = connection.getChannel();
        if (connection.getExtraBytes() == null) {
            //we have to resume from with the io thread
            if (exchange.isInIoThread()) {
                //no need for CAS, we are in the IO thread
                newRequest();
                channel.getSourceChannel().setReadListener(HttpReadListener.this);
                channel.getSourceChannel().resumeReads();
                requestStateUpdater.set(this, 0);
            } else {
                while (true) {
                    if (connection.getOriginalSourceConduit().isReadShutdown() || connection.getOriginalSinkConduit().isWriteShutdown()) {
                        channel.getSourceChannel().suspendReads();
                        channel.getSinkChannel().suspendWrites();
                        IoUtils.safeClose(connection);
                        return;
                    } else {
                        if (requestStateUpdater.compareAndSet(this, 1, 2)) {
                            try {
                                newRequest();
                                channel.getSourceChannel().setReadListener(HttpReadListener.this);
                                channel.getSourceChannel().resumeReads();
                            } finally {
                                requestStateUpdater.set(this, 0);
                            }
                            break;
                        }
                    }
                }
            }
        } else {
            if (exchange.isInIoThread()) {
                //no need to CAS, as we don't actually resume
                requestStateUpdater.set(this, 0);
                newRequest();
                //no need to suspend reads here, the task will always run before the read listener anyway
                channel.getIoThread().execute(this);
            } else {
                while (true) {
                    if (connection.getOriginalSinkConduit().isWriteShutdown()) {
                        channel.getSourceChannel().suspendReads();
                        channel.getSinkChannel().suspendWrites();
                        IoUtils.safeClose(connection);
                        return;
                    } else if (requestStateUpdater.compareAndSet(this, 1, 2)) {
                        try {
                            newRequest();
                            channel.getSourceChannel().suspendReads();
                        } finally {
                            requestStateUpdater.set(this, 0);
                        }
                        break;
                    }
                }
                Executor executor = exchange.getDispatchExecutor();
                if (executor == null) {
                    executor = exchange.getConnection().getWorker();
                }
                executor.execute(this);
            }
        }
    } else if (!exchange.isPersistent()) {
        ConnectionUtils.cleanClose(connection.getChannel(), connection);
    } else {
        //upgrade or connect handling
        if (connection.getExtraBytes() != null) {
            connection.getChannel().getSourceChannel().setConduit(new ReadDataStreamSourceConduit(connection.getChannel().getSourceChannel().getConduit(), connection));
        }
        try {
            if (!connection.getChannel().getSinkChannel().flush()) {
                connection.getChannel().getSinkChannel().setWriteListener(ChannelListeners.flushingChannelListener(new ChannelListener<ConduitStreamSinkChannel>() {

                    @Override
                    public void handleEvent(ConduitStreamSinkChannel conduitStreamSinkChannel) {
                        connection.getUpgradeListener().handleUpgrade(connection.getChannel(), exchange);
                    }
                }, new ClosingChannelExceptionHandler<ConduitStreamSinkChannel>(connection)));
                connection.getChannel().getSinkChannel().resumeWrites();
                return;
            }
            connection.getUpgradeListener().handleUpgrade(connection.getChannel(), exchange);
        } catch (IOException e) {
            UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
            IoUtils.safeClose(connection);
        }
    }
}
Also used : Executor(java.util.concurrent.Executor) ReadDataStreamSourceConduit(io.undertow.conduits.ReadDataStreamSourceConduit) IOException(java.io.IOException) StreamConnection(org.xnio.StreamConnection) ConduitStreamSinkChannel(org.xnio.conduits.ConduitStreamSinkChannel)

Example 8 with StreamConnection

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

the class AjpReadListener method handleCPing.

private void handleCPing() {
    state = new AjpRequestParseState();
    final StreamConnection underlyingChannel = connection.getChannel();
    underlyingChannel.getSourceChannel().suspendReads();
    final ByteBuffer buffer = ByteBuffer.wrap(CPONG);
    int res;
    try {
        do {
            res = underlyingChannel.getSinkChannel().write(buffer);
            if (res == 0) {
                underlyingChannel.getSinkChannel().setWriteListener(new ChannelListener<ConduitStreamSinkChannel>() {

                    @Override
                    public void handleEvent(ConduitStreamSinkChannel channel) {
                        int res;
                        do {
                            try {
                                res = channel.write(buffer);
                                if (res == 0) {
                                    return;
                                }
                            } catch (IOException e) {
                                UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                                safeClose(connection);
                            }
                        } while (buffer.hasRemaining());
                        channel.suspendWrites();
                        AjpReadListener.this.handleEvent(underlyingChannel.getSourceChannel());
                    }
                });
                underlyingChannel.getSinkChannel().resumeWrites();
                return;
            }
        } while (buffer.hasRemaining());
        AjpReadListener.this.handleEvent(underlyingChannel.getSourceChannel());
    } catch (IOException e) {
        UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
        safeClose(connection);
    }
}
Also used : IOException(java.io.IOException) StreamConnection(org.xnio.StreamConnection) ByteBuffer(java.nio.ByteBuffer) PooledByteBuffer(io.undertow.connector.PooledByteBuffer) ConduitStreamSinkChannel(org.xnio.conduits.ConduitStreamSinkChannel)

Example 9 with StreamConnection

use of org.xnio.StreamConnection in project indy by Commonjava.

the class ProxyAcceptHandler method handleEvent.

@Override
public void handleEvent(AcceptingChannel<StreamConnection> channel) {
    final Logger logger = LoggerFactory.getLogger(getClass());
    StreamConnection accepted;
    try {
        accepted = channel.accept();
    } catch (IOException e) {
        logger.error("Failed to addMetadata httprox connection: " + e.getMessage(), e);
        return;
    }
    if (accepted == null) {
        return;
    }
    logger.debug("accepted {}", accepted.getPeerAddress());
    final ConduitStreamSourceChannel source = accepted.getSourceChannel();
    final ConduitStreamSinkChannel sink = accepted.getSinkChannel();
    final ProxyRepositoryCreator creator = createRepoCreator();
    final ProxyResponseWriter writer = new ProxyResponseWriter(config, storeManager, contentController, proxyAuthenticator, cacheProvider, creator);
    logger.debug("Setting writer: {}", writer);
    sink.getWriteSetter().set(writer);
    final ProxyRequestReader reader = new ProxyRequestReader(writer, sink);
    logger.debug("Setting reader: {}", reader);
    source.getReadSetter().set(reader);
    source.resumeReads();
}
Also used : IOException(java.io.IOException) Logger(org.slf4j.Logger) StreamConnection(org.xnio.StreamConnection) ConduitStreamSourceChannel(org.xnio.conduits.ConduitStreamSourceChannel) ConduitStreamSinkChannel(org.xnio.conduits.ConduitStreamSinkChannel)

Example 10 with StreamConnection

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

the class Undertow method start.

public synchronized void start() {
    UndertowLogger.ROOT_LOGGER.debugf("starting undertow server %s", this);
    xnio = Xnio.getInstance(Undertow.class.getClassLoader());
    channels = new ArrayList<>();
    try {
        if (internalWorker) {
            worker = xnio.createWorker(OptionMap.builder().set(Options.WORKER_IO_THREADS, ioThreads).set(Options.CONNECTION_HIGH_WATER, 1000000).set(Options.CONNECTION_LOW_WATER, 1000000).set(Options.WORKER_TASK_CORE_THREADS, workerThreads).set(Options.WORKER_TASK_MAX_THREADS, workerThreads).set(Options.TCP_NODELAY, true).set(Options.CORK, true).addAll(workerOptions).getMap());
        }
        OptionMap socketOptions = OptionMap.builder().set(Options.WORKER_IO_THREADS, worker.getIoThreadCount()).set(Options.TCP_NODELAY, true).set(Options.REUSE_ADDRESSES, true).set(Options.BALANCING_TOKENS, 1).set(Options.BALANCING_CONNECTIONS, 2).set(Options.BACKLOG, 1000).addAll(this.socketOptions).getMap();
        OptionMap serverOptions = OptionMap.builder().set(UndertowOptions.NO_REQUEST_TIMEOUT, 60 * 1000).addAll(this.serverOptions).getMap();
        ByteBufferPool buffers = new DefaultByteBufferPool(directBuffers, bufferSize, -1, 4);
        listenerInfo = new ArrayList<>();
        for (ListenerConfig listener : listeners) {
            UndertowLogger.ROOT_LOGGER.debugf("Configuring listener with protocol %s for interface %s and port %s", listener.type, listener.host, listener.port);
            final HttpHandler rootHandler = listener.rootHandler != null ? listener.rootHandler : this.rootHandler;
            if (listener.type == ListenerType.AJP) {
                AjpOpenListener openListener = new AjpOpenListener(buffers, serverOptions);
                openListener.setRootHandler(rootHandler);
                ChannelListener<AcceptingChannel<StreamConnection>> acceptListener = ChannelListeners.openListenerAdapter(openListener);
                OptionMap socketOptionsWithOverrides = OptionMap.builder().addAll(socketOptions).addAll(listener.overrideSocketOptions).getMap();
                AcceptingChannel<? extends StreamConnection> server = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port), acceptListener, socketOptionsWithOverrides);
                server.resumeAccepts();
                channels.add(server);
                listenerInfo.add(new ListenerInfo("ajp", server.getLocalAddress(), null, openListener));
            } else {
                OptionMap undertowOptions = OptionMap.builder().set(UndertowOptions.BUFFER_PIPELINED_DATA, true).addAll(serverOptions).getMap();
                if (listener.type == ListenerType.HTTP) {
                    HttpOpenListener openListener = new HttpOpenListener(buffers, undertowOptions);
                    openListener.setRootHandler(rootHandler);
                    ChannelListener<AcceptingChannel<StreamConnection>> acceptListener = ChannelListeners.openListenerAdapter(openListener);
                    OptionMap socketOptionsWithOverrides = OptionMap.builder().addAll(socketOptions).addAll(listener.overrideSocketOptions).getMap();
                    AcceptingChannel<? extends StreamConnection> server = worker.createStreamConnectionServer(new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port), acceptListener, socketOptionsWithOverrides);
                    server.resumeAccepts();
                    channels.add(server);
                    listenerInfo.add(new ListenerInfo("http", server.getLocalAddress(), null, openListener));
                } else if (listener.type == ListenerType.HTTPS) {
                    OpenListener openListener;
                    HttpOpenListener httpOpenListener = new HttpOpenListener(buffers, undertowOptions);
                    httpOpenListener.setRootHandler(rootHandler);
                    boolean http2 = serverOptions.get(UndertowOptions.ENABLE_HTTP2, false);
                    if (http2) {
                        AlpnOpenListener alpn = new AlpnOpenListener(buffers, undertowOptions, httpOpenListener);
                        if (http2) {
                            Http2OpenListener http2Listener = new Http2OpenListener(buffers, undertowOptions);
                            http2Listener.setRootHandler(rootHandler);
                            alpn.addProtocol(Http2OpenListener.HTTP2, http2Listener, 10);
                            alpn.addProtocol(Http2OpenListener.HTTP2_14, http2Listener, 7);
                        }
                        openListener = alpn;
                    } else {
                        openListener = httpOpenListener;
                    }
                    ChannelListener<AcceptingChannel<StreamConnection>> acceptListener = ChannelListeners.openListenerAdapter(openListener);
                    XnioSsl xnioSsl;
                    if (listener.sslContext != null) {
                        xnioSsl = new UndertowXnioSsl(xnio, OptionMap.create(Options.USE_DIRECT_BUFFERS, true), listener.sslContext);
                    } else {
                        xnioSsl = new UndertowXnioSsl(xnio, OptionMap.create(Options.USE_DIRECT_BUFFERS, true), JsseSslUtils.createSSLContext(listener.keyManagers, listener.trustManagers, new SecureRandom(), OptionMap.create(Options.USE_DIRECT_BUFFERS, true)));
                    }
                    OptionMap socketOptionsWithOverrides = OptionMap.builder().addAll(socketOptions).addAll(listener.overrideSocketOptions).getMap();
                    AcceptingChannel<SslConnection> sslServer = xnioSsl.createSslConnectionServer(worker, new InetSocketAddress(Inet4Address.getByName(listener.host), listener.port), (ChannelListener) acceptListener, socketOptionsWithOverrides);
                    sslServer.resumeAccepts();
                    channels.add(sslServer);
                    listenerInfo.add(new ListenerInfo("https", sslServer.getLocalAddress(), listener.sslContext, openListener));
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) ByteBufferPool(io.undertow.connector.ByteBufferPool) AlpnOpenListener(io.undertow.server.protocol.http.AlpnOpenListener) HttpHandler(io.undertow.server.HttpHandler) ChannelListener(org.xnio.ChannelListener) DefaultByteBufferPool(io.undertow.server.DefaultByteBufferPool) XnioSsl(org.xnio.ssl.XnioSsl) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) InetSocketAddress(java.net.InetSocketAddress) Http2OpenListener(io.undertow.server.protocol.http2.Http2OpenListener) AlpnOpenListener(io.undertow.server.protocol.http.AlpnOpenListener) AjpOpenListener(io.undertow.server.protocol.ajp.AjpOpenListener) OpenListener(io.undertow.server.OpenListener) HttpOpenListener(io.undertow.server.protocol.http.HttpOpenListener) SecureRandom(java.security.SecureRandom) Http2OpenListener(io.undertow.server.protocol.http2.Http2OpenListener) StreamConnection(org.xnio.StreamConnection) AjpOpenListener(io.undertow.server.protocol.ajp.AjpOpenListener) OptionMap(org.xnio.OptionMap) HttpOpenListener(io.undertow.server.protocol.http.HttpOpenListener) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) AcceptingChannel(org.xnio.channels.AcceptingChannel)

Aggregations

StreamConnection (org.xnio.StreamConnection)20 IOException (java.io.IOException)9 HttpServerExchange (io.undertow.server.HttpServerExchange)8 HttpUpgradeListener (io.undertow.server.HttpUpgradeListener)8 InetSocketAddress (java.net.InetSocketAddress)7 ChannelListener (org.xnio.ChannelListener)6 OptionMap (org.xnio.OptionMap)5 WebSocketChannel (io.undertow.websockets.core.WebSocketChannel)4 Handshake (io.undertow.websockets.core.protocol.Handshake)4 DefaultByteBufferPool (io.undertow.server.DefaultByteBufferPool)3 HttpOpenListener (io.undertow.server.protocol.http.HttpOpenListener)3 ConduitStreamSinkChannel (org.xnio.conduits.ConduitStreamSinkChannel)3 Http2Channel (io.undertow.protocols.http2.Http2Channel)2 HttpHandler (io.undertow.server.HttpHandler)2 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)2 DeploymentManager (io.undertow.servlet.api.DeploymentManager)2 FilterInfo (io.undertow.servlet.api.FilterInfo)2 ServletContainer (io.undertow.servlet.api.ServletContainer)2 ServletWebSocketHttpExchange (io.undertow.servlet.websockets.ServletWebSocketHttpExchange)2 Hybi07Handshake (io.undertow.websockets.core.protocol.version07.Hybi07Handshake)2