Search in sources :

Example 91 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project lispflowmapping by opendaylight.

the class LispXtrSouthboundHandlerTest method channelReadCompleteTest.

/**
 * Tests {@link LispXtrSouthboundHandler#channelReadComplete} method.
 */
@Test
public void channelReadCompleteTest() throws Exception {
    ChannelHandlerContext ctxMock = Mockito.mock(ChannelHandlerContext.class);
    handler.channelReadComplete(ctxMock);
    Mockito.verify(ctxMock).flush();
}
Also used : ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Test(org.junit.Test)

Example 92 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project LanternServer by LanternPowered.

the class QueryHandler method handleFullStats.

private void handleFullStats(ChannelHandlerContext ctx, DatagramPacket packet, int sessionId) {
    final LanternGame game = this.queryServer.getGame();
    final LanternServer server = game.getServer();
    final Platform platform = game.getPlatform();
    final PluginContainer api = platform.getContainer(Platform.Component.API);
    final PluginContainer impl = platform.getContainer(Platform.Component.IMPLEMENTATION);
    final PluginContainer mc = platform.getContainer(Platform.Component.GAME);
    final StringBuilder plugins = new StringBuilder().append(impl.getName()).append(" ").append(impl.getVersion()).append(" on ").append(api.getName()).append(" ").append(api.getVersion());
    if (this.showPlugins) {
        final List<PluginContainer> containers = new ArrayList<>(game.getPluginManager().getPlugins());
        containers.remove(api);
        containers.remove(impl);
        containers.remove(mc);
        char delim = ':';
        for (PluginContainer plugin : containers) {
            plugins.append(delim).append(' ').append(plugin.getName());
            delim = ';';
        }
    }
    final List<String> playerNames = server.getOnlinePlayers().stream().map(CommandSource::getName).collect(Collectors.toList());
    final Cause cause = Cause.of(EventContext.empty(), new SimpleRemoteConnection((InetSocketAddress) ctx.channel().remoteAddress(), null));
    final QueryServerEvent.Full event = SpongeEventFactory.createQueryServerEventFull(cause, (InetSocketAddress) ctx.channel().localAddress(), new HashMap<>(), "MINECRAFT", "SMP", getWorldName(), server.getMotd().toPlain(), playerNames, plugins.toString(), mc.getVersion().orElse("unknown"), server.getMaxPlayers(), Integer.MAX_VALUE, playerNames.size(), 0);
    final InetSocketAddress address = event.getAddress();
    final Map<String, Object> data = new LinkedHashMap<>();
    data.put("hostname", event.getMotd());
    data.put("gametype", event.getGameType());
    data.put("game_id", event.getGameId());
    data.put("version", event.getVersion());
    data.put("plugins", event.getPlugins());
    data.put("map", event.getMap());
    data.put("numplayers", event.getPlayerCount());
    data.put("maxplayers", event.getMaxPlayerCount());
    data.put("hostport", address.getPort());
    data.put("hostip", address.getHostString());
    event.getCustomValuesMap().entrySet().stream().filter(entry -> !data.containsKey(entry.getKey())).forEach(entry -> data.put(entry.getKey(), entry.getValue()));
    final ByteBuf buf = ctx.alloc().buffer();
    buf.writeByte(ACTION_STATS);
    buf.writeInt(sessionId);
    // constant: splitnum\x00\x80\x00
    buf.writeBytes(new byte[] { 0x73, 0x70, 0x6C, 0x69, 0x74, 0x6E, 0x75, 0x6D, 0x00, (byte) 0x80, 0x00 });
    for (Entry<String, Object> e : data.entrySet()) {
        writeString(buf, e.getKey());
        writeString(buf, String.valueOf(e.getValue()));
    }
    buf.writeByte(0);
    // constant: \x01player_\x00\x00
    buf.writeBytes(new byte[] { 0x01, 0x70, 0x6C, 0x61, 0x79, 0x65, 0x72, 0x5F, 0x00, 0x00 });
    for (Player player : game.getServer().getOnlinePlayers()) {
        writeString(buf, player.getName());
    }
    buf.writeByte(0);
    ctx.write(new DatagramPacket(buf, packet.sender()));
}
Also used : HashMap(java.util.HashMap) Platform(org.spongepowered.api.Platform) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) DatagramPacket(io.netty.channel.socket.DatagramPacket) PluginContainer(org.spongepowered.api.plugin.PluginContainer) SimpleRemoteConnection(org.lanternpowered.server.network.SimpleRemoteConnection) LanternServer(org.lanternpowered.server.LanternServer) CommandSource(org.spongepowered.api.command.CommandSource) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) Collection(java.util.Collection) Sponge(org.spongepowered.api.Sponge) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) LanternGame(org.lanternpowered.server.game.LanternGame) StandardCharsets(java.nio.charset.StandardCharsets) Cause(org.spongepowered.api.event.cause.Cause) List(java.util.List) QueryServerEvent(org.spongepowered.api.event.server.query.QueryServerEvent) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) World(org.spongepowered.api.world.World) Entry(java.util.Map.Entry) Player(org.spongepowered.api.entity.living.player.Player) EventContext(org.spongepowered.api.event.cause.EventContext) Player(org.spongepowered.api.entity.living.player.Player) PluginContainer(org.spongepowered.api.plugin.PluginContainer) Platform(org.spongepowered.api.Platform) SimpleRemoteConnection(org.lanternpowered.server.network.SimpleRemoteConnection) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) QueryServerEvent(org.spongepowered.api.event.server.query.QueryServerEvent) ByteBuf(io.netty.buffer.ByteBuf) LanternGame(org.lanternpowered.server.game.LanternGame) LinkedHashMap(java.util.LinkedHashMap) LanternServer(org.lanternpowered.server.LanternServer) Cause(org.spongepowered.api.event.cause.Cause) DatagramPacket(io.netty.channel.socket.DatagramPacket)

Example 93 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project LogHub by fbacchella.

the class TestServer method testSimple.

@Test(timeout = 2000)
public void testSimple() throws InterruptedException {
    Properties empty = new Properties(Collections.emptyMap());
    BlockingQueue<Event> receiver = new ArrayBlockingQueue<>(1);
    TesterReceiver r = new TesterReceiver(receiver, new Pipeline(Collections.emptyList(), "testone", null));
    r.configure(empty);
    final ChannelFuture[] sent = new ChannelFuture[1];
    EventLoopGroup workerGroup = new DefaultEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(LocalChannel.class);
    b.handler(new SimpleChannelInboundHandler<ByteBuf>() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            sent[0] = ctx.writeAndFlush(Unpooled.copiedBuffer("Message\r\n", CharsetUtil.UTF_8));
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        }
    });
    // Start the client.
    ChannelFuture f = b.connect(new LocalAddress(TestServer.class.getCanonicalName())).sync();
    Thread.sleep(100);
    sent[0].sync();
    f.channel().close();
    // Wait until the connection is closed.
    f.channel().closeFuture().sync();
    Event e = receiver.poll();
    Assert.assertEquals("Message", e.get("message"));
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) LocalAddress(io.netty.channel.local.LocalAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Properties(loghub.configuration.Properties) ByteBuf(io.netty.buffer.ByteBuf) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) IOException(java.io.IOException) Pipeline(loghub.Pipeline) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Event(loghub.Event) AbstractBootstrap(io.netty.bootstrap.AbstractBootstrap) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Test(org.junit.Test)

Example 94 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project bgpcep by opendaylight.

the class PCCDispatcherImpl method createClient.

@Override
@SuppressWarnings("unchecked")
public Future<PCEPSession> createClient(final InetSocketAddress remoteAddress, final long reconnectTime, final PCEPSessionListenerFactory listenerFactory, final PCEPSessionNegotiatorFactory negotiatorFactory, final KeyMapping keys, final InetSocketAddress localAddress, final BigInteger dbVersion) {
    final Bootstrap b = new Bootstrap();
    b.group(this.workerGroup);
    b.localAddress(localAddress);
    setChannelFactory(b, keys);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.RCVBUF_ALLOCATOR, new io.netty.channel.FixedRecvByteBufAllocator(1));
    final long retryTimer = reconnectTime == -1 ? 0 : reconnectTime;
    final PCCReconnectPromise promise = new PCCReconnectPromise(remoteAddress, (int) retryTimer, CONNECT_TIMEOUT, b);
    final ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel ch) {
            ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getDecoders());
            ch.pipeline().addLast("negotiator", negotiatorFactory.getSessionNegotiator(new PCEPSessionNegotiatorFactoryDependencies() {

                @Override
                public PCEPSessionListenerFactory getListenerFactory() {
                    return listenerFactory;
                }

                @Override
                public PCEPPeerProposal getPeerProposal() {
                    return new PCCPeerProposal(dbVersion);
                }
            }, ch, promise));
            ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getEncoders());
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelInactive(final ChannelHandlerContext ctx) {
                    if (promise.isCancelled()) {
                        return;
                    }
                    if (!promise.isInitialConnectFinished()) {
                        LOG.debug("Connection to {} was dropped during negotiation, reattempting", remoteAddress);
                        return;
                    }
                    LOG.debug("Reconnecting after connection to {} was dropped", remoteAddress);
                    PCCDispatcherImpl.this.createClient(remoteAddress, reconnectTime, listenerFactory, negotiatorFactory, keys, localAddress, dbVersion);
                }
            });
        }
    };
    b.handler(channelInitializer);
    promise.connect();
    return promise;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) PCEPSessionNegotiatorFactoryDependencies(org.opendaylight.protocol.pcep.PCEPSessionNegotiatorFactoryDependencies) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 95 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project drill by axbaretto.

the class UserServer method getHandshakeHandler.

@Override
protected ServerHandshakeHandler<UserToBitHandshake> getHandshakeHandler(final BitToUserConnection connection) {
    return new ServerHandshakeHandler<UserToBitHandshake>(RpcType.HANDSHAKE, UserToBitHandshake.PARSER) {

        @Override
        protected void consumeHandshake(ChannelHandlerContext ctx, UserToBitHandshake inbound) throws Exception {
            BitToUserHandshake handshakeResp = getHandshakeResponse(inbound);
            OutboundRpcMessage msg = new OutboundRpcMessage(RpcMode.RESPONSE, this.handshakeType, coordinationId, handshakeResp);
            ctx.writeAndFlush(msg);
            if (handshakeResp.getStatus() != HandshakeStatus.SUCCESS && handshakeResp.getStatus() != HandshakeStatus.AUTH_REQUIRED) {
                // If handling handshake results in an error, throw an exception to terminate the connection.
                throw new RpcException("Handshake request failed: " + handshakeResp.getErrorMessage());
            }
        }

        @Override
        public BitToUserHandshake getHandshakeResponse(UserToBitHandshake inbound) throws Exception {
            if (logger.isTraceEnabled()) {
                logger.trace("Handling handshake from user to bit. {}", serializeUserToBitHandshakeWithoutPassword(inbound));
            }
            // if timeout is unsupported or is set to false, disable timeout.
            if (!inbound.hasSupportTimeout() || !inbound.getSupportTimeout()) {
                connection.disableReadTimeout();
                logger.warn("Timeout Disabled as client doesn't support it.", connection.getName());
            }
            BitToUserHandshake.Builder respBuilder = BitToUserHandshake.newBuilder().setRpcVersion(UserRpcConfig.RPC_VERSION).setServerInfos(UserRpcUtils.getRpcEndpointInfos(SERVER_NAME)).addAllSupportedMethods(UserRpcConfig.SUPPORTED_SERVER_METHODS);
            try {
                if (inbound.getRpcVersion() != UserRpcConfig.RPC_VERSION) {
                    final String errMsg = String.format("Invalid rpc version. Expected %d, actual %d.", UserRpcConfig.RPC_VERSION, inbound.getRpcVersion());
                    return handleFailure(respBuilder, HandshakeStatus.RPC_VERSION_MISMATCH, errMsg, null);
                }
                connection.setHandshake(inbound);
                if (!config.isAuthEnabled()) {
                    connection.finalizeSession(inbound.getCredentials().getUserName());
                    respBuilder.setStatus(HandshakeStatus.SUCCESS);
                    return respBuilder.build();
                }
                // If sasl_support field is absent in handshake message then treat the client as < 1.10 client
                final boolean clientSupportsSasl = inbound.hasSaslSupport();
                // saslSupportOrdinal will be set to UNKNOWN_SASL_SUPPORT, if sasl_support field in handshake is set to a
                // value which is unknown to this server. We will treat those clients as one which knows SASL protocol.
                final int saslSupportOrdinal = (clientSupportsSasl) ? inbound.getSaslSupport().ordinal() : SaslSupport.UNKNOWN_SASL_SUPPORT.ordinal();
                // Check if client doesn't support SASL or only supports SASL_AUTH and server has encryption enabled
                if ((!clientSupportsSasl || saslSupportOrdinal == SaslSupport.SASL_AUTH.ordinal()) && config.isEncryptionEnabled()) {
                    throw new UserAuthenticationException("The server doesn't allow client without encryption support." + " Please upgrade your client or talk to your system administrator.");
                }
                if (!clientSupportsSasl) {
                    // for backward compatibility < 1.10
                    final String userName = inbound.getCredentials().getUserName();
                    if (logger.isTraceEnabled()) {
                        logger.trace("User {} on connection {} is likely using an older client.", userName, connection.getRemoteAddress());
                    }
                    try {
                        String password = "";
                        final UserProperties props = inbound.getProperties();
                        for (int i = 0; i < props.getPropertiesCount(); i++) {
                            Property prop = props.getProperties(i);
                            if (DrillProperties.PASSWORD.equalsIgnoreCase(prop.getKey())) {
                                password = prop.getValue();
                                break;
                            }
                        }
                        final PlainFactory plainFactory;
                        try {
                            plainFactory = (PlainFactory) config.getAuthProvider().getAuthenticatorFactory(PlainFactory.SIMPLE_NAME);
                        } catch (final SaslException e) {
                            throw new UserAuthenticationException("The server no longer supports username/password" + " based authentication. Please talk to your system administrator.");
                        }
                        plainFactory.getAuthenticator().authenticate(userName, password);
                        connection.changeHandlerTo(config.getMessageHandler());
                        connection.finalizeSession(userName);
                        respBuilder.setStatus(HandshakeStatus.SUCCESS);
                        if (logger.isTraceEnabled()) {
                            logger.trace("Authenticated {} successfully using PLAIN from {}", userName, connection.getRemoteAddress());
                        }
                        return respBuilder.build();
                    } catch (UserAuthenticationException ex) {
                        return handleFailure(respBuilder, HandshakeStatus.AUTH_FAILED, ex.getMessage(), ex);
                    }
                }
                // Offer all the configured mechanisms to client. If certain mechanism doesn't support encryption
                // like PLAIN, those should fail during the SASL handshake negotiation.
                respBuilder.addAllAuthenticationMechanisms(config.getAuthProvider().getAllFactoryNames());
                // set the encrypted flag in handshake message. For older clients this field is optional so will be ignored
                respBuilder.setEncrypted(connection.isEncryptionEnabled());
                respBuilder.setMaxWrappedSize(connection.getMaxWrappedSize());
                // for now, this means PLAIN credentials will be sent over twice
                // (during handshake and during sasl exchange)
                respBuilder.setStatus(HandshakeStatus.AUTH_REQUIRED);
                return respBuilder.build();
            } catch (Exception e) {
                return handleFailure(respBuilder, HandshakeStatus.UNKNOWN_FAILURE, e.getMessage(), e);
            }
        }
    };
}
Also used : PlainFactory(org.apache.drill.exec.rpc.security.plain.PlainFactory) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SaslException(javax.security.sasl.SaslException) RpcException(org.apache.drill.exec.rpc.RpcException) SaslException(javax.security.sasl.SaslException) UserAuthenticationException(org.apache.drill.exec.rpc.user.security.UserAuthenticationException) DrillbitStartupException(org.apache.drill.exec.exception.DrillbitStartupException) IOException(java.io.IOException) DrillException(org.apache.drill.common.exceptions.DrillException) UserToBitHandshake(org.apache.drill.exec.proto.UserProtos.UserToBitHandshake) UserAuthenticationException(org.apache.drill.exec.rpc.user.security.UserAuthenticationException) UserProperties(org.apache.drill.exec.proto.UserProtos.UserProperties) BitToUserHandshake(org.apache.drill.exec.proto.UserProtos.BitToUserHandshake) OutboundRpcMessage(org.apache.drill.exec.rpc.OutboundRpcMessage) RpcException(org.apache.drill.exec.rpc.RpcException) Property(org.apache.drill.exec.proto.UserProtos.Property)

Aggregations

ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)661 Channel (io.netty.channel.Channel)274 ByteBuf (io.netty.buffer.ByteBuf)234 ChannelFuture (io.netty.channel.ChannelFuture)210 Test (org.junit.Test)208 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)201 Bootstrap (io.netty.bootstrap.Bootstrap)177 InetSocketAddress (java.net.InetSocketAddress)160 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)156 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)154 Test (org.junit.jupiter.api.Test)153 ChannelPipeline (io.netty.channel.ChannelPipeline)151 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)141 AtomicReference (java.util.concurrent.atomic.AtomicReference)140 IOException (java.io.IOException)137 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)120 ClosedChannelException (java.nio.channels.ClosedChannelException)119 CountDownLatch (java.util.concurrent.CountDownLatch)115 ArrayList (java.util.ArrayList)113 List (java.util.List)111