Search in sources :

Example 1 with State

use of org.apache.flink.api.common.state.State in project flink by apache.

the class TtlVerifyUpdateFunction method performUpdate.

private TtlUpdateContext<?, ?> performUpdate(TtlStateVerifier<?, ?> verifier, Object update) throws Exception {
    return MonotonicTTLTimeProvider.doWithFrozenTime(frozenTimestamp -> {
        State state = states.get(verifier.getId());
        Object valueBeforeUpdate = verifier.get(state);
        verifier.update(state, update);
        Object updatedValue = verifier.get(state);
        return new TtlUpdateContext<>(valueBeforeUpdate, update, updatedValue, frozenTimestamp);
    });
}
Also used : ListState(org.apache.flink.api.common.state.ListState) State(org.apache.flink.api.common.state.State) TtlUpdateContext(org.apache.flink.streaming.tests.verify.TtlUpdateContext)

Example 2 with State

use of org.apache.flink.api.common.state.State in project flink by apache.

the class BatchExecutionKeyedStateBackend method setCurrentKey.

@Override
public void setCurrentKey(K newKey) {
    if (!Objects.equals(newKey, currentKey)) {
        notifyKeySelected(newKey);
        for (State value : states.values()) {
            ((AbstractBatchExecutionKeyState<?, ?, ?>) value).clearAllNamespaces();
        }
        for (KeyGroupedInternalPriorityQueue<?> value : priorityQueues.values()) {
            while (value.poll() != null) {
            // remove everything for the key
            }
        }
        this.currentKey = newKey;
    }
}
Also used : InternalKvState(org.apache.flink.runtime.state.internal.InternalKvState) State(org.apache.flink.api.common.state.State)

Example 3 with State

use of org.apache.flink.api.common.state.State in project flink by apache.

the class AbstractQueryableStateTestBase method testDuplicateRegistrationFailsJob.

/**
 * Tests that duplicate query registrations fail the job at the JobManager.
 */
@Test(timeout = 60_000)
public void testDuplicateRegistrationFailsJob() throws Exception {
    final int numKeys = 256;
    StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
    env.setStateBackend(stateBackend);
    env.setParallelism(maxParallelism);
    // Very important, because cluster is shared between tests and we
    // don't explicitly check that all slots are available before
    // submitting.
    env.setRestartStrategy(RestartStrategies.fixedDelayRestart(Integer.MAX_VALUE, 1000L));
    DataStream<Tuple2<Integer, Long>> source = env.addSource(new TestKeyRangeSource(numKeys));
    // Reducing state
    ReducingStateDescriptor<Tuple2<Integer, Long>> reducingState = new ReducingStateDescriptor<>("any-name", new SumReduce(), source.getType());
    final String queryName = "duplicate-me";
    final QueryableStateStream<Integer, Tuple2<Integer, Long>> queryableState = source.keyBy(new KeySelector<Tuple2<Integer, Long>, Integer>() {

        private static final long serialVersionUID = -4126824763829132959L;

        @Override
        public Integer getKey(Tuple2<Integer, Long> value) {
            return value.f0;
        }
    }).asQueryableState(queryName, reducingState);
    final QueryableStateStream<Integer, Tuple2<Integer, Long>> duplicate = source.keyBy(new KeySelector<Tuple2<Integer, Long>, Integer>() {

        private static final long serialVersionUID = -6265024000462809436L;

        @Override
        public Integer getKey(Tuple2<Integer, Long> value) {
            return value.f0;
        }
    }).asQueryableState(queryName);
    // Submit the job graph
    final JobGraph jobGraph = env.getStreamGraph().getJobGraph();
    clusterClient.submitJob(jobGraph).thenCompose(clusterClient::requestJobResult).thenApply(JobResult::getSerializedThrowable).thenAccept(serializedThrowable -> {
        assertTrue(serializedThrowable.isPresent());
        final Throwable t = serializedThrowable.get().deserializeError(getClass().getClassLoader());
        final String failureCause = ExceptionUtils.stringifyException(t);
        assertThat(failureCause, containsString("KvState with name '" + queryName + "' has already been registered by another operator"));
    }).get();
}
Also used : Deadline(org.apache.flink.api.common.time.Deadline) Arrays(java.util.Arrays) ReducingStateDescriptor(org.apache.flink.api.common.state.ReducingStateDescriptor) Tuple2(org.apache.flink.api.java.tuple.Tuple2) JobGraph(org.apache.flink.runtime.jobgraph.JobGraph) ClassLoaderUtils(org.apache.flink.testutils.ClassLoaderUtils) ExceptionUtils(org.apache.flink.util.ExceptionUtils) BasicTypeInfo(org.apache.flink.api.common.typeinfo.BasicTypeInfo) Assert.assertThat(org.junit.Assert.assertThat) ListState(org.apache.flink.api.common.state.ListState) AggregateFunction(org.apache.flink.api.common.functions.AggregateFunction) StateBackend(org.apache.flink.runtime.state.StateBackend) URLClassLoader(java.net.URLClassLoader) AggregatingState(org.apache.flink.api.common.state.AggregatingState) CheckpointListener(org.apache.flink.api.common.state.CheckpointListener) ReducingState(org.apache.flink.api.common.state.ReducingState) QueryableStateStream(org.apache.flink.streaming.api.datastream.QueryableStateStream) Duration(java.time.Duration) Map(java.util.Map) TestLogger(org.apache.flink.util.TestLogger) ListStateDescriptor(org.apache.flink.api.common.state.ListStateDescriptor) Assert.fail(org.junit.Assert.fail) TypeInformation(org.apache.flink.api.common.typeinfo.TypeInformation) ClassRule(org.junit.ClassRule) State(org.apache.flink.api.common.state.State) KeySelector(org.apache.flink.api.java.functions.KeySelector) ScheduledExecutor(org.apache.flink.util.concurrent.ScheduledExecutor) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) CancellationException(java.util.concurrent.CancellationException) Set(java.util.Set) CompletionException(java.util.concurrent.CompletionException) Preconditions(org.apache.flink.util.Preconditions) Executors(java.util.concurrent.Executors) Serializable(java.io.Serializable) TestingUtils(org.apache.flink.testutils.TestingUtils) VoidNamespaceSerializer(org.apache.flink.queryablestate.client.VoidNamespaceSerializer) List(java.util.List) ValueState(org.apache.flink.api.common.state.ValueState) ClusterClient(org.apache.flink.client.program.ClusterClient) OneInputStreamOperator(org.apache.flink.streaming.api.operators.OneInputStreamOperator) VoidNamespace(org.apache.flink.queryablestate.client.VoidNamespace) Time(org.apache.flink.api.common.time.Time) StreamExecutionEnvironment(org.apache.flink.streaming.api.environment.StreamExecutionEnvironment) AtomicLongArray(java.util.concurrent.atomic.AtomicLongArray) ScheduledExecutorServiceAdapter(org.apache.flink.util.concurrent.ScheduledExecutorServiceAdapter) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) JobStatus(org.apache.flink.api.common.JobStatus) RestartStrategies(org.apache.flink.api.common.restartstrategy.RestartStrategies) MapStateDescriptor(org.apache.flink.api.common.state.MapStateDescriptor) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) JobResult(org.apache.flink.runtime.jobmaster.JobResult) StreamRecord(org.apache.flink.streaming.runtime.streamrecord.StreamRecord) FutureUtils(org.apache.flink.util.concurrent.FutureUtils) Collector(org.apache.flink.util.Collector) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) RichParallelSourceFunction(org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ProcessFunction(org.apache.flink.streaming.api.functions.ProcessFunction) ReduceFunction(org.apache.flink.api.common.functions.ReduceFunction) AggregatingStateDescriptor(org.apache.flink.api.common.state.AggregatingStateDescriptor) Before(org.junit.Before) Serializer(com.esotericsoftware.kryo.Serializer) StateDescriptor(org.apache.flink.api.common.state.StateDescriptor) GenericTypeInfo(org.apache.flink.api.java.typeutils.GenericTypeInfo) ValueStateDescriptor(org.apache.flink.api.common.state.ValueStateDescriptor) Configuration(org.apache.flink.configuration.Configuration) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) UnknownKeyOrNamespaceException(org.apache.flink.queryablestate.exceptions.UnknownKeyOrNamespaceException) AbstractStreamOperator(org.apache.flink.streaming.api.operators.AbstractStreamOperator) DataStream(org.apache.flink.streaming.api.datastream.DataStream) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) JobID(org.apache.flink.api.common.JobID) Ignore(org.junit.Ignore) MapState(org.apache.flink.api.common.state.MapState) Assert(org.junit.Assert) QueryableStateClient(org.apache.flink.queryablestate.client.QueryableStateClient) TemporaryFolder(org.junit.rules.TemporaryFolder) Assert.assertEquals(org.junit.Assert.assertEquals) ReducingStateDescriptor(org.apache.flink.api.common.state.ReducingStateDescriptor) JobResult(org.apache.flink.runtime.jobmaster.JobResult) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) KeySelector(org.apache.flink.api.java.functions.KeySelector) JobGraph(org.apache.flink.runtime.jobgraph.JobGraph) Tuple2(org.apache.flink.api.java.tuple.Tuple2) AtomicLong(java.util.concurrent.atomic.AtomicLong) StreamExecutionEnvironment(org.apache.flink.streaming.api.environment.StreamExecutionEnvironment) Test(org.junit.Test)

Example 4 with State

use of org.apache.flink.api.common.state.State in project flink by apache.

the class MultiStateKeyIterator method remove.

/**
 * Removes the current key from <b>ALL</b> known states in the state backend.
 */
@Override
public void remove() {
    if (currentKey == null) {
        return;
    }
    for (StateDescriptor<?, ?> descriptor : descriptors) {
        try {
            State state = backend.getPartitionedState(VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, descriptor);
            state.clear();
        } catch (Exception e) {
            throw new RuntimeException("Failed to drop partitioned state from state backend", e);
        }
    }
}
Also used : State(org.apache.flink.api.common.state.State) IOException(java.io.IOException)

Example 5 with State

use of org.apache.flink.api.common.state.State in project flink by apache.

the class MockKeyedStateBackend method createInternalState.

@Override
@SuppressWarnings("unchecked")
@Nonnull
public <N, SV, SEV, S extends State, IS extends S> IS createInternalState(@Nonnull TypeSerializer<N> namespaceSerializer, @Nonnull StateDescriptor<S, SV> stateDesc, @Nonnull StateSnapshotTransformFactory<SEV> snapshotTransformFactory) throws Exception {
    StateFactory stateFactory = STATE_FACTORIES.get(stateDesc.getType());
    if (stateFactory == null) {
        String message = String.format("State %s is not supported by %s", stateDesc.getClass(), TtlStateFactory.class);
        throw new FlinkRuntimeException(message);
    }
    IS state = stateFactory.createInternalState(namespaceSerializer, stateDesc);
    stateSnapshotFilters.put(stateDesc.getName(), (StateSnapshotTransformer<Object>) getStateSnapshotTransformer(stateDesc, snapshotTransformFactory));
    ((MockInternalKvState<K, N, SV>) state).values = () -> stateValues.computeIfAbsent(stateDesc.getName(), n -> new HashMap<>()).computeIfAbsent(getCurrentKey(), k -> new HashMap<>());
    return state;
}
Also used : Tuple2(org.apache.flink.api.java.tuple.Tuple2) SharedStateRegistry(org.apache.flink.runtime.state.SharedStateRegistry) StateHandleID(org.apache.flink.runtime.state.StateHandleID) FutureTask(java.util.concurrent.FutureTask) HashMap(java.util.HashMap) MapStateDescriptor(org.apache.flink.api.common.state.MapStateDescriptor) KeyExtractorFunction(org.apache.flink.runtime.state.KeyExtractorFunction) InternalKeyContext(org.apache.flink.runtime.state.heap.InternalKeyContext) ArrayList(java.util.ArrayList) StateSnapshotTransformers(org.apache.flink.runtime.state.StateSnapshotTransformers) CloseableRegistry(org.apache.flink.core.fs.CloseableRegistry) HeapPriorityQueueSet(org.apache.flink.runtime.state.heap.HeapPriorityQueueSet) Map(java.util.Map) StateSnapshotTransformer(org.apache.flink.runtime.state.StateSnapshotTransformer) ListStateDescriptor(org.apache.flink.api.common.state.ListStateDescriptor) KeyGroupedInternalPriorityQueue(org.apache.flink.runtime.state.KeyGroupedInternalPriorityQueue) Nonnull(javax.annotation.Nonnull) LatencyTrackingStateConfig(org.apache.flink.runtime.state.metrics.LatencyTrackingStateConfig) State(org.apache.flink.api.common.state.State) RunnableFuture(java.util.concurrent.RunnableFuture) KeyGroupRange(org.apache.flink.runtime.state.KeyGroupRange) SnapshotResult(org.apache.flink.runtime.state.SnapshotResult) TaskKvStateRegistry(org.apache.flink.runtime.query.TaskKvStateRegistry) TypeSerializer(org.apache.flink.api.common.typeutils.TypeSerializer) StateDescriptor(org.apache.flink.api.common.state.StateDescriptor) Keyed(org.apache.flink.runtime.state.Keyed) StateSnapshotTransformFactory(org.apache.flink.runtime.state.StateSnapshotTransformer.StateSnapshotTransformFactory) FlinkRuntimeException(org.apache.flink.util.FlinkRuntimeException) KeyedStateHandle(org.apache.flink.runtime.state.KeyedStateHandle) CheckpointOptions(org.apache.flink.runtime.checkpoint.CheckpointOptions) Collectors(java.util.stream.Collectors) HeapPriorityQueueElement(org.apache.flink.runtime.state.heap.HeapPriorityQueueElement) Serializable(java.io.Serializable) TtlTimeProvider(org.apache.flink.runtime.state.ttl.TtlTimeProvider) List(java.util.List) PriorityComparator(org.apache.flink.runtime.state.PriorityComparator) Stream(java.util.stream.Stream) PriorityComparable(org.apache.flink.runtime.state.PriorityComparable) AbstractKeyedStateBackend(org.apache.flink.runtime.state.AbstractKeyedStateBackend) ExecutionConfig(org.apache.flink.api.common.ExecutionConfig) Optional(java.util.Optional) CheckpointStreamFactory(org.apache.flink.runtime.state.CheckpointStreamFactory) SavepointResources(org.apache.flink.runtime.state.SavepointResources) TtlStateFactory(org.apache.flink.runtime.state.ttl.TtlStateFactory) TtlStateFactory(org.apache.flink.runtime.state.ttl.TtlStateFactory) HashMap(java.util.HashMap) FlinkRuntimeException(org.apache.flink.util.FlinkRuntimeException) Nonnull(javax.annotation.Nonnull)

Aggregations

State (org.apache.flink.api.common.state.State)8 IOException (java.io.IOException)2 Serializable (java.io.Serializable)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 ExecutionConfig (org.apache.flink.api.common.ExecutionConfig)2 ListStateDescriptor (org.apache.flink.api.common.state.ListStateDescriptor)2 MapStateDescriptor (org.apache.flink.api.common.state.MapStateDescriptor)2 StateDescriptor (org.apache.flink.api.common.state.StateDescriptor)2 Tuple2 (org.apache.flink.api.java.tuple.Tuple2)2 FlinkRuntimeException (org.apache.flink.util.FlinkRuntimeException)2 Serializer (com.esotericsoftware.kryo.Serializer)1 URLClassLoader (java.net.URLClassLoader)1 Duration (java.time.Duration)1 Arrays (java.util.Arrays)1 HashSet (java.util.HashSet)1 Optional (java.util.Optional)1 Set (java.util.Set)1