Search in sources :

Example 1 with KvStateServerImpl

use of org.apache.flink.queryablestate.server.KvStateServerImpl in project flink by apache.

the class KvStateServerHandlerTest method testQueryExecutorShutDown.

/**
 * Tests the failure response on a rejected execution, because the query executor has been
 * closed.
 */
@Test
public void testQueryExecutorShutDown() throws Throwable {
    KvStateRegistry registry = new KvStateRegistry();
    AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats();
    KvStateServerImpl localTestServer = new KvStateServerImpl(InetAddress.getLocalHost().getHostName(), Collections.singletonList(0).iterator(), 1, 1, new KvStateRegistry(), new DisabledKvStateRequestStats());
    localTestServer.start();
    localTestServer.shutdown();
    assertTrue(localTestServer.getQueryExecutor().isTerminated());
    MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>(new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer());
    KvStateServerHandler handler = new KvStateServerHandler(localTestServer, registry, serializer, stats);
    EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler);
    int numKeyGroups = 1;
    AbstractStateBackend abstractBackend = new MemoryStateBackend();
    DummyEnvironment dummyEnv = new DummyEnvironment("test", 1, 0);
    dummyEnv.setKvStateRegistry(registry);
    KeyedStateBackend<Integer> backend = createKeyedStateBackend(registry, numKeyGroups, abstractBackend, dummyEnv);
    final TestRegistryListener registryListener = new TestRegistryListener();
    registry.registerListener(dummyEnv.getJobID(), registryListener);
    // Register state
    ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("any", IntSerializer.INSTANCE);
    desc.setQueryable("vanilla");
    backend.getPartitionedState(VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, desc);
    assertTrue(registryListener.registrationName.equals("vanilla"));
    KvStateInternalRequest request = new KvStateInternalRequest(registryListener.kvStateId, new byte[0]);
    ByteBuf serRequest = MessageSerializer.serializeRequest(channel.alloc(), 282872L, request);
    // Write the request and wait for the response
    channel.writeInbound(serRequest);
    ByteBuf buf = (ByteBuf) readInboundBlocking(channel);
    // skip frame length
    buf.skipBytes(4);
    // Verify the response
    assertEquals(MessageType.REQUEST_FAILURE, MessageSerializer.deserializeHeader(buf));
    RequestFailure response = MessageSerializer.deserializeRequestFailure(buf);
    buf.release();
    assertTrue(response.getCause().getMessage().contains("RejectedExecutionException"));
    assertEquals(1L, stats.getNumRequests());
    assertEquals(1L, stats.getNumFailed());
    localTestServer.shutdown();
}
Also used : KvStateRegistry(org.apache.flink.runtime.query.KvStateRegistry) MessageSerializer(org.apache.flink.queryablestate.network.messages.MessageSerializer) MemoryStateBackend(org.apache.flink.runtime.state.memory.MemoryStateBackend) EmbeddedChannel(org.apache.flink.shaded.netty4.io.netty.channel.embedded.EmbeddedChannel) DummyEnvironment(org.apache.flink.runtime.operators.testutils.DummyEnvironment) ByteBuf(org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf) KvStateServerImpl(org.apache.flink.queryablestate.server.KvStateServerImpl) ValueStateDescriptor(org.apache.flink.api.common.state.ValueStateDescriptor) KvStateServerHandler(org.apache.flink.queryablestate.server.KvStateServerHandler) KvStateInternalRequest(org.apache.flink.queryablestate.messages.KvStateInternalRequest) KvStateResponse(org.apache.flink.queryablestate.messages.KvStateResponse) RequestFailure(org.apache.flink.queryablestate.network.messages.RequestFailure) DisabledKvStateRequestStats(org.apache.flink.queryablestate.network.stats.DisabledKvStateRequestStats) AtomicKvStateRequestStats(org.apache.flink.queryablestate.network.stats.AtomicKvStateRequestStats) AbstractStateBackend(org.apache.flink.runtime.state.AbstractStateBackend) Test(org.junit.Test)

Example 2 with KvStateServerImpl

use of org.apache.flink.queryablestate.server.KvStateServerImpl in project flink by apache.

the class ClientTest method testClientServerIntegration.

/**
 * Tests multiple clients querying multiple servers until 100k queries have been processed. At
 * this point, the client is shut down and its verified that all ongoing requests are failed.
 */
@Test
public void testClientServerIntegration() throws Throwable {
    // Config
    final int numServers = 2;
    final int numServerEventLoopThreads = 2;
    final int numServerQueryThreads = 2;
    final int numClientEventLoopThreads = 4;
    final int numClientsTasks = 8;
    final int batchSize = 16;
    final int numKeyGroups = 1;
    AbstractStateBackend abstractBackend = new MemoryStateBackend();
    KvStateRegistry dummyRegistry = new KvStateRegistry();
    DummyEnvironment dummyEnv = new DummyEnvironment("test", 1, 0);
    dummyEnv.setKvStateRegistry(dummyRegistry);
    AbstractKeyedStateBackend<Integer> backend = abstractBackend.createKeyedStateBackend(dummyEnv, new JobID(), "test_op", IntSerializer.INSTANCE, numKeyGroups, new KeyGroupRange(0, 0), dummyRegistry.createTaskRegistry(new JobID(), new JobVertexID()), TtlTimeProvider.DEFAULT, new UnregisteredMetricsGroup(), Collections.emptyList(), new CloseableRegistry());
    AtomicKvStateRequestStats clientStats = new AtomicKvStateRequestStats();
    final MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>(new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer());
    Client<KvStateInternalRequest, KvStateResponse> client = null;
    ExecutorService clientTaskExecutor = null;
    final KvStateServerImpl[] server = new KvStateServerImpl[numServers];
    try {
        client = new Client<>("Test Client", numClientEventLoopThreads, serializer, clientStats);
        clientTaskExecutor = Executors.newFixedThreadPool(numClientsTasks);
        // Create state
        ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("any", IntSerializer.INSTANCE);
        desc.setQueryable("any");
        // Create servers
        KvStateRegistry[] registry = new KvStateRegistry[numServers];
        AtomicKvStateRequestStats[] serverStats = new AtomicKvStateRequestStats[numServers];
        final KvStateID[] ids = new KvStateID[numServers];
        for (int i = 0; i < numServers; i++) {
            registry[i] = new KvStateRegistry();
            serverStats[i] = new AtomicKvStateRequestStats();
            server[i] = new KvStateServerImpl(InetAddress.getLocalHost().getHostName(), Collections.singletonList(0).iterator(), numServerEventLoopThreads, numServerQueryThreads, registry[i], serverStats[i]);
            server[i].start();
            backend.setCurrentKey(1010 + i);
            // Value per server
            ValueState<Integer> state = backend.getPartitionedState(VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, desc);
            state.update(201 + i);
            // we know it must be a KvState but this is not exposed to the user via State
            InternalKvState<Integer, ?, Integer> kvState = (InternalKvState<Integer, ?, Integer>) state;
            // Register KvState (one state instance for all server)
            ids[i] = registry[i].registerKvState(new JobID(), new JobVertexID(), new KeyGroupRange(0, 0), "any", kvState, getClass().getClassLoader());
        }
        final Client<KvStateInternalRequest, KvStateResponse> finalClient = client;
        Callable<Void> queryTask = () -> {
            while (true) {
                if (Thread.interrupted()) {
                    throw new InterruptedException();
                }
                // Random server permutation
                List<Integer> random = new ArrayList<>();
                for (int j = 0; j < batchSize; j++) {
                    random.add(j);
                }
                Collections.shuffle(random);
                // Dispatch queries
                List<CompletableFuture<KvStateResponse>> futures = new ArrayList<>(batchSize);
                for (int j = 0; j < batchSize; j++) {
                    int targetServer = random.get(j) % numServers;
                    byte[] serializedKeyAndNamespace = KvStateSerializer.serializeKeyAndNamespace(1010 + targetServer, IntSerializer.INSTANCE, VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE);
                    KvStateInternalRequest request = new KvStateInternalRequest(ids[targetServer], serializedKeyAndNamespace);
                    futures.add(finalClient.sendRequest(server[targetServer].getServerAddress(), request));
                }
                // Verify results
                for (int j = 0; j < batchSize; j++) {
                    int targetServer = random.get(j) % numServers;
                    Future<KvStateResponse> future = futures.get(j);
                    byte[] buf = future.get().getContent();
                    int value = KvStateSerializer.deserializeValue(buf, IntSerializer.INSTANCE);
                    assertEquals(201L + targetServer, value);
                }
            }
        };
        // Submit tasks
        List<Future<Void>> taskFutures = new ArrayList<>();
        for (int i = 0; i < numClientsTasks; i++) {
            taskFutures.add(clientTaskExecutor.submit(queryTask));
        }
        long numRequests;
        while ((numRequests = clientStats.getNumRequests()) < 100_000L) {
            Thread.sleep(100L);
            LOG.info("Number of requests {}/100_000", numRequests);
        }
        try {
            client.shutdown().get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Assert.assertTrue(client.isEventGroupShutdown());
        final CombinableMatcher<Throwable> exceptionMatcher = either(FlinkMatchers.containsCause(ClosedChannelException.class)).or(FlinkMatchers.containsCause(IllegalStateException.class));
        for (Future<Void> future : taskFutures) {
            try {
                future.get();
                fail("Did not throw expected Exception after shut down");
            } catch (ExecutionException t) {
                assertThat(t, exceptionMatcher);
            }
        }
        assertEquals("Connection leak (client)", 0L, clientStats.getNumConnections());
        for (int i = 0; i < numServers; i++) {
            boolean success = false;
            int numRetries = 0;
            while (!success) {
                try {
                    assertEquals("Connection leak (server)", 0L, serverStats[i].getNumConnections());
                    success = true;
                } catch (Throwable t) {
                    if (numRetries < 10) {
                        LOG.info("Retrying connection leak check (server)");
                        Thread.sleep((numRetries + 1) * 50L);
                        numRetries++;
                    } else {
                        throw t;
                    }
                }
            }
        }
    } finally {
        if (client != null) {
            try {
                client.shutdown().get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Assert.assertTrue(client.isEventGroupShutdown());
        }
        for (int i = 0; i < numServers; i++) {
            if (server[i] != null) {
                server[i].shutdown();
            }
        }
        if (clientTaskExecutor != null) {
            clientTaskExecutor.shutdown();
        }
    }
}
Also used : KvStateRegistry(org.apache.flink.runtime.query.KvStateRegistry) MessageSerializer(org.apache.flink.queryablestate.network.messages.MessageSerializer) KeyGroupRange(org.apache.flink.runtime.state.KeyGroupRange) ArrayList(java.util.ArrayList) CloseableRegistry(org.apache.flink.core.fs.CloseableRegistry) KvStateServerImpl(org.apache.flink.queryablestate.server.KvStateServerImpl) ValueStateDescriptor(org.apache.flink.api.common.state.ValueStateDescriptor) KvStateID(org.apache.flink.queryablestate.KvStateID) List(java.util.List) ArrayList(java.util.ArrayList) KvStateInternalRequest(org.apache.flink.queryablestate.messages.KvStateInternalRequest) JobID(org.apache.flink.api.common.JobID) AtomicKvStateRequestStats(org.apache.flink.queryablestate.network.stats.AtomicKvStateRequestStats) UnregisteredMetricsGroup(org.apache.flink.metrics.groups.UnregisteredMetricsGroup) MemoryStateBackend(org.apache.flink.runtime.state.memory.MemoryStateBackend) JobVertexID(org.apache.flink.runtime.jobgraph.JobVertexID) KvStateResponse(org.apache.flink.queryablestate.messages.KvStateResponse) ExecutionException(java.util.concurrent.ExecutionException) AbstractStateBackend(org.apache.flink.runtime.state.AbstractStateBackend) DummyEnvironment(org.apache.flink.runtime.operators.testutils.DummyEnvironment) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) UnknownHostException(java.net.UnknownHostException) ExecutionException(java.util.concurrent.ExecutionException) InternalKvState(org.apache.flink.runtime.state.internal.InternalKvState) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) CompletableFuture(java.util.concurrent.CompletableFuture) Test(org.junit.Test)

Example 3 with KvStateServerImpl

use of org.apache.flink.queryablestate.server.KvStateServerImpl 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 4 with KvStateServerImpl

use of org.apache.flink.queryablestate.server.KvStateServerImpl in project flink by apache.

the class KvStateServerHandlerTest method setup.

@BeforeClass
public static void setup() {
    try {
        testServer = new KvStateServerImpl(InetAddress.getLocalHost().getHostName(), Collections.singletonList(0).iterator(), 1, 1, new KvStateRegistry(), new DisabledKvStateRequestStats());
        testServer.start();
    } catch (Throwable e) {
        e.printStackTrace();
    }
}
Also used : KvStateServerImpl(org.apache.flink.queryablestate.server.KvStateServerImpl) KvStateRegistry(org.apache.flink.runtime.query.KvStateRegistry) DisabledKvStateRequestStats(org.apache.flink.queryablestate.network.stats.DisabledKvStateRequestStats) BeforeClass(org.junit.BeforeClass)

Aggregations

KvStateServerImpl (org.apache.flink.queryablestate.server.KvStateServerImpl)4 KvStateRegistry (org.apache.flink.runtime.query.KvStateRegistry)4 ValueStateDescriptor (org.apache.flink.api.common.state.ValueStateDescriptor)3 KvStateInternalRequest (org.apache.flink.queryablestate.messages.KvStateInternalRequest)3 KvStateResponse (org.apache.flink.queryablestate.messages.KvStateResponse)3 AtomicKvStateRequestStats (org.apache.flink.queryablestate.network.stats.AtomicKvStateRequestStats)3 DummyEnvironment (org.apache.flink.runtime.operators.testutils.DummyEnvironment)3 AbstractStateBackend (org.apache.flink.runtime.state.AbstractStateBackend)3 MemoryStateBackend (org.apache.flink.runtime.state.memory.MemoryStateBackend)3 Test (org.junit.Test)3 JobID (org.apache.flink.api.common.JobID)2 CloseableRegistry (org.apache.flink.core.fs.CloseableRegistry)2 UnregisteredMetricsGroup (org.apache.flink.metrics.groups.UnregisteredMetricsGroup)2 MessageSerializer (org.apache.flink.queryablestate.network.messages.MessageSerializer)2 DisabledKvStateRequestStats (org.apache.flink.queryablestate.network.stats.DisabledKvStateRequestStats)2 JobVertexID (org.apache.flink.runtime.jobgraph.JobVertexID)2 KeyGroupRange (org.apache.flink.runtime.state.KeyGroupRange)2 ByteBuf (org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf)2 ConnectException (java.net.ConnectException)1 InetSocketAddress (java.net.InetSocketAddress)1