Search in sources :

Example 66 with LengthFieldBasedFrameDecoder

use of io.netty.handler.codec.LengthFieldBasedFrameDecoder in project flink by apache.

the class KvStateServerTest method testSimpleRequest.

/**
 * Tests a simple successful query via a SocketChannel.
 */
@Test
public void testSimpleRequest() throws Throwable {
    KvStateServerImpl server = null;
    Bootstrap bootstrap = null;
    try {
        KvStateRegistry registry = new KvStateRegistry();
        KvStateRequestStats stats = new AtomicKvStateRequestStats();
        server = new KvStateServerImpl(InetAddress.getLocalHost().getHostName(), Collections.singletonList(0).iterator(), 1, 1, registry, stats);
        server.start();
        InetSocketAddress serverAddress = server.getServerAddress();
        int numKeyGroups = 1;
        AbstractStateBackend abstractBackend = new MemoryStateBackend();
        DummyEnvironment dummyEnv = new DummyEnvironment("test", 1, 0);
        dummyEnv.setKvStateRegistry(registry);
        final JobID jobId = new JobID();
        AbstractKeyedStateBackend<Integer> backend = abstractBackend.createKeyedStateBackend(dummyEnv, jobId, "test_op", IntSerializer.INSTANCE, numKeyGroups, new KeyGroupRange(0, 0), registry.createTaskRegistry(jobId, new JobVertexID()), TtlTimeProvider.DEFAULT, new UnregisteredMetricsGroup(), Collections.emptyList(), new CloseableRegistry());
        final KvStateServerHandlerTest.TestRegistryListener registryListener = new KvStateServerHandlerTest.TestRegistryListener();
        registry.registerListener(jobId, registryListener);
        ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("any", IntSerializer.INSTANCE);
        desc.setQueryable("vanilla");
        ValueState<Integer> state = backend.getPartitionedState(VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, desc);
        // Update KvState
        int expectedValue = 712828289;
        int key = 99812822;
        backend.setCurrentKey(key);
        state.update(expectedValue);
        // Request
        byte[] serializedKeyAndNamespace = KvStateSerializer.serializeKeyAndNamespace(key, IntSerializer.INSTANCE, VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE);
        // Connect to the server
        final BlockingQueue<ByteBuf> responses = new LinkedBlockingQueue<>();
        bootstrap = createBootstrap(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4), new ChannelInboundHandlerAdapter() {

            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                responses.add((ByteBuf) msg);
            }
        });
        Channel channel = bootstrap.connect(serverAddress.getAddress(), serverAddress.getPort()).sync().channel();
        long requestId = Integer.MAX_VALUE + 182828L;
        assertTrue(registryListener.registrationName.equals("vanilla"));
        final KvStateInternalRequest request = new KvStateInternalRequest(registryListener.kvStateId, serializedKeyAndNamespace);
        ByteBuf serializeRequest = MessageSerializer.serializeRequest(channel.alloc(), requestId, request);
        channel.writeAndFlush(serializeRequest);
        ByteBuf buf = responses.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        assertEquals(MessageType.REQUEST_RESULT, MessageSerializer.deserializeHeader(buf));
        assertEquals(requestId, MessageSerializer.getRequestId(buf));
        KvStateResponse response = server.getSerializer().deserializeResponse(buf);
        int actualValue = KvStateSerializer.deserializeValue(response.getContent(), IntSerializer.INSTANCE);
        assertEquals(expectedValue, actualValue);
    } finally {
        if (server != null) {
            server.shutdown();
        }
        if (bootstrap != null) {
            EventLoopGroup group = bootstrap.group();
            if (group != null) {
                // note: no "quiet period" to not trigger Netty#4357
                group.shutdownGracefully(0, 10, TimeUnit.SECONDS);
            }
        }
    }
}
Also used : KvStateRegistry(org.apache.flink.runtime.query.KvStateRegistry) UnregisteredMetricsGroup(org.apache.flink.metrics.groups.UnregisteredMetricsGroup) InetSocketAddress(java.net.InetSocketAddress) MemoryStateBackend(org.apache.flink.runtime.state.memory.MemoryStateBackend) JobVertexID(org.apache.flink.runtime.jobgraph.JobVertexID) KeyGroupRange(org.apache.flink.runtime.state.KeyGroupRange) ChannelHandlerContext(org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext) CloseableRegistry(org.apache.flink.core.fs.CloseableRegistry) ByteBuf(org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) AtomicKvStateRequestStats(org.apache.flink.queryablestate.network.stats.AtomicKvStateRequestStats) KvStateRequestStats(org.apache.flink.queryablestate.network.stats.KvStateRequestStats) KvStateServerImpl(org.apache.flink.queryablestate.server.KvStateServerImpl) ValueStateDescriptor(org.apache.flink.api.common.state.ValueStateDescriptor) Bootstrap(org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap) KvStateResponse(org.apache.flink.queryablestate.messages.KvStateResponse) LengthFieldBasedFrameDecoder(org.apache.flink.shaded.netty4.io.netty.handler.codec.LengthFieldBasedFrameDecoder) AbstractStateBackend(org.apache.flink.runtime.state.AbstractStateBackend) NioSocketChannel(org.apache.flink.shaded.netty4.io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel) Channel(org.apache.flink.shaded.netty4.io.netty.channel.Channel) DummyEnvironment(org.apache.flink.runtime.operators.testutils.DummyEnvironment) EventLoopGroup(org.apache.flink.shaded.netty4.io.netty.channel.EventLoopGroup) NioEventLoopGroup(org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup) KvStateInternalRequest(org.apache.flink.queryablestate.messages.KvStateInternalRequest) AtomicKvStateRequestStats(org.apache.flink.queryablestate.network.stats.AtomicKvStateRequestStats) JobID(org.apache.flink.api.common.JobID) ChannelInboundHandlerAdapter(org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 67 with LengthFieldBasedFrameDecoder

use of io.netty.handler.codec.LengthFieldBasedFrameDecoder in project netty by netty.

the class LengthFieldBasedFrameDecoderTest method testFailSlowTooLongFrameRecovery.

@Test
public void testFailSlowTooLongFrameRecovery() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new LengthFieldBasedFrameDecoder(5, 0, 4, 0, 4, false));
    for (int i = 0; i < 2; i++) {
        assertFalse(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 0, 0, 2 })));
        try {
            assertTrue(ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 0 })));
            fail(DecoderException.class.getSimpleName() + " must be raised.");
        } catch (TooLongFrameException e) {
        // Expected
        }
        ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 0, 0, 0, 1, 'A' }));
        ByteBuf buf = ch.readInbound();
        assertEquals("A", buf.toString(CharsetUtil.ISO_8859_1));
        buf.release();
    }
}
Also used : TooLongFrameException(io.netty.handler.codec.TooLongFrameException) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ByteBuf(io.netty.buffer.ByteBuf) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) Test(org.junit.jupiter.api.Test)

Example 68 with LengthFieldBasedFrameDecoder

use of io.netty.handler.codec.LengthFieldBasedFrameDecoder in project JaPS by JackWhite20.

the class ServerChannelInitializer method initChannel.

@Override
protected void initChannel(Channel channel) throws Exception {
    try {
        channel.config().setOption(ChannelOption.IP_TOS, 0x18);
    } catch (ChannelException e) {
    // Not supported
    }
    channel.config().setAllocator(PooledByteBufAllocator.DEFAULT);
    channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4));
    channel.pipeline().addLast(new JSONObjectDecoder());
    channel.pipeline().addLast(new LengthFieldPrepender(4));
    channel.pipeline().addLast(new JSONObjectEncoder());
    channel.pipeline().addLast(new Connection(jaPSServer, channel));
}
Also used : JSONObjectEncoder(de.jackwhite20.japs.shared.pipeline.handler.JSONObjectEncoder) Connection(de.jackwhite20.japs.server.network.Connection) JSONObjectDecoder(de.jackwhite20.japs.shared.pipeline.handler.JSONObjectDecoder) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) ChannelException(io.netty.channel.ChannelException)

Example 69 with LengthFieldBasedFrameDecoder

use of io.netty.handler.codec.LengthFieldBasedFrameDecoder in project JaPS by JackWhite20.

the class ClientChannelInitializer method initChannel.

@Override
protected void initChannel(Channel channel) throws Exception {
    try {
        channel.config().setOption(ChannelOption.IP_TOS, 0x18);
    } catch (ChannelException e) {
    // Not supported
    }
    channel.config().setAllocator(PooledByteBufAllocator.DEFAULT);
    channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4));
    channel.pipeline().addLast(new JSONObjectDecoder());
    channel.pipeline().addLast(new LengthFieldPrepender(4));
    channel.pipeline().addLast(new JSONObjectEncoder());
    channel.pipeline().addLast(nioSocketClient);
}
Also used : JSONObjectEncoder(de.jackwhite20.japs.shared.pipeline.handler.JSONObjectEncoder) JSONObjectDecoder(de.jackwhite20.japs.shared.pipeline.handler.JSONObjectDecoder) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) ChannelException(io.netty.channel.ChannelException)

Example 70 with LengthFieldBasedFrameDecoder

use of io.netty.handler.codec.LengthFieldBasedFrameDecoder in project java by wavefrontHQ.

the class PushAgent method startPickleListener.

protected void startPickleListener(String strPort, ReportableEntityHandlerFactory handlerFactory, GraphiteFormatter formatter) {
    if (tokenAuthenticator.authRequired()) {
        logger.warning("Port: " + strPort + " (pickle format) is not compatible with HTTP authentication, ignoring");
        return;
    }
    int port = Integer.parseInt(strPort);
    registerPrefixFilter(strPort);
    registerTimestampFilter(strPort);
    // Set up a custom handler
    ChannelHandler channelHandler = new ChannelByteArrayHandler(new PickleProtocolDecoder("unknown", proxyConfig.getCustomSourceTags(), formatter.getMetricMangler(), port), handlerFactory.getHandler(HandlerKey.of(ReportableEntityType.POINT, strPort)), preprocessors.get(strPort), blockedPointsLogger);
    startAsManagedThread(port, new TcpIngester(createInitializer(ImmutableList.of(() -> new LengthFieldBasedFrameDecoder(ByteOrder.BIG_ENDIAN, 1000000, 0, 4, 0, 4, false), ByteArrayDecoder::new, () -> channelHandler), port, proxyConfig.getListenerIdleConnectionTimeout(), getSslContext(strPort)), port).withChildChannelOptions(childChannelOptions), "listener-binary-pickle-" + strPort);
    logger.info("listening on port: " + strPort + " for Graphite/pickle protocol metrics");
}
Also used : ChannelByteArrayHandler(com.wavefront.agent.listeners.ChannelByteArrayHandler) PickleProtocolDecoder(com.wavefront.ingester.PickleProtocolDecoder) ChannelHandler(io.netty.channel.ChannelHandler) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) ReportPoint(wavefront.report.ReportPoint) TcpIngester(com.wavefront.ingester.TcpIngester) ByteArrayDecoder(io.netty.handler.codec.bytes.ByteArrayDecoder)

Aggregations

LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)71 LengthFieldPrepender (io.netty.handler.codec.LengthFieldPrepender)37 SocketChannel (io.netty.channel.socket.SocketChannel)35 ChannelPipeline (io.netty.channel.ChannelPipeline)31 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)25 Bootstrap (io.netty.bootstrap.Bootstrap)20 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)20 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)19 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)18 Channel (io.netty.channel.Channel)14 ChannelFuture (io.netty.channel.ChannelFuture)14 EventLoopGroup (io.netty.channel.EventLoopGroup)14 StringEncoder (io.netty.handler.codec.string.StringEncoder)13 SslContext (io.netty.handler.ssl.SslContext)13 StringDecoder (io.netty.handler.codec.string.StringDecoder)12 IOException (java.io.IOException)11 EpollEventLoopGroup (io.netty.channel.epoll.EpollEventLoopGroup)9 CommandDecoder (io.pravega.shared.protocol.netty.CommandDecoder)8 CommandEncoder (io.pravega.shared.protocol.netty.CommandEncoder)8 ExceptionLoggingHandler (io.pravega.shared.protocol.netty.ExceptionLoggingHandler)7