Search in sources :

Example 1 with RetrievableStateHandle

use of org.apache.flink.runtime.state.RetrievableStateHandle in project flink by apache.

the class ZooKeeperStateHandleStoreITCase method testAddWithCreateMode.

/**
	 * Tests that {@link CreateMode} is respected.
	 */
@Test
public void testAddWithCreateMode() throws Exception {
    LongStateStorage longStateStorage = new LongStateStorage();
    ZooKeeperStateHandleStore<Long> store = new ZooKeeperStateHandleStore<Long>(ZooKeeper.getClient(), longStateStorage, Executors.directExecutor());
    // Config
    Long state = 3457347234L;
    CreateMode[] modes = CreateMode.values();
    for (int i = 0; i < modes.length; i++) {
        CreateMode mode = modes[i];
        state += i;
        String pathInZooKeeper = "/testAddWithCreateMode" + mode.name();
        // Test
        store.add(pathInZooKeeper, state, mode);
        if (mode.isSequential()) {
            // Figure out the sequential ID
            List<String> paths = ZooKeeper.getClient().getChildren().forPath("/");
            for (String p : paths) {
                if (p.startsWith("testAddWithCreateMode" + mode.name())) {
                    pathInZooKeeper = "/" + p;
                    break;
                }
            }
        }
        // Verify
        // State handle created
        assertEquals(i + 1, store.getAll().size());
        assertEquals(state, longStateStorage.getStateHandles().get(i).retrieveState());
        // Path created
        Stat stat = ZooKeeper.getClient().checkExists().forPath(pathInZooKeeper);
        assertNotNull(stat);
        // Is ephemeral or persistent
        if (mode.isEphemeral()) {
            assertTrue(stat.getEphemeralOwner() != 0);
        } else {
            assertEquals(0, stat.getEphemeralOwner());
        }
        // Data is equal
        @SuppressWarnings("unchecked") Long actual = ((RetrievableStateHandle<Long>) InstantiationUtil.deserializeObject(ZooKeeper.getClient().getData().forPath(pathInZooKeeper), ClassLoader.getSystemClassLoader())).retrieveState();
        assertEquals(state, actual);
    }
}
Also used : Stat(org.apache.zookeeper.data.Stat) CreateMode(org.apache.zookeeper.CreateMode) RetrievableStateHandle(org.apache.flink.runtime.state.RetrievableStateHandle) Test(org.junit.Test)

Example 2 with RetrievableStateHandle

use of org.apache.flink.runtime.state.RetrievableStateHandle in project flink by apache.

the class ZooKeeperCompletedCheckpointStoreTest method testRecoverFailsIfDownloadFails.

@Test
public void testRecoverFailsIfDownloadFails() {
    final Configuration configuration = new Configuration();
    configuration.setString(HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM, zooKeeperResource.getConnectString());
    final List<Tuple2<RetrievableStateHandle<CompletedCheckpoint>, String>> checkpointsInZk = new ArrayList<>();
    final ZooKeeperStateHandleStore<CompletedCheckpoint> checkpointsInZooKeeper = new ZooKeeperStateHandleStore<CompletedCheckpoint>(ZooKeeperUtils.startCuratorFramework(configuration, NoOpFatalErrorHandler.INSTANCE).asCuratorFramework(), new TestingRetrievableStateStorageHelper<>()) {

        @Override
        public List<Tuple2<RetrievableStateHandle<CompletedCheckpoint>, String>> getAllAndLock() {
            return checkpointsInZk;
        }
    };
    checkpointsInZk.add(createHandle(1, id -> {
        throw new ExpectedTestException();
    }));
    final Exception exception = assertThrows(Exception.class, () -> DefaultCompletedCheckpointStoreUtils.retrieveCompletedCheckpoints(checkpointsInZooKeeper, zooKeeperCheckpointStoreUtil));
    assertThat(exception, FlinkMatchers.containsCause(ExpectedTestException.class));
}
Also used : ZooKeeperUtils(org.apache.flink.runtime.util.ZooKeeperUtils) Tuple2(org.apache.flink.api.java.tuple.Tuple2) CuratorFramework(org.apache.flink.shaded.curator5.org.apache.curator.framework.CuratorFramework) Assert.assertThrows(org.junit.Assert.assertThrows) FlinkMatchers(org.apache.flink.core.testutils.FlinkMatchers) TestCompletedCheckpointStorageLocation(org.apache.flink.runtime.state.testutils.TestCompletedCheckpointStorageLocation) SharedStateRegistry(org.apache.flink.runtime.state.SharedStateRegistry) JobStatus(org.apache.flink.api.common.JobStatus) Function(java.util.function.Function) NEVER_RETAIN_AFTER_TERMINATION(org.apache.flink.runtime.checkpoint.CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION) ArrayList(java.util.ArrayList) TestLogger(org.apache.flink.util.TestLogger) ZooKeeperStateHandleStore(org.apache.flink.runtime.zookeeper.ZooKeeperStateHandleStore) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ClassRule(org.junit.ClassRule) Nonnull(javax.annotation.Nonnull) RetrievableStateHandle(org.apache.flink.runtime.state.RetrievableStateHandle) ExpectedTestException(org.apache.flink.runtime.operators.testutils.ExpectedTestException) Collections.emptyList(java.util.Collections.emptyList) Configuration(org.apache.flink.configuration.Configuration) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) Executors(org.apache.flink.util.concurrent.Executors) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) JobID(org.apache.flink.api.common.JobID) SharedStateRegistryImpl(org.apache.flink.runtime.state.SharedStateRegistryImpl) CuratorFrameworkWithUnhandledErrorListener(org.apache.flink.runtime.highavailability.zookeeper.CuratorFrameworkWithUnhandledErrorListener) NoOpFatalErrorHandler(org.apache.flink.runtime.rest.util.NoOpFatalErrorHandler) ZooKeeperResource(org.apache.flink.runtime.zookeeper.ZooKeeperResource) Collections(java.util.Collections) HighAvailabilityOptions(org.apache.flink.configuration.HighAvailabilityOptions) Assert.assertEquals(org.junit.Assert.assertEquals) ExpectedTestException(org.apache.flink.runtime.operators.testutils.ExpectedTestException) Configuration(org.apache.flink.configuration.Configuration) Tuple2(org.apache.flink.api.java.tuple.Tuple2) ZooKeeperStateHandleStore(org.apache.flink.runtime.zookeeper.ZooKeeperStateHandleStore) ArrayList(java.util.ArrayList) ExpectedTestException(org.apache.flink.runtime.operators.testutils.ExpectedTestException) Test(org.junit.Test)

Example 3 with RetrievableStateHandle

use of org.apache.flink.runtime.state.RetrievableStateHandle in project flink by apache.

the class KubernetesStateHandleStore method releaseAndTryRemoveAll.

/**
 * Remove all the state handle keys in the ConfigMap and discard the states.
 *
 * @throws Exception when removing the keys or discarding the state failed
 */
@Override
public void releaseAndTryRemoveAll() throws Exception {
    final List<RetrievableStateHandle<T>> validStateHandles = new ArrayList<>();
    kubeClient.checkAndUpdateConfigMap(configMapName, c -> {
        if (isValidOperation(c)) {
            final Map<String, String> updateData = new HashMap<>(c.getData());
            c.getData().entrySet().stream().filter(entry -> configMapKeyFilter.test(entry.getKey())).forEach(entry -> {
                try {
                    validStateHandles.add(deserializeObject(entry.getValue()));
                    updateData.remove(entry.getKey());
                } catch (IOException e) {
                    LOG.warn("ConfigMap {} contained corrupted data. Ignoring the key {}.", configMapName, entry.getKey());
                }
            });
            c.getData().clear();
            c.getData().putAll(updateData);
            return Optional.of(c);
        }
        return Optional.empty();
    }).whenComplete((succeed, ignore) -> {
        if (succeed) {
            Exception exception = null;
            for (RetrievableStateHandle<T> stateHandle : validStateHandles) {
                try {
                    stateHandle.discardState();
                } catch (Exception e) {
                    exception = ExceptionUtils.firstOrSuppressed(e, exception);
                }
            }
            if (exception != null) {
                throw new CompletionException(new KubernetesException("Could not properly remove all state handles.", exception));
            }
        }
    }).get();
}
Also used : Tuple2(org.apache.flink.api.java.tuple.Tuple2) LoggerFactory(org.slf4j.LoggerFactory) StateHandleStoreUtils.deserialize(org.apache.flink.runtime.util.StateHandleStoreUtils.deserialize) ExceptionUtils(org.apache.flink.util.ExceptionUtils) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) StringResourceVersion(org.apache.flink.runtime.persistence.StringResourceVersion) KubernetesConfigMap(org.apache.flink.kubernetes.kubeclient.resources.KubernetesConfigMap) ArrayList(java.util.ArrayList) Map(java.util.Map) StateHandleStore(org.apache.flink.runtime.persistence.StateHandleStore) Preconditions.checkNotNull(org.apache.flink.util.Preconditions.checkNotNull) Nullable(javax.annotation.Nullable) RetrievableStateHandle(org.apache.flink.runtime.state.RetrievableStateHandle) Logger(org.slf4j.Logger) Predicate(java.util.function.Predicate) Collection(java.util.Collection) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) Base64(java.util.Base64) List(java.util.List) StateHandleStoreUtils.serializeOrDiscard(org.apache.flink.runtime.util.StateHandleStoreUtils.serializeOrDiscard) KubernetesException(org.apache.flink.kubernetes.kubeclient.resources.KubernetesException) Optional(java.util.Optional) PossibleInconsistentStateException(org.apache.flink.runtime.persistence.PossibleInconsistentStateException) RetrievableStateStorageHelper(org.apache.flink.runtime.persistence.RetrievableStateStorageHelper) KubernetesLeaderElector(org.apache.flink.kubernetes.kubeclient.resources.KubernetesLeaderElector) Collections(java.util.Collections) FlinkKubeClient(org.apache.flink.kubernetes.kubeclient.FlinkKubeClient) HashMap(java.util.HashMap) RetrievableStateHandle(org.apache.flink.runtime.state.RetrievableStateHandle) CompletionException(java.util.concurrent.CompletionException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) KubernetesException(org.apache.flink.kubernetes.kubeclient.resources.KubernetesException) PossibleInconsistentStateException(org.apache.flink.runtime.persistence.PossibleInconsistentStateException) KubernetesException(org.apache.flink.kubernetes.kubeclient.resources.KubernetesException)

Example 4 with RetrievableStateHandle

use of org.apache.flink.runtime.state.RetrievableStateHandle in project flink by apache.

the class ZooKeeperStateHandleStoreTest method testGetAllSortedByName.

/**
 * Tests that the state is returned sorted.
 */
@Test
public void testGetAllSortedByName() throws Exception {
    // Setup
    final TestingLongStateHandleHelper stateHandleProvider = new TestingLongStateHandleHelper();
    ZooKeeperStateHandleStore<TestingLongStateHandleHelper.LongStateHandle> store = new ZooKeeperStateHandleStore<>(ZOOKEEPER.getClient(), stateHandleProvider);
    // Config
    final String basePath = "/testGetAllSortedByName";
    final Long[] expected = new Long[] { 311222268470898L, 132812888L, 27255442L, 11122233124L };
    // Test
    for (long val : expected) {
        final String pathInZooKeeper = String.format("%s%016d", basePath, val);
        store.addAndLock(pathInZooKeeper, new TestingLongStateHandleHelper.LongStateHandle(val));
    }
    List<Tuple2<RetrievableStateHandle<TestingLongStateHandleHelper.LongStateHandle>, String>> actual = store.getAllAndLock();
    assertEquals(expected.length, actual.size());
    // bring the elements in sort order
    Arrays.sort(expected);
    Collections.sort(actual, Comparator.comparing(o -> o.f1));
    for (int i = 0; i < expected.length; i++) {
        assertEquals(expected[i], (Long) actual.get(i).f0.retrieveState().getValue());
    }
}
Also used : ZooKeeperUtils(org.apache.flink.runtime.util.ZooKeeperUtils) Arrays(java.util.Arrays) Tuple2(org.apache.flink.api.java.tuple.Tuple2) CuratorFramework(org.apache.flink.shaded.curator5.org.apache.curator.framework.CuratorFramework) Assert.assertThrows(org.junit.Assert.assertThrows) KeeperException(org.apache.flink.shaded.zookeeper3.org.apache.zookeeper.KeeperException) Mockito.spy(org.mockito.Mockito.spy) HashSet(java.util.HashSet) Assert.assertThat(org.junit.Assert.assertThat) InstantiationUtil(org.apache.flink.util.InstantiationUtil) TestLogger(org.apache.flink.util.TestLogger) StateHandleStore(org.apache.flink.runtime.persistence.StateHandleStore) Assert.fail(org.junit.Assert.fail) IsInstanceOf(org.hamcrest.core.IsInstanceOf) Before(org.junit.Before) AfterClass(org.junit.AfterClass) Matchers.empty(org.hamcrest.Matchers.empty) RetrievableStateHandle(org.apache.flink.runtime.state.RetrievableStateHandle) Assert.assertNotNull(org.junit.Assert.assertNotNull) Collection(java.util.Collection) Configuration(org.apache.flink.configuration.Configuration) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) Stat(org.apache.flink.shaded.zookeeper3.org.apache.zookeeper.data.Stat) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) CuratorFrameworkWithUnhandledErrorListener(org.apache.flink.runtime.highavailability.zookeeper.CuratorFrameworkWithUnhandledErrorListener) PossibleInconsistentStateException(org.apache.flink.runtime.persistence.PossibleInconsistentStateException) RetrievableStateStorageHelper(org.apache.flink.runtime.persistence.RetrievableStateStorageHelper) TestingLongStateHandleHelper(org.apache.flink.runtime.persistence.TestingLongStateHandleHelper) Matchers.is(org.hamcrest.Matchers.is) NoOpFatalErrorHandler(org.apache.flink.runtime.rest.util.NoOpFatalErrorHandler) Comparator(java.util.Comparator) Collections(java.util.Collections) HighAvailabilityOptions(org.apache.flink.configuration.HighAvailabilityOptions) Assert.assertEquals(org.junit.Assert.assertEquals) IntegerResourceVersion(org.apache.flink.runtime.persistence.IntegerResourceVersion) TestingLongStateHandleHelper(org.apache.flink.runtime.persistence.TestingLongStateHandleHelper) Tuple2(org.apache.flink.api.java.tuple.Tuple2) Test(org.junit.Test)

Example 5 with RetrievableStateHandle

use of org.apache.flink.runtime.state.RetrievableStateHandle in project flink by apache.

the class DefaultJobGraphStoreTest method testOnAddedJobGraphShouldOnlyProcessUnknownJobGraphs.

@Test
public void testOnAddedJobGraphShouldOnlyProcessUnknownJobGraphs() throws Exception {
    final RetrievableStateHandle<JobGraph> stateHandle = jobGraphStorageHelper.store(testingJobGraph);
    final TestingStateHandleStore<JobGraph> stateHandleStore = builder.setGetFunction(ignore -> stateHandle).setAddFunction((ignore, state) -> jobGraphStorageHelper.store(state)).build();
    final JobGraphStore jobGraphStore = createAndStartJobGraphStore(stateHandleStore);
    jobGraphStore.recoverJobGraph(testingJobGraph.getJobID());
    // Known recovered job
    testingJobGraphStoreWatcher.addJobGraph(testingJobGraph.getJobID());
    // Unknown job
    final JobID unknownJobId = JobID.generate();
    testingJobGraphStoreWatcher.addJobGraph(unknownJobId);
    assertThat(testingJobGraphListener.getAddedJobGraphs().size(), is(1));
    assertThat(testingJobGraphListener.getAddedJobGraphs(), contains(unknownJobId));
}
Also used : FlinkException(org.apache.flink.util.FlinkException) Arrays(java.util.Arrays) Tuple3(org.apache.flink.api.java.tuple.Tuple3) FlinkMatchers(org.apache.flink.core.testutils.FlinkMatchers) JobGraph(org.apache.flink.runtime.jobgraph.JobGraph) TimeoutException(java.util.concurrent.TimeoutException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) Assert.assertThat(org.junit.Assert.assertThat) After(org.junit.After) Matchers.nullValue(org.hamcrest.Matchers.nullValue) JobGraphTestUtils(org.apache.flink.runtime.jobgraph.JobGraphTestUtils) TestLogger(org.apache.flink.util.TestLogger) StateHandleStore(org.apache.flink.runtime.persistence.StateHandleStore) Assert.fail(org.junit.Assert.fail) Before(org.junit.Before) RetrievableStateHandle(org.apache.flink.runtime.state.RetrievableStateHandle) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) AbstractID(org.apache.flink.util.AbstractID) Collection(java.util.Collection) Test(org.junit.Test) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) Executors(org.apache.flink.util.concurrent.Executors) List(java.util.List) JobID(org.apache.flink.api.common.JobID) TestingRetrievableStateStorageHelper(org.apache.flink.runtime.checkpoint.TestingRetrievableStateStorageHelper) Matchers.contains(org.hamcrest.Matchers.contains) Matchers.is(org.hamcrest.Matchers.is) IntegerResourceVersion(org.apache.flink.runtime.persistence.IntegerResourceVersion) TestingStateHandleStore(org.apache.flink.runtime.persistence.TestingStateHandleStore) JobGraph(org.apache.flink.runtime.jobgraph.JobGraph) JobID(org.apache.flink.api.common.JobID) Test(org.junit.Test)

Aggregations

RetrievableStateHandle (org.apache.flink.runtime.state.RetrievableStateHandle)13 Test (org.junit.Test)10 List (java.util.List)7 Collection (java.util.Collection)6 Tuple2 (org.apache.flink.api.java.tuple.Tuple2)6 StateHandleStore (org.apache.flink.runtime.persistence.StateHandleStore)6 Collections (java.util.Collections)5 Collectors (java.util.stream.Collectors)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 PossibleInconsistentStateException (org.apache.flink.runtime.persistence.PossibleInconsistentStateException)4 RetrievableStateStorageHelper (org.apache.flink.runtime.persistence.RetrievableStateStorageHelper)4 Serializable (java.io.Serializable)3 Arrays (java.util.Arrays)3 Base64 (java.util.Base64)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 Map (java.util.Map)3 Optional (java.util.Optional)3 TestLogger (org.apache.flink.util.TestLogger)3