Search in sources :

Example 46 with ByteBuf

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf in project flink by apache.

the class KvStateServerTest method testSimpleRequest.

/**
	 * Tests a simple successful query via a SocketChannel.
	 */
@Test
public void testSimpleRequest() throws Exception {
    KvStateServer server = null;
    Bootstrap bootstrap = null;
    try {
        KvStateRegistry registry = new KvStateRegistry();
        KvStateRequestStats stats = new AtomicKvStateRequestStats();
        server = new KvStateServer(InetAddress.getLocalHost(), 0, 1, 1, registry, stats);
        server.start();
        KvStateServerAddress serverAddress = server.getAddress();
        int numKeyGroups = 1;
        AbstractStateBackend abstractBackend = new MemoryStateBackend();
        DummyEnvironment dummyEnv = new DummyEnvironment("test", 1, 0);
        dummyEnv.setKvStateRegistry(registry);
        AbstractKeyedStateBackend<Integer> backend = abstractBackend.createKeyedStateBackend(dummyEnv, new JobID(), "test_op", IntSerializer.INSTANCE, numKeyGroups, new KeyGroupRange(0, 0), registry.createTaskRegistry(new JobID(), new JobVertexID()));
        final KvStateServerHandlerTest.TestRegistryListener registryListener = new KvStateServerHandlerTest.TestRegistryListener();
        registry.registerListener(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 = KvStateRequestSerializer.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.getHost(), serverAddress.getPort()).sync().channel();
        long requestId = Integer.MAX_VALUE + 182828L;
        assertTrue(registryListener.registrationName.equals("vanilla"));
        ByteBuf request = KvStateRequestSerializer.serializeKvStateRequest(channel.alloc(), requestId, registryListener.kvStateId, serializedKeyAndNamespace);
        channel.writeAndFlush(request);
        ByteBuf buf = responses.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        assertEquals(KvStateRequestType.REQUEST_RESULT, KvStateRequestSerializer.deserializeHeader(buf));
        KvStateRequestResult response = KvStateRequestSerializer.deserializeKvStateRequestResult(buf);
        assertEquals(requestId, response.getRequestId());
        int actualValue = KvStateRequestSerializer.deserializeValue(response.getSerializedResult(), IntSerializer.INSTANCE);
        assertEquals(expectedValue, actualValue);
    } finally {
        if (server != null) {
            server.shutDown();
        }
        if (bootstrap != null) {
            EventLoopGroup group = bootstrap.group();
            if (group != null) {
                group.shutdownGracefully();
            }
        }
    }
}
Also used : KvStateRegistry(org.apache.flink.runtime.query.KvStateRegistry) KvStateRequestResult(org.apache.flink.runtime.query.netty.message.KvStateRequestResult) MemoryStateBackend(org.apache.flink.runtime.state.memory.MemoryStateBackend) JobVertexID(org.apache.flink.runtime.jobgraph.JobVertexID) KeyGroupRange(org.apache.flink.runtime.state.KeyGroupRange) KvStateServerAddress(org.apache.flink.runtime.query.KvStateServerAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ByteBuf(io.netty.buffer.ByteBuf) ValueStateDescriptor(org.apache.flink.api.common.state.ValueStateDescriptor) Bootstrap(io.netty.bootstrap.Bootstrap) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) AbstractStateBackend(org.apache.flink.runtime.state.AbstractStateBackend) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) DummyEnvironment(org.apache.flink.runtime.operators.testutils.DummyEnvironment) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) JobID(org.apache.flink.api.common.JobID) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 47 with ByteBuf

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf in project flink by apache.

the class KvStateRequestSerializerTest method testServerFailureSerialization.

/**
	 * Tests KvState server failure serialization.
	 */
@Test
public void testServerFailureSerialization() throws Exception {
    IllegalStateException cause = new IllegalStateException("Expected test");
    ByteBuf buf = KvStateRequestSerializer.serializeServerFailure(alloc, cause);
    int frameLength = buf.readInt();
    assertEquals(KvStateRequestType.SERVER_FAILURE, KvStateRequestSerializer.deserializeHeader(buf));
    Throwable request = KvStateRequestSerializer.deserializeServerFailure(buf);
    assertEquals(buf.readerIndex(), frameLength + 4);
    assertEquals(cause.getClass(), request.getClass());
    assertEquals(cause.getMessage(), request.getMessage());
}
Also used : ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Example 48 with ByteBuf

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf in project flink by apache.

the class KvStateRequestSerializerTest method testKvStateRequestSerializationWithZeroLengthKeyAndNamespace.

/**
	 * Tests KvState request serialization with zero-length serialized key and namespace.
	 */
@Test
public void testKvStateRequestSerializationWithZeroLengthKeyAndNamespace() throws Exception {
    byte[] serializedKeyAndNamespace = new byte[0];
    ByteBuf buf = KvStateRequestSerializer.serializeKvStateRequest(alloc, 1823, new KvStateID(), serializedKeyAndNamespace);
    int frameLength = buf.readInt();
    assertEquals(KvStateRequestType.REQUEST, KvStateRequestSerializer.deserializeHeader(buf));
    KvStateRequest request = KvStateRequestSerializer.deserializeKvStateRequest(buf);
    assertEquals(buf.readerIndex(), frameLength + 4);
    assertArrayEquals(serializedKeyAndNamespace, request.getSerializedKeyAndNamespace());
}
Also used : KvStateID(org.apache.flink.runtime.query.KvStateID) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Example 49 with ByteBuf

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf in project camel by apache.

the class LumberjackFrameDecoder method handleCompressedFrame.

private boolean handleCompressedFrame(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable(FRAME_COMPRESS_HEADER_LENGTH)) {
        return false;
    }
    int compressedPayloadLength = in.readInt();
    if (!in.isReadable(compressedPayloadLength)) {
        return false;
    }
    // decompress payload
    Inflater inflater = new Inflater();
    if (in.hasArray()) {
        inflater.setInput(in.array(), in.arrayOffset() + in.readerIndex(), compressedPayloadLength);
        in.skipBytes(compressedPayloadLength);
    } else {
        byte[] array = new byte[compressedPayloadLength];
        in.readBytes(array);
        inflater.setInput(array);
    }
    while (!inflater.finished()) {
        ByteBuf decompressed = ctx.alloc().heapBuffer(1024, 1024);
        byte[] outArray = decompressed.array();
        int count = inflater.inflate(outArray, decompressed.arrayOffset(), decompressed.writableBytes());
        decompressed.writerIndex(count);
        // put data in the pipeline
        out.add(decompressed);
    }
    return true;
}
Also used : Inflater(java.util.zip.Inflater) ByteBuf(io.netty.buffer.ByteBuf)

Example 50 with ByteBuf

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf in project flink by apache.

the class RuntimeMonitorHandler method respondAsLeader.

@Override
protected void respondAsLeader(ChannelHandlerContext ctx, Routed routed, ActorGateway jobManager) {
    FullHttpResponse response;
    try {
        // we only pass the first element in the list to the handlers.
        Map<String, String> queryParams = new HashMap<>();
        for (String key : routed.queryParams().keySet()) {
            queryParams.put(key, routed.queryParam(key));
        }
        Map<String, String> pathParams = new HashMap<>(routed.pathParams().size());
        for (String key : routed.pathParams().keySet()) {
            pathParams.put(key, URLDecoder.decode(routed.pathParams().get(key), ENCODING.toString()));
        }
        InetSocketAddress address = (InetSocketAddress) ctx.channel().localAddress();
        queryParams.put(WEB_MONITOR_ADDRESS_KEY, (httpsEnabled ? "https://" : "http://") + address.getHostName() + ":" + address.getPort());
        response = handler.handleRequest(pathParams, queryParams, jobManager);
    } catch (NotFoundException e) {
        // this should result in a 404 error code (not found)
        ByteBuf message = e.getMessage() == null ? Unpooled.buffer(0) : Unpooled.wrappedBuffer(e.getMessage().getBytes(ENCODING));
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, message);
        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
        LOG.debug("Error while handling request", e);
    } catch (Exception e) {
        byte[] bytes = ExceptionUtils.stringifyException(e).getBytes(ENCODING);
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(bytes));
        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
        LOG.debug("Error while handling request", e);
    }
    response.headers().set(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    // Content-Encoding:utf-8
    response.headers().set(HttpHeaders.Names.CONTENT_ENCODING, ENCODING.name());
    KeepAliveWrite.flush(ctx, routed.request(), response);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

ByteBuf (io.netty.buffer.ByteBuf)5080 Test (org.junit.Test)1813 Test (org.junit.jupiter.api.Test)680 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)377 ArrayList (java.util.ArrayList)301 IOException (java.io.IOException)297 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)200 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)182 ByteBuffer (java.nio.ByteBuffer)167 InetSocketAddress (java.net.InetSocketAddress)145 ByteBuf (org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf)144 Test (org.testng.annotations.Test)140 Channel (io.netty.channel.Channel)137 List (java.util.List)134 ChannelFuture (io.netty.channel.ChannelFuture)128 Map (java.util.Map)118 MatchEntryBuilder (org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntryBuilder)107 Position (org.traccar.model.Position)105 DeviceSession (org.traccar.DeviceSession)100 NetworkMessage (org.traccar.NetworkMessage)93