Search in sources :

Example 41 with EventLoop

use of io.netty.channel.EventLoop in project grpc-java by grpc.

the class NettyClientTransport method start.

@SuppressWarnings("unchecked")
@Override
public Runnable start(Listener transportListener) {
    lifecycleManager = new ClientTransportLifecycleManager(Preconditions.checkNotNull(transportListener, "listener"));
    EventLoop eventLoop = group.next();
    if (keepAliveTimeNanos != KEEPALIVE_TIME_NANOS_DISABLED) {
        keepAliveManager = new KeepAliveManager(new ClientKeepAlivePinger(this), eventLoop, keepAliveTimeNanos, keepAliveTimeoutNanos, keepAliveWithoutCalls);
    }
    handler = NettyClientHandler.newHandler(lifecycleManager, keepAliveManager, autoFlowControl, flowControlWindow, maxHeaderListSize, GrpcUtil.STOPWATCH_SUPPLIER, tooManyPingsRunnable, transportTracer, eagAttributes, authorityString, channelLogger);
    ChannelHandler negotiationHandler = negotiator.newHandler(handler);
    Bootstrap b = new Bootstrap();
    b.option(ALLOCATOR, Utils.getByteBufAllocator(false));
    b.group(eventLoop);
    b.channelFactory(channelFactory);
    // For non-socket based channel, the option will be ignored.
    b.option(SO_KEEPALIVE, true);
    // For non-epoll based channel, the option will be ignored.
    if (keepAliveTimeNanos != KEEPALIVE_TIME_NANOS_DISABLED) {
        ChannelOption<Integer> tcpUserTimeout = Utils.maybeGetTcpUserTimeoutOption();
        if (tcpUserTimeout != null) {
            b.option(tcpUserTimeout, (int) TimeUnit.NANOSECONDS.toMillis(keepAliveTimeoutNanos));
        }
    }
    for (Map.Entry<ChannelOption<?>, ?> entry : channelOptions.entrySet()) {
        // Every entry in the map is obtained from
        // NettyChannelBuilder#withOption(ChannelOption<T> option, T value)
        // so it is safe to pass the key-value pair to b.option().
        b.option((ChannelOption<Object>) entry.getKey(), entry.getValue());
    }
    ChannelHandler bufferingHandler = new WriteBufferingAndExceptionHandler(negotiationHandler);
    /**
     * We don't use a ChannelInitializer in the client bootstrap because its "initChannel" method
     * is executed in the event loop and we need this handler to be in the pipeline immediately so
     * that it may begin buffering writes.
     */
    b.handler(bufferingHandler);
    ChannelFuture regFuture = b.register();
    if (regFuture.isDone() && !regFuture.isSuccess()) {
        channel = null;
        // Initialization has failed badly. All new streams should be made to fail.
        Throwable t = regFuture.cause();
        if (t == null) {
            t = new IllegalStateException("Channel is null, but future doesn't have a cause");
        }
        statusExplainingWhyTheChannelIsNull = Utils.statusFromThrowable(t);
        // Use a Runnable since lifecycleManager calls transportListener
        return new Runnable() {

            @Override
            public void run() {
                // NOTICE: we not are calling lifecycleManager from the event loop. But there isn't really
                // an event loop in this case, so nothing should be accessing the lifecycleManager. We
                // could use GlobalEventExecutor (which is what regFuture would use for notifying
                // listeners in this case), but avoiding on-demand thread creation in an error case seems
                // a good idea and is probably clearer threading.
                lifecycleManager.notifyTerminated(statusExplainingWhyTheChannelIsNull);
            }
        };
    }
    channel = regFuture.channel();
    // Start the write queue as soon as the channel is constructed
    handler.startWriteQueue(channel);
    // This write will have no effect, yet it will only complete once the negotiationHandler
    // flushes any pending writes. We need it to be staged *before* the `connect` so that
    // the channel can't have been closed yet, removing all handlers. This write will sit in the
    // AbstractBufferingHandler's buffer, and will either be flushed on a successful connection,
    // or failed if the connection fails.
    channel.writeAndFlush(NettyClientHandler.NOOP_MESSAGE).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                // Need to notify of this failure, because NettyClientHandler may not have been added to
                // the pipeline before the error occurred.
                lifecycleManager.notifyTerminated(Utils.statusFromThrowable(future.cause()));
            }
        }
    });
    // Start the connection operation to the server.
    SocketAddress localAddress = localSocketPicker.createSocketAddress(remoteAddress, eagAttributes);
    if (localAddress != null) {
        channel.connect(remoteAddress, localAddress);
    } else {
        channel.connect(remoteAddress);
    }
    if (keepAliveManager != null) {
        keepAliveManager.onTransportStarted();
    }
    return null;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelOption(io.netty.channel.ChannelOption) ChannelHandler(io.netty.channel.ChannelHandler) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Http2ChannelClosedException(io.netty.handler.codec.http2.StreamBufferingEncoder.Http2ChannelClosedException) ClosedChannelException(java.nio.channels.ClosedChannelException) EventLoop(io.netty.channel.EventLoop) ClientKeepAlivePinger(io.grpc.internal.KeepAliveManager.ClientKeepAlivePinger) Bootstrap(io.netty.bootstrap.Bootstrap) KeepAliveManager(io.grpc.internal.KeepAliveManager) SocketAddress(java.net.SocketAddress) Map(java.util.Map)

Example 42 with EventLoop

use of io.netty.channel.EventLoop in project Glowstone by GlowstoneMC.

the class HttpClient method connect.

/**
 * Opens a URL.
 *
 * @param url       the URL to download
 * @param eventLoop an {@link EventLoop} that will receive the response body
 * @param callback  a callback to handle the response or any error
 */
public void connect(String url, EventLoop eventLoop, HttpCallback callback) {
    URI uri = URI.create(url);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    SslContext sslCtx = null;
    if ("https".equalsIgnoreCase(scheme)) {
        if (port == -1) {
            port = 443;
        }
        try {
            sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } catch (SSLException e) {
            callback.error(e);
            return;
        }
    } else if ("http".equalsIgnoreCase(scheme)) {
        if (port == -1) {
            port = 80;
        }
    } else {
        throw new IllegalArgumentException("Only http(s) is supported!");
    }
    new Bootstrap().group(eventLoop).resolver(resolverGroup).channel(Networking.bestSocketChannel()).handler(new HttpChannelInitializer(sslCtx, callback)).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).connect(InetSocketAddress.createUnresolved(host, port)).addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            String path = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery());
            HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
            request.headers().set(HttpHeaderNames.HOST, host);
            future.channel().writeAndFlush(request);
        } else {
            callback.error(future.cause());
        }
    });
}
Also used : HttpVersion(io.netty.handler.codec.http.HttpVersion) ChannelOption(io.netty.channel.ChannelOption) DnsServerAddressStreamProvider(io.netty.resolver.dns.DnsServerAddressStreamProvider) SequentialDnsServerAddressStreamProvider(io.netty.resolver.dns.SequentialDnsServerAddressStreamProvider) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SocketUtils(io.netty.util.internal.SocketUtils) URI(java.net.URI) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) SslContext(io.netty.handler.ssl.SslContext) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) HttpMethod(io.netty.handler.codec.http.HttpMethod) EventLoop(io.netty.channel.EventLoop) DnsServerAddressStreamProviders(io.netty.resolver.dns.DnsServerAddressStreamProviders) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) Networking(net.glowstone.net.Networking) SSLException(javax.net.ssl.SSLException) List(java.util.List) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) DnsEndpoint(net.glowstone.net.config.DnsEndpoint) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AllArgsConstructor(lombok.AllArgsConstructor) DnsAddressResolverGroup(io.netty.resolver.dns.DnsAddressResolverGroup) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Bootstrap(io.netty.bootstrap.Bootstrap) URI(java.net.URI) SSLException(javax.net.ssl.SSLException) DnsEndpoint(net.glowstone.net.config.DnsEndpoint) SslContext(io.netty.handler.ssl.SslContext)

Example 43 with EventLoop

use of io.netty.channel.EventLoop in project vert.x by eclipse.

the class HandlerManager method addHandler.

public synchronized void addHandler(T handler, ContextImpl context) {
    EventLoop worker = context.nettyEventLoop();
    availableWorkers.addWorker(worker);
    Handlers<T> handlers = new Handlers<>();
    Handlers<T> prev = handlerMap.putIfAbsent(worker, handlers);
    if (prev != null) {
        handlers = prev;
    }
    handlers.addHandler(new HandlerHolder<>(context, handler));
    hasHandlers = true;
}
Also used : EventLoop(io.netty.channel.EventLoop)

Example 44 with EventLoop

use of io.netty.channel.EventLoop in project vert.x by eclipse.

the class HandlerManager method removeHandler.

public synchronized void removeHandler(T handler, ContextImpl context) {
    EventLoop worker = context.nettyEventLoop();
    Handlers<T> handlers = handlerMap.get(worker);
    if (!handlers.removeHandler(new HandlerHolder<>(context, handler))) {
        throw new IllegalStateException("Can't find handler");
    }
    if (handlers.isEmpty()) {
        handlerMap.remove(worker);
    }
    if (handlerMap.isEmpty()) {
        hasHandlers = false;
    }
    //Available workers does it's own reference counting -since workers can be shared across different Handlers
    availableWorkers.removeWorker(worker);
}
Also used : EventLoop(io.netty.channel.EventLoop)

Example 45 with EventLoop

use of io.netty.channel.EventLoop in project hbase by apache.

the class AsyncFSWALProvider method createAsyncWriter.

/**
   * public because of AsyncFSWAL. Should be package-private
   */
public static AsyncWriter createAsyncWriter(Configuration conf, FileSystem fs, Path path, boolean overwritable, EventLoop eventLoop) throws IOException {
    // Configuration already does caching for the Class lookup.
    Class<? extends AsyncWriter> logWriterClass = conf.getClass("hbase.regionserver.hlog.async.writer.impl", AsyncProtobufLogWriter.class, AsyncWriter.class);
    try {
        AsyncWriter writer = logWriterClass.getConstructor(EventLoop.class).newInstance(eventLoop);
        writer.init(fs, path, conf, overwritable);
        return writer;
    } catch (Exception e) {
        LOG.debug("Error instantiating log writer.", e);
        Throwables.propagateIfPossible(e, IOException.class);
        throw new IOException("cannot get log writer", e);
    }
}
Also used : EventLoop(io.netty.channel.EventLoop) IOException(java.io.IOException) IOException(java.io.IOException)

Aggregations

EventLoop (io.netty.channel.EventLoop)79 EventLoopGroup (io.netty.channel.EventLoopGroup)27 Test (org.junit.jupiter.api.Test)27 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)18 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)17 Bootstrap (io.netty.bootstrap.Bootstrap)11 Channel (io.netty.channel.Channel)11 InetSocketAddress (java.net.InetSocketAddress)11 InetAddress (java.net.InetAddress)9 ChannelFuture (io.netty.channel.ChannelFuture)7 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)7 ChannelPromise (io.netty.channel.ChannelPromise)6 ChannelFutureListener (io.netty.channel.ChannelFutureListener)5 LocalAddress (io.netty.channel.local.LocalAddress)5 ClosedChannelException (java.nio.channels.ClosedChannelException)5 HttpProcessingState (com.nike.riposte.server.http.HttpProcessingState)4 ChannelPipeline (io.netty.channel.ChannelPipeline)4 List (java.util.List)4 SingleThreadEventLoop (io.netty.channel.SingleThreadEventLoop)3 IOException (java.io.IOException)3