Search in sources :

Example 6 with EventLoop

use of io.netty.channel.EventLoop in project ratpack by ratpack.

the class DefaultExecController method fork.

@Override
public ExecStarter fork() {
    return new ExecStarter() {

        private Action<? super Throwable> onError = LOG_UNCAUGHT;

        private Action<? super Execution> onComplete = noop();

        private Action<? super Execution> onStart = noop();

        private Action<? super RegistrySpec> registry = noop();

        private EventLoop eventLoop = getEventLoopGroup().next();

        @Override
        public ExecStarter eventLoop(EventLoop eventLoop) {
            this.eventLoop = eventLoop;
            return this;
        }

        @Override
        public ExecStarter onError(Action<? super Throwable> onError) {
            this.onError = onError;
            return this;
        }

        @Override
        public ExecStarter onComplete(Action<? super Execution> onComplete) {
            this.onComplete = onComplete;
            return this;
        }

        @Override
        public ExecStarter onStart(Action<? super Execution> onStart) {
            this.onStart = onStart;
            return this;
        }

        @Override
        public ExecStarter register(Action<? super RegistrySpec> action) {
            this.registry = action;
            return this;
        }

        @Override
        public void start(Action<? super Execution> initialExecutionSegment) {
            DefaultExecution current = DefaultExecution.get();
            DefaultExecution execution = createExecution(initialExecutionSegment, current == null ? null : current.getRef());
            if (eventLoop.inEventLoop() && current == null) {
                execution.drain();
            } else {
                eventLoop.submit(execution::drain);
            }
        }

        private DefaultExecution createExecution(Action<? super Execution> initialExecutionSegment, ExecutionRef parentRef) {
            try {
                return new DefaultExecution(DefaultExecController.this, parentRef, eventLoop, registry, initialExecutionSegment, onError, onStart, onComplete);
            } catch (Throwable e) {
                throw new InternalRatpackError("could not start execution", e);
            }
        }
    };
}
Also used : Action(ratpack.func.Action) EventLoop(io.netty.channel.EventLoop) InternalRatpackError(ratpack.util.internal.InternalRatpackError) RegistrySpec(ratpack.registry.RegistrySpec)

Example 7 with EventLoop

use of io.netty.channel.EventLoop in project ratpack by ratpack.

the class Blocking method get.

/**
 * Performs a blocking operation on a separate thread, returning a promise for its value.
 * <p>
 * This method should be used to perform blocking IO, or to perform any operation that synchronously waits for something to happen.
 * The given factory function will be executed on a thread from a special pool for such operations (i.e. not a thread from the main compute event loop).
 * <p>
 * The operation should do as little computation as possible.
 * It should just perform the blocking operation and immediately return the result.
 * Performing computation during the operation will degrade performance.
 *
 * @param factory the operation that blocks
 * @param <T> the type of value created by the operation
 * @return a promise for the return value of the given blocking operation
 */
public static <T> Promise<T> get(Factory<T> factory) {
    return new DefaultPromise<>(downstream -> {
        DefaultExecution execution = DefaultExecution.require();
        EventLoop eventLoop = execution.getEventLoop();
        execution.delimit(downstream::error, continuation -> eventLoop.execute(() -> CompletableFuture.supplyAsync(new Supplier<Result<T>>() {

            Result<T> result;

            @Override
            public Result<T> get() {
                try {
                    execution.bindToThread();
                    intercept(execution, execution.getAllInterceptors().iterator(), () -> {
                        try {
                            result = Result.success(factory.create());
                        } catch (Throwable e) {
                            result = Result.error(e);
                        }
                    });
                    return result;
                } catch (Throwable e) {
                    DefaultExecution.interceptorError(e);
                    return result;
                } finally {
                    execution.unbindFromThread();
                }
            }
        }, execution.getController().getBlockingExecutor()).thenAcceptAsync(v -> continuation.resume(() -> downstream.accept(v)), eventLoop)));
    });
}
Also used : EventLoop(io.netty.channel.EventLoop) DefaultExecution(ratpack.exec.internal.DefaultExecution) DefaultPromise(ratpack.exec.internal.DefaultPromise) Supplier(java.util.function.Supplier)

Example 8 with EventLoop

use of io.netty.channel.EventLoop in project bgpcep by opendaylight.

the class PeerTest method mockSession.

private void mockSession() {
    final EventLoop eventLoop = mock(EventLoop.class);
    final Channel channel = mock(Channel.class);
    final ChannelPipeline pipeline = mock(ChannelPipeline.class);
    doReturn(null).when(eventLoop).schedule(any(Runnable.class), any(long.class), any(TimeUnit.class));
    doReturn(eventLoop).when(channel).eventLoop();
    doReturn(Boolean.TRUE).when(channel).isWritable();
    doReturn(null).when(channel).close();
    doReturn(pipeline).when(channel).pipeline();
    doCallRealMethod().when(channel).toString();
    doReturn(pipeline).when(pipeline).addLast(any(ChannelHandler.class));
    doReturn(new DefaultChannelPromise(channel)).when(channel).writeAndFlush(any(Notification.class));
    doReturn(new InetSocketAddress("localhost", 12345)).when(channel).remoteAddress();
    doReturn(new InetSocketAddress("localhost", 12345)).when(channel).localAddress();
    final List<BgpParameters> params = Lists.newArrayList(new BgpParametersBuilder().setOptionalCapabilities(Lists.newArrayList(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class, new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder().setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class).build()).build()).build()).build())).build());
    final Open openObj = new OpenBuilder().setBgpIdentifier(new Ipv4Address("1.1.1.1")).setHoldTimer(50).setMyAsNumber(72).setBgpParameters(params).build();
    this.session = new BGPSessionImpl(this.classic, channel, openObj, 30, null);
    this.session.setChannelExtMsgCoder(openObj);
}
Also used : OptionalCapabilitiesBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.OptionalCapabilitiesBuilder) MultiprotocolCapabilityBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.mp.capabilities.MultiprotocolCapabilityBuilder) OpenBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.OpenBuilder) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) ChannelHandler(io.netty.channel.ChannelHandler) BgpParameters(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.BgpParameters) BgpParametersBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.BgpParametersBuilder) CParameters1(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.CParameters1) ChannelPipeline(io.netty.channel.ChannelPipeline) Notification(org.opendaylight.yangtools.yang.binding.Notification) Open(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.Open) CParametersBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.open.message.bgp.parameters.optional.capabilities.CParametersBuilder) CParameters1Builder(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.CParameters1Builder) EventLoop(io.netty.channel.EventLoop) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) TimeUnit(java.util.concurrent.TimeUnit) UnicastSubsequentAddressFamily(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily) Ipv4Address(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address)

Example 9 with EventLoop

use of io.netty.channel.EventLoop in project bgpcep by opendaylight.

the class BGPProtocolSessionPromise method reconnect.

synchronized void reconnect() {
    if (this.retryTimer == 0) {
        LOG.debug("Retry timer value is 0. Reconnection will not be attempted");
        this.setFailure(this.pending.cause());
        return;
    }
    final EventLoop loop = this.pending.channel().eventLoop();
    loop.schedule(() -> {
        synchronized (BGPProtocolSessionPromise.this) {
            if (BGPProtocolSessionPromise.this.peerSessionPresent) {
                LOG.debug("Connection to {} already exists", BGPProtocolSessionPromise.this.address);
                BGPProtocolSessionPromise.this.connectSkipped = true;
                return;
            }
            BGPProtocolSessionPromise.this.connectSkipped = false;
            LOG.debug("Attempting to connect to {}", BGPProtocolSessionPromise.this.address);
            final ChannelFuture reconnectFuture = BGPProtocolSessionPromise.this.bootstrap.connect();
            reconnectFuture.addListener(new BootstrapConnectListener());
            BGPProtocolSessionPromise.this.pending = reconnectFuture;
        }
    }, this.retryTimer, TimeUnit.SECONDS);
    LOG.debug("Next reconnection attempt in {}s", this.retryTimer);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) EventLoop(io.netty.channel.EventLoop)

Example 10 with EventLoop

use of io.netty.channel.EventLoop in project LanternServer by LanternPowered.

the class NetworkSession method send.

/**
 * Sends a iterable of {@link Message}s.
 *
 * @param messages The messages
 */
public void send(Iterable<Message> messages) {
    checkNotNull(messages, "messages");
    final Iterator<Message> it = messages.iterator();
    checkArgument(it.hasNext(), "messages cannot be empty");
    Message message = it.next();
    // Don't bother checking if we are in the event loop,
    // there is only one message.
    final ChannelPromise voidPromise = this.channel.voidPromise();
    if (!it.hasNext()) {
        this.channel.writeAndFlush(message, voidPromise);
    } else {
        final EventLoop eventLoop = this.channel.eventLoop();
        if (eventLoop.inEventLoop()) {
            for (Message message0 : messages) {
                this.channel.writeAndFlush(message0, voidPromise);
            }
        } else {
            // If there are more then one message, combine them inside the
            // event loop to reduce overhead of wakeup calls and object creation
            // Create a copy of the list, to avoid concurrent modifications
            final List<Message> messages0 = ImmutableList.copyOf(messages);
            eventLoop.submit(() -> {
                for (Message message0 : messages0) {
                    this.channel.writeAndFlush(message0, voidPromise);
                }
            });
        }
    }
}
Also used : EventLoop(io.netty.channel.EventLoop) HandlerMessage(org.lanternpowered.server.network.message.HandlerMessage) NullMessage(org.lanternpowered.server.network.message.NullMessage) Message(org.lanternpowered.server.network.message.Message) BulkMessage(org.lanternpowered.server.network.message.BulkMessage) ChannelPromise(io.netty.channel.ChannelPromise)

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