You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by tz...@apache.org on 2019/06/26 03:33:28 UTC
[flink] 08/20: [FLINK-12732] [state-processing-api] Add savepoint
reader for consuming partitioned operator state
This is an automated email from the ASF dual-hosted git repository.
tzulitai pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink.git
commit edb9f939a8c0f60d7c03adb86ec99a6685056205
Author: Seth Wiesman <sj...@gmail.com>
AuthorDate: Tue Jun 4 11:49:14 2019 -0500
[FLINK-12732] [state-processing-api] Add savepoint reader for consuming partitioned operator state
---
.../flink/util/concurrent/NeverCompleteFuture.java | 3 +
flink-libraries/flink-state-processing-api/pom.xml | 7 +
.../apache/flink/state/api/ExistingSavepoint.java | 74 ++++++
.../api/functions/KeyedStateReaderFunction.java | 82 +++++++
.../BufferingCollector.java} | 39 +--
.../state/api/input/KeyedStateInputFormat.java | 268 +++++++++++++++++++++
.../state/api/input/MultiStateKeyIterator.java | 89 +++++++
.../api/input/splits/KeyGroupRangeInputSplit.java | 78 ++++++
.../state/api/runtime/SavepointEnvironment.java | 32 +--
.../runtime/SavepointLocalRecoveryProvider.java | 2 +-
.../state/api/runtime/SavepointRuntimeContext.java | 25 +-
.../runtime/SavepointTaskManagerRuntimeInfo.java | 2 +-
.../api/runtime/SavepointTaskStateManager.java | 2 +-
...anagerRuntimeInfo.java => VoidTriggerable.java} | 34 ++-
.../state/api/SavepointReaderKeyedStateITCase.java | 212 ++++++++++++++++
.../state/api/input/BufferingCollectorTest.java | 45 ++++
.../state/api/input/KeyedStateInputFormatTest.java | 250 +++++++++++++++++++
.../state/api/input/MultiStateKeyIteratorTest.java | 126 ++++++++++
18 files changed, 1301 insertions(+), 69 deletions(-)
diff --git a/flink-core/src/main/java/org/apache/flink/util/concurrent/NeverCompleteFuture.java b/flink-core/src/main/java/org/apache/flink/util/concurrent/NeverCompleteFuture.java
index 1488c68..d5d0700 100644
--- a/flink-core/src/main/java/org/apache/flink/util/concurrent/NeverCompleteFuture.java
+++ b/flink-core/src/main/java/org/apache/flink/util/concurrent/NeverCompleteFuture.java
@@ -17,6 +17,8 @@
package org.apache.flink.util.concurrent;
+import org.apache.flink.annotation.Internal;
+
import javax.annotation.Nonnull;
import java.util.concurrent.CancellationException;
@@ -28,6 +30,7 @@ import java.util.concurrent.TimeoutException;
/**
* A future that never completes.
*/
+@Internal
public final class NeverCompleteFuture implements ScheduledFuture<Object> {
private final Object lock = new Object();
diff --git a/flink-libraries/flink-state-processing-api/pom.xml b/flink-libraries/flink-state-processing-api/pom.xml
index 385592b..41b3340 100644
--- a/flink-libraries/flink-state-processing-api/pom.xml
+++ b/flink-libraries/flink-state-processing-api/pom.xml
@@ -56,6 +56,13 @@ under the License.
<dependency>
<groupId>org.apache.flink</groupId>
+ <artifactId>flink-statebackend-rocksdb_${scala.binary.version}</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-java_${scala.binary.version}</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/ExistingSavepoint.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/ExistingSavepoint.java
index 15e9d07..9bfd997 100644
--- a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/ExistingSavepoint.java
+++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/ExistingSavepoint.java
@@ -18,17 +18,23 @@
package org.apache.flink.state.api;
import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.InvalidProgramException;
+import org.apache.flink.api.common.functions.InvalidTypesException;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
+import org.apache.flink.api.java.Utils;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.typeutils.TupleTypeInfo;
+import org.apache.flink.api.java.typeutils.TypeExtractor;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.state.StateBackend;
+import org.apache.flink.state.api.functions.KeyedStateReaderFunction;
import org.apache.flink.state.api.input.BroadcastStateInputFormat;
+import org.apache.flink.state.api.input.KeyedStateInputFormat;
import org.apache.flink.state.api.input.ListStateInputFormat;
import org.apache.flink.state.api.input.UnionStateInputFormat;
import org.apache.flink.state.api.runtime.metadata.OnDiskSavepointMetadata;
@@ -190,4 +196,72 @@ public class ExistingSavepoint {
BroadcastStateInputFormat<K, V> inputFormat = new BroadcastStateInputFormat<>(operatorState, descriptor);
return env.createInput(inputFormat, new TupleTypeInfo<>(keyTypeInfo, valueTypeInfo));
}
+
+ /*
+ * Read keyed state from an operator in a {@code Savepoint}.
+ * @param uid The uid of the operator.
+ * @param function The {@link KeyedStateReaderFunction} that is called for each key in state.
+ * @param <K> The type of the key in state.
+ * @param <OUT> The output type of the transform function.
+ * @return A {@code DataSet} of objects read from keyed state.
+ */
+ public <K, OUT> DataSet<OUT> readKeyedState(String uid, KeyedStateReaderFunction<K, OUT> function) throws IOException {
+
+ TypeInformation<K> keyTypeInfo;
+ TypeInformation<OUT> outType;
+
+ try {
+ keyTypeInfo = TypeExtractor.createTypeInfo(
+ KeyedStateReaderFunction.class,
+ function.getClass(), 0, null, null);
+ } catch (InvalidTypesException e) {
+ throw new InvalidProgramException(
+ "The key type of the KeyedStateReaderFunction could not be automatically determined. Please use " +
+ "Savepoint#readKeyedState(String, KeyedStateReaderFunction, TypeInformation, TypeInformation) instead.", e);
+ }
+
+ try {
+ outType = TypeExtractor.getUnaryOperatorReturnType(
+ function,
+ KeyedStateReaderFunction.class,
+ 0,
+ 1,
+ TypeExtractor.NO_INDEX,
+ keyTypeInfo,
+ Utils.getCallLocationName(),
+ false);
+ } catch (InvalidTypesException e) {
+ throw new InvalidProgramException(
+ "The output type of the KeyedStateReaderFunction could not be automatically determined. Please use " +
+ "Savepoint#readKeyedState(String, KeyedStateReaderFunction, TypeInformation, TypeInformation) instead.", e);
+ }
+
+ return readKeyedState(uid, function, keyTypeInfo, outType);
+ }
+
+ /**
+ * Read keyed state from an operator in a {@code Savepoint}.
+ * @param uid The uid of the operator.
+ * @param function The {@link KeyedStateReaderFunction} that is called for each key in state.
+ * @param keyTypeInfo The type information of the key in state.
+ * @param outTypeInfo The type information of the output of the transform reader function.
+ * @param <K> The type of the key in state.
+ * @param <OUT> The output type of the transform function.
+ * @return A {@code DataSet} of objects read from keyed state.
+ */
+ public <K, OUT> DataSet<OUT> readKeyedState(
+ String uid,
+ KeyedStateReaderFunction<K, OUT> function,
+ TypeInformation<K> keyTypeInfo,
+ TypeInformation<OUT> outTypeInfo) throws IOException {
+
+ OperatorState operatorState = metadata.getOperatorState(uid);
+ KeyedStateInputFormat<K, OUT> inputFormat = new KeyedStateInputFormat<>(
+ operatorState,
+ stateBackend,
+ keyTypeInfo,
+ function);
+
+ return env.createInput(inputFormat, outTypeInfo);
+ }
}
diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/functions/KeyedStateReaderFunction.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/functions/KeyedStateReaderFunction.java
new file mode 100644
index 0000000..0d227d7
--- /dev/null
+++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/functions/KeyedStateReaderFunction.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.state.api.functions;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.api.common.functions.AbstractRichFunction;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.util.Collector;
+
+/**
+ * A function that processes keys from a restored operator
+ *
+ * <p>For every key {@link #readKey(Object, Context, Collector)} is invoked. This can produce zero or more
+ * elements as output.
+ *
+ * <p><b>NOTE:</b> State descriptors must be eagerly registered in {@code open(Configuration)}. Any
+ * attempt to dynamically register states inside of {@code readKey} will result in a {@code
+ * RuntimeException}.
+ *
+ * <p><b>NOTE:</b> A {@code KeyedStateReaderFunction} is always a {@link
+ * org.apache.flink.api.common.functions.RichFunction}. Therefore, access to the {@link
+ * org.apache.flink.api.common.functions.RuntimeContext} is always available and setup and teardown
+ * methods can be implemented. See {@link
+ * org.apache.flink.api.common.functions.RichFunction#open(Configuration)} and {@link
+ * org.apache.flink.api.common.functions.RichFunction#close()}.
+ *
+ * @param <K> Type of the keys
+ * @param <OUT> Type of the output elements.
+ */
+@PublicEvolving
+public abstract class KeyedStateReaderFunction<K, OUT> extends AbstractRichFunction {
+
+ /**
+ * Initialization method for the function. It is called before {@link #readKey(Object,
+ * Context, Collector)} and thus suitable for one time setup work.
+ *
+ * <p>This is the only method that my register state descriptors within a {@code
+ * KeyedStateReaderFunction}.
+ */
+ public abstract void open(Configuration parameters) throws Exception;
+
+ /**
+ * Process one key from the restored state backend.
+ *
+ * <p>This function can read partitioned state from the restored state backend and output zero or
+ * more elements using the {@link Collector} parameter.
+ *
+ * @param key The input value.
+ * @param out The collector for returning result values.
+ * @throws Exception This method may throw exceptions. Throwing an exception will cause the
+ * operation to fail and may trigger recovery.
+ */
+ public abstract void readKey(K key, Context ctx, Collector<OUT> out) throws Exception;
+
+ /**
+ * Context that {@link KeyedStateReaderFunction}'s can use for getting additional data about an input
+ * record.
+ *
+ * <p>The context is only valid for the duration of a {@link
+ * KeyedStateReaderFunction#readKey(Object, Context, Collector)} call. Do not store the context and use
+ * afterwards!
+ */
+ public interface Context {
+ }
+}
+
diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskManagerRuntimeInfo.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/BufferingCollector.java
similarity index 52%
copy from flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskManagerRuntimeInfo.java
copy to flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/BufferingCollector.java
index 93362ab..fe1a7bc 100644
--- a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskManagerRuntimeInfo.java
+++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/BufferingCollector.java
@@ -16,36 +16,41 @@
* limitations under the License.
*/
-package org.apache.flink.state.api.runtime;
+package org.apache.flink.state.api.input;
-import org.apache.flink.configuration.Configuration;
-import org.apache.flink.runtime.io.disk.iomanager.IOManager;
-import org.apache.flink.runtime.taskmanager.TaskManagerRuntimeInfo;
+import org.apache.flink.util.Collector;
+
+import java.util.ArrayDeque;
+import java.util.Iterator;
+import java.util.Queue;
/**
- * A minimally implemented {@link TaskManagerRuntimeInfo} that provides the functionality required
- * to run the {@code savepoint-connector}.
+ * A collector that buffers elements in memory to be pulled later by downstream operators.
+ *
+ * @param <T> The type of the records being collected.
*/
-class SavepointTaskManagerRuntimeInfo implements TaskManagerRuntimeInfo {
- private final IOManager ioManager;
+final class BufferingCollector<T> implements Collector<T>, Iterator<T> {
+ private final Queue<T> buffer;
- SavepointTaskManagerRuntimeInfo(IOManager ioManager) {
- this.ioManager = ioManager;
+ BufferingCollector() {
+ this.buffer = new ArrayDeque<>(1);
}
@Override
- public Configuration getConfiguration() {
- return new Configuration();
+ public boolean hasNext() {
+ return !buffer.isEmpty();
}
@Override
- public String[] getTmpDirectories() {
- return ioManager.getSpillingDirectoriesPaths();
+ public T next() {
+ return buffer.poll();
}
@Override
- public boolean shouldExitJvmOnOutOfMemoryError() {
- return false;
+ public void collect(T record) {
+ buffer.add(record);
}
-}
+ @Override
+ public void close() {}
+}
diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/KeyedStateInputFormat.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/KeyedStateInputFormat.java
new file mode 100644
index 0000000..f2733e1
--- /dev/null
+++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/KeyedStateInputFormat.java
@@ -0,0 +1,268 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.state.api.input;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.common.functions.util.FunctionUtils;
+import org.apache.flink.api.common.io.DefaultInputSplitAssigner;
+import org.apache.flink.api.common.io.RichInputFormat;
+import org.apache.flink.api.common.io.statistics.BaseStatistics;
+import org.apache.flink.api.common.state.StateDescriptor;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.fs.CloseableRegistry;
+import org.apache.flink.core.io.InputSplitAssigner;
+import org.apache.flink.runtime.checkpoint.OperatorState;
+import org.apache.flink.runtime.checkpoint.StateAssignmentOperation;
+import org.apache.flink.runtime.execution.Environment;
+import org.apache.flink.runtime.state.AbstractKeyedStateBackend;
+import org.apache.flink.runtime.state.DefaultKeyedStateStore;
+import org.apache.flink.runtime.state.KeyGroupRange;
+import org.apache.flink.runtime.state.KeyedStateHandle;
+import org.apache.flink.runtime.state.StateBackend;
+import org.apache.flink.state.api.functions.KeyedStateReaderFunction;
+import org.apache.flink.state.api.input.splits.KeyGroupRangeInputSplit;
+import org.apache.flink.state.api.runtime.NeverFireProcessingTimeService;
+import org.apache.flink.state.api.runtime.SavepointEnvironment;
+import org.apache.flink.state.api.runtime.SavepointRuntimeContext;
+import org.apache.flink.streaming.api.operators.KeyContext;
+import org.apache.flink.streaming.api.operators.StreamOperatorStateContext;
+import org.apache.flink.streaming.api.operators.StreamTaskStateInitializer;
+import org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl;
+import org.apache.flink.util.CollectionUtil;
+import org.apache.flink.util.Preconditions;
+
+import javax.annotation.Nonnull;
+
+import java.io.IOException;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * Input format for reading partitioned state.
+ *
+ * @param <K> The type of the key.
+ * @param <OUT> The type of the output of the {@link KeyedStateReaderFunction}.
+ */
+@Internal
+public class KeyedStateInputFormat<K, OUT> extends RichInputFormat<OUT, KeyGroupRangeInputSplit> implements KeyContext {
+
+ private final OperatorState operatorState;
+
+ private final StateBackend stateBackend;
+
+ private final TypeInformation<K> keyType;
+
+ private final KeyedStateReaderFunction<K, OUT> userFunction;
+
+ private transient TypeSerializer<K> keySerializer;
+
+ private transient CloseableRegistry registry;
+
+ private transient BufferingCollector<OUT> out;
+
+ private transient Iterator<K> keys;
+
+ private transient AbstractKeyedStateBackend<K> keyedStateBackend;
+
+ private transient Context ctx;
+
+ /**
+ * Creates an input format for reading partitioned state from an operator in a savepoint.
+ *
+ * @param operatorState The state to be queried.
+ * @param stateBackend The state backed used to snapshot the operator.
+ * @param keyType The type information describing the key type.
+ * @param userFunction The {@link KeyedStateReaderFunction} called for each key in the operator.
+ */
+ public KeyedStateInputFormat(
+ OperatorState operatorState,
+ StateBackend stateBackend,
+ TypeInformation<K> keyType,
+ KeyedStateReaderFunction<K, OUT> userFunction) {
+ Preconditions.checkNotNull(operatorState, "The operator state cannot be null");
+ Preconditions.checkNotNull(stateBackend, "The state backend cannot be null");
+ Preconditions.checkNotNull(keyType, "The key type information cannot be null");
+ Preconditions.checkNotNull(userFunction, "The userfunction cannot be null");
+
+ this.operatorState = operatorState;
+ this.stateBackend = stateBackend;
+ this.keyType = keyType;
+ this.userFunction = userFunction;
+ }
+
+ @Override
+ public void configure(Configuration parameters) {
+ }
+
+ @Override
+ public InputSplitAssigner getInputSplitAssigner(KeyGroupRangeInputSplit[] inputSplits) {
+ return new DefaultInputSplitAssigner(inputSplits);
+ }
+
+ @Override
+ public BaseStatistics getStatistics(BaseStatistics cachedStatistics) {
+ return cachedStatistics;
+ }
+
+ @Override
+ public KeyGroupRangeInputSplit[] createInputSplits(int minNumSplits) throws IOException {
+ final int maxParallelism = operatorState.getMaxParallelism();
+
+ final List<KeyGroupRange> keyGroups = sortedKeyGroupRanges(minNumSplits, maxParallelism);
+
+ return CollectionUtil.mapWithIndex(
+ keyGroups,
+ (keyGroupRange, index) -> createKeyGroupRangeInputSplit(
+ operatorState,
+ maxParallelism,
+ keyGroupRange,
+ index)
+ ).toArray(KeyGroupRangeInputSplit[]::new);
+ }
+
+ @Override
+ public void openInputFormat() {
+ out = new BufferingCollector<>();
+ keySerializer = keyType.createSerializer(getRuntimeContext().getExecutionConfig());
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public void open(KeyGroupRangeInputSplit split) throws IOException {
+ registry = new CloseableRegistry();
+
+ final Environment environment = new SavepointEnvironment
+ .Builder(getRuntimeContext(), split.getNumKeyGroups())
+ .setSubtaskIndex(split.getSplitNumber())
+ .setPrioritizedOperatorSubtaskState(split.getPrioritizedOperatorSubtaskState())
+ .build();
+
+ final StreamOperatorStateContext context = getStreamOperatorStateContext(environment);
+
+ keyedStateBackend = (AbstractKeyedStateBackend<K>) context.keyedStateBackend();
+
+ final DefaultKeyedStateStore keyedStateStore = new DefaultKeyedStateStore(keyedStateBackend, getRuntimeContext().getExecutionConfig());
+ SavepointRuntimeContext ctx = new SavepointRuntimeContext(getRuntimeContext(), keyedStateStore);
+ FunctionUtils.setFunctionRuntimeContext(userFunction, ctx);
+
+ keys = getKeyIterator(ctx);
+ this.ctx = new Context();
+ }
+
+ @SuppressWarnings("unchecked")
+ private Iterator<K> getKeyIterator(SavepointRuntimeContext ctx) throws IOException {
+ final List<StateDescriptor<?, ?>> stateDescriptors;
+ try {
+ FunctionUtils.openFunction(userFunction, new Configuration());
+ ctx.disableStateRegistration();
+ stateDescriptors = ctx.getStateDescriptors();
+ } catch (Exception e) {
+ throw new IOException("Failed to open user defined function", e);
+ }
+
+ return new MultiStateKeyIterator<>(stateDescriptors, keyedStateBackend);
+ }
+
+ private StreamOperatorStateContext getStreamOperatorStateContext(Environment environment) throws IOException {
+ StreamTaskStateInitializer initializer = new StreamTaskStateInitializerImpl(
+ environment,
+ stateBackend,
+ new NeverFireProcessingTimeService());
+
+ try {
+ return initializer.streamOperatorStateContext(
+ operatorState.getOperatorID(),
+ operatorState.getOperatorID().toString(),
+ this,
+ keySerializer,
+ registry,
+ getRuntimeContext().getMetricGroup());
+ } catch (Exception e) {
+ throw new IOException("Failed to restore state backend", e);
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ registry.close();
+ }
+
+ @Override
+ public boolean reachedEnd() {
+ return !out.hasNext() && !keys.hasNext();
+ }
+
+ @Override
+ public OUT nextRecord(OUT reuse) throws IOException {
+ if (out.hasNext()) {
+ return out.next();
+ }
+
+ final K key = keys.next();
+ setCurrentKey(key);
+
+ try {
+ userFunction.readKey(key, ctx, out);
+ } catch (Exception e) {
+ throw new IOException("User defined function KeyedStateReaderFunction#readKey threw an exception", e);
+ }
+
+ keys.remove();
+
+ return out.next();
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public void setCurrentKey(Object key) {
+ keyedStateBackend.setCurrentKey((K) key);
+ }
+
+ @Override
+ public Object getCurrentKey() {
+ return keyedStateBackend.getCurrentKey();
+ }
+
+ private static KeyGroupRangeInputSplit createKeyGroupRangeInputSplit(
+ OperatorState operatorState,
+ int maxParallelism,
+ KeyGroupRange keyGroupRange,
+ Integer index) {
+
+ final List<KeyedStateHandle> managedKeyedState = StateAssignmentOperation.getManagedKeyedStateHandles(operatorState, keyGroupRange);
+ final List<KeyedStateHandle> rawKeyedState = StateAssignmentOperation.getRawKeyedStateHandles(operatorState, keyGroupRange);
+
+ return new KeyGroupRangeInputSplit(managedKeyedState, rawKeyedState, maxParallelism, index);
+ }
+
+ @Nonnull
+ private static List<KeyGroupRange> sortedKeyGroupRanges(int minNumSplits, int maxParallelism) {
+ List<KeyGroupRange> keyGroups = StateAssignmentOperation.createKeyGroupPartitions(
+ maxParallelism,
+ Math.min(minNumSplits, maxParallelism));
+
+ keyGroups.sort(Comparator.comparing(KeyGroupRange::getStartKeyGroup));
+ return keyGroups;
+ }
+
+ private static class Context implements KeyedStateReaderFunction.Context {}
+}
diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/MultiStateKeyIterator.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/MultiStateKeyIterator.java
new file mode 100644
index 0000000..02b6b5b
--- /dev/null
+++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/MultiStateKeyIterator.java
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.state.api.input;
+
+import org.apache.flink.api.common.state.State;
+import org.apache.flink.api.common.state.StateDescriptor;
+import org.apache.flink.runtime.state.AbstractKeyedStateBackend;
+import org.apache.flink.runtime.state.VoidNamespace;
+import org.apache.flink.runtime.state.VoidNamespaceSerializer;
+
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * An iterator for reading all keys in a state backend across multiple partitioned states.
+ *
+ * <p>To read unique keys across all partitioned states callers must invoke {@link MultiStateKeyIterator#remove}.
+ *
+ * @param <K> Type of the key by which state is keyed.
+ */
+final class MultiStateKeyIterator<K> implements Iterator<K> {
+ private final List<? extends StateDescriptor<?, ?>> descriptors;
+
+ private final AbstractKeyedStateBackend<K> backend;
+
+ private final Iterator<K> internal;
+
+ private K currentKey;
+
+ MultiStateKeyIterator(List<? extends StateDescriptor<?, ?>> descriptors, AbstractKeyedStateBackend<K> backend) {
+ this.descriptors = descriptors;
+
+ this.backend = backend;
+
+ this.internal = descriptors
+ .stream()
+ .flatMap(descriptor -> backend.getKeys(descriptor.getName(), VoidNamespace.INSTANCE))
+ .iterator();
+ }
+
+ @Override
+ public boolean hasNext() {
+ return internal.hasNext();
+ }
+
+ @Override
+ public K next() {
+ currentKey = internal.next();
+ return currentKey;
+ }
+
+ /** 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);
+ }
+ }
+ }
+}
+
diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/splits/KeyGroupRangeInputSplit.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/splits/KeyGroupRangeInputSplit.java
new file mode 100644
index 0000000..ea35f5c
--- /dev/null
+++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/input/splits/KeyGroupRangeInputSplit.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.state.api.input.splits;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.core.io.InputSplit;
+import org.apache.flink.runtime.checkpoint.OperatorSubtaskState;
+import org.apache.flink.runtime.checkpoint.PrioritizedOperatorSubtaskState;
+import org.apache.flink.runtime.checkpoint.StateObjectCollection;
+import org.apache.flink.runtime.state.KeyedStateHandle;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * An input split representing a key-group range from a savepoint.
+ */
+@Internal
+public final class KeyGroupRangeInputSplit implements InputSplit {
+
+ private final List<KeyedStateHandle> managedKeyedState;
+
+ private final List<KeyedStateHandle> rawKeyedState;
+
+ private final int numKeyGroups;
+
+ private final int split;
+
+ public KeyGroupRangeInputSplit(
+ List<KeyedStateHandle> managedKeyedState,
+ List<KeyedStateHandle> rawKeyedState,
+ int numKeyGroups,
+ int split) {
+
+ this.managedKeyedState = managedKeyedState;
+ this.rawKeyedState = rawKeyedState;
+
+ this.numKeyGroups = numKeyGroups;
+ this.split = split;
+ }
+
+ @Override
+ public int getSplitNumber() {
+ return split;
+ }
+
+ public PrioritizedOperatorSubtaskState getPrioritizedOperatorSubtaskState() {
+ return new PrioritizedOperatorSubtaskState.Builder(
+ new OperatorSubtaskState(
+ StateObjectCollection.empty(),
+ StateObjectCollection.empty(),
+ new StateObjectCollection<>(managedKeyedState),
+ new StateObjectCollection<>(rawKeyedState)
+ ),
+ Collections.emptyList()
+ ).build();
+ }
+
+ public int getNumKeyGroups() {
+ return numKeyGroups;
+ }
+}
diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointEnvironment.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointEnvironment.java
index f551ec1..07fe936 100644
--- a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointEnvironment.java
+++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointEnvironment.java
@@ -54,11 +54,11 @@ import java.util.concurrent.Future;
/**
* A minimally implemented {@link Environment} that provides the functionality required to run the
- * {@code savepoint-connector}.
+ * {@code state-processor-api}.
*/
@Internal
public class SavepointEnvironment implements Environment {
- private static final String MSG = "This method should never be called";
+ private static final String ERROR_MSG = "This method should never be called";
private final JobID jobID;
@@ -128,12 +128,12 @@ public class SavepointEnvironment implements Environment {
@Override
public TaskMetricGroup getMetricGroup() {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
public Configuration getJobConfiguration() {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
@@ -148,7 +148,7 @@ public class SavepointEnvironment implements Environment {
@Override
public InputSplitProvider getInputSplitProvider() {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
@@ -158,7 +158,7 @@ public class SavepointEnvironment implements Environment {
@Override
public MemoryManager getMemoryManager() {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
@@ -173,7 +173,7 @@ public class SavepointEnvironment implements Environment {
@Override
public BroadcastVariableManager getBroadcastVariableManager() {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
@@ -183,7 +183,7 @@ public class SavepointEnvironment implements Environment {
@Override
public GlobalAggregateManager getGlobalAggregateManager() {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
@@ -198,17 +198,17 @@ public class SavepointEnvironment implements Environment {
@Override
public void acknowledgeCheckpoint(long checkpointId, CheckpointMetrics checkpointMetrics) {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
public void acknowledgeCheckpoint(long checkpointId, CheckpointMetrics checkpointMetrics, TaskStateSnapshot subtaskState) {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
public void declineCheckpoint(long checkpointId, Throwable cause) {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
@@ -218,27 +218,27 @@ public class SavepointEnvironment implements Environment {
@Override
public ResultPartitionWriter getWriter(int index) {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
public ResultPartitionWriter[] getAllWriters() {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
public InputGate getInputGate(int index) {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
public InputGate[] getAllInputGates() {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
@Override
public TaskEventDispatcher getTaskEventDispatcher() {
- throw new UnsupportedOperationException(MSG);
+ throw new UnsupportedOperationException(ERROR_MSG);
}
/**
diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointLocalRecoveryProvider.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointLocalRecoveryProvider.java
index 77ba567..658172f 100644
--- a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointLocalRecoveryProvider.java
+++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointLocalRecoveryProvider.java
@@ -24,7 +24,7 @@ import java.io.File;
/**
* A minimally implemented {@link LocalRecoveryDirectoryProvider} that provides the functionality
- * required to run the {@code savepoint-connector}.
+ * required to run the {@code state-processor-api}.
*/
final class SavepointLocalRecoveryProvider implements LocalRecoveryDirectoryProvider {
private static final String MSG = "This method should never be called";
diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointRuntimeContext.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointRuntimeContext.java
index 573279a..43a55bf 100644
--- a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointRuntimeContext.java
+++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointRuntimeContext.java
@@ -54,11 +54,11 @@ import java.util.Map;
* A streaming {@link RuntimeContext} which delegates to the underlying batch {@code RuntimeContext}
* along with a specified {@link KeyedStateStore}.
*
- * <p>This {@code RuntimeContext} may has the ability to force eager state registration by by
+ * <p>This {@code RuntimeContext} has the ability to force eager state registration by
* throwing an exception if state is registered outside of open.
*/
@Internal
-public final class SavepointRuntimeContext implements RuntimeContext, AutoCloseable {
+public final class SavepointRuntimeContext implements RuntimeContext {
private static final String REGISTRATION_EXCEPTION_MSG =
"State Descriptors may only be registered inside of open";
@@ -68,12 +68,12 @@ public final class SavepointRuntimeContext implements RuntimeContext, AutoClosea
private final List<StateDescriptor<?, ?>> registeredDescriptors;
- private boolean inOpen;
+ private boolean stateRegistrationAllowed;
public SavepointRuntimeContext(RuntimeContext ctx, KeyedStateStore keyedStateStore) {
this.ctx = ctx;
this.keyedStateStore = keyedStateStore;
- this.inOpen = true;
+ this.stateRegistrationAllowed = true;
this.registeredDescriptors = new ArrayList<>();
}
@@ -183,7 +183,7 @@ public final class SavepointRuntimeContext implements RuntimeContext, AutoClosea
@Override
public <T> ValueState<T> getState(ValueStateDescriptor<T> stateProperties) {
- if (!inOpen) {
+ if (!stateRegistrationAllowed) {
throw new RuntimeException(REGISTRATION_EXCEPTION_MSG);
}
@@ -193,7 +193,7 @@ public final class SavepointRuntimeContext implements RuntimeContext, AutoClosea
@Override
public <T> ListState<T> getListState(ListStateDescriptor<T> stateProperties) {
- if (!inOpen) {
+ if (!stateRegistrationAllowed) {
throw new RuntimeException(REGISTRATION_EXCEPTION_MSG);
}
@@ -203,7 +203,7 @@ public final class SavepointRuntimeContext implements RuntimeContext, AutoClosea
@Override
public <T> ReducingState<T> getReducingState(ReducingStateDescriptor<T> stateProperties) {
- if (!inOpen) {
+ if (!stateRegistrationAllowed) {
throw new RuntimeException(REGISTRATION_EXCEPTION_MSG);
}
@@ -213,7 +213,7 @@ public final class SavepointRuntimeContext implements RuntimeContext, AutoClosea
@Override
public <IN, ACC, OUT> AggregatingState<IN, OUT> getAggregatingState(AggregatingStateDescriptor<IN, ACC, OUT> stateProperties) {
- if (!inOpen) {
+ if (!stateRegistrationAllowed) {
throw new RuntimeException(REGISTRATION_EXCEPTION_MSG);
}
@@ -224,7 +224,7 @@ public final class SavepointRuntimeContext implements RuntimeContext, AutoClosea
@Override
@Deprecated
public <T, ACC> FoldingState<T, ACC> getFoldingState(FoldingStateDescriptor<T, ACC> stateProperties) {
- if (!inOpen) {
+ if (!stateRegistrationAllowed) {
throw new RuntimeException(REGISTRATION_EXCEPTION_MSG);
}
@@ -234,7 +234,7 @@ public final class SavepointRuntimeContext implements RuntimeContext, AutoClosea
@Override
public <UK, UV> MapState<UK, UV> getMapState(MapStateDescriptor<UK, UV> stateProperties) {
- if (!inOpen) {
+ if (!stateRegistrationAllowed) {
throw new RuntimeException(REGISTRATION_EXCEPTION_MSG);
}
@@ -249,9 +249,8 @@ public final class SavepointRuntimeContext implements RuntimeContext, AutoClosea
return new ArrayList<>(registeredDescriptors);
}
- @Override
- public void close() throws Exception {
- inOpen = false;
+ public void disableStateRegistration() throws Exception {
+ stateRegistrationAllowed = false;
}
}
diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskManagerRuntimeInfo.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskManagerRuntimeInfo.java
index 93362ab..99a5062 100644
--- a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskManagerRuntimeInfo.java
+++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskManagerRuntimeInfo.java
@@ -24,7 +24,7 @@ import org.apache.flink.runtime.taskmanager.TaskManagerRuntimeInfo;
/**
* A minimally implemented {@link TaskManagerRuntimeInfo} that provides the functionality required
- * to run the {@code savepoint-connector}.
+ * to run the {@code state-processor-api}.
*/
class SavepointTaskManagerRuntimeInfo implements TaskManagerRuntimeInfo {
private final IOManager ioManager;
diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskStateManager.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskStateManager.java
index d8df36b..9acc77b 100644
--- a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskStateManager.java
+++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskStateManager.java
@@ -33,7 +33,7 @@ import javax.annotation.Nullable;
/**
* A minimally implemented {@link TaskStateManager} that provides the functionality required to run
- * the {@code savepoint-connector}.
+ * the {@code state-processor-api}.
*/
final class SavepointTaskStateManager implements TaskStateManager {
private static final String MSG = "This method should never be called";
diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskManagerRuntimeInfo.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/VoidTriggerable.java
similarity index 53%
copy from flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskManagerRuntimeInfo.java
copy to flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/VoidTriggerable.java
index 93362ab..647a1dd 100644
--- a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointTaskManagerRuntimeInfo.java
+++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/VoidTriggerable.java
@@ -18,34 +18,28 @@
package org.apache.flink.state.api.runtime;
-import org.apache.flink.configuration.Configuration;
-import org.apache.flink.runtime.io.disk.iomanager.IOManager;
-import org.apache.flink.runtime.taskmanager.TaskManagerRuntimeInfo;
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.streaming.api.operators.InternalTimer;
+import org.apache.flink.streaming.api.operators.Triggerable;
/**
- * A minimally implemented {@link TaskManagerRuntimeInfo} that provides the functionality required
- * to run the {@code savepoint-connector}.
+ * A {@link Triggerable} that does nothing.
+ *
+ * @param <K> Type of the keys to which timers are scoped.
+ * @param <N> Type of the namespace to which timers are scoped.
*/
-class SavepointTaskManagerRuntimeInfo implements TaskManagerRuntimeInfo {
- private final IOManager ioManager;
-
- SavepointTaskManagerRuntimeInfo(IOManager ioManager) {
- this.ioManager = ioManager;
+@Internal
+public final class VoidTriggerable<K, N> implements Triggerable<K, N> {
+ public static <K, N> VoidTriggerable<K, N> instance() {
+ return new VoidTriggerable<>();
}
- @Override
- public Configuration getConfiguration() {
- return new Configuration();
- }
+ private VoidTriggerable() {}
@Override
- public String[] getTmpDirectories() {
- return ioManager.getSpillingDirectoriesPaths();
- }
+ public void onEventTime(InternalTimer<K, N> timer) {}
@Override
- public boolean shouldExitJvmOnOutOfMemoryError() {
- return false;
- }
+ public void onProcessingTime(InternalTimer<K, N> timer) {}
}
diff --git a/flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/SavepointReaderKeyedStateITCase.java b/flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/SavepointReaderKeyedStateITCase.java
new file mode 100644
index 0000000..663c111
--- /dev/null
+++ b/flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/SavepointReaderKeyedStateITCase.java
@@ -0,0 +1,212 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.state.api;
+
+import org.apache.flink.api.common.JobID;
+import org.apache.flink.api.common.JobSubmissionResult;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.time.Deadline;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.java.ExecutionEnvironment;
+import org.apache.flink.client.program.ClusterClient;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.contrib.streaming.state.RocksDBStateBackend;
+import org.apache.flink.runtime.jobgraph.JobGraph;
+import org.apache.flink.runtime.state.StateBackend;
+import org.apache.flink.runtime.state.memory.MemoryStateBackend;
+import org.apache.flink.state.api.functions.KeyedStateReaderFunction;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
+import org.apache.flink.streaming.api.functions.sink.DiscardingSink;
+import org.apache.flink.streaming.api.functions.source.SourceFunction;
+import org.apache.flink.test.util.AbstractTestBase;
+import org.apache.flink.util.AbstractID;
+import org.apache.flink.util.Collector;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * IT case for reading state.
+ */
+public class SavepointReaderKeyedStateITCase extends AbstractTestBase {
+ private static final String uid = "stateful-operator";
+
+ private static ValueStateDescriptor<Integer> valueState = new ValueStateDescriptor<>("value", Types.INT);
+
+ @Test
+ public void testKeyedInputFormat() throws Exception {
+ runKeyedState(new MemoryStateBackend());
+ // Reset the cluster so we can change the
+ // state backend in the StreamEnvironment.
+ // If we don't do this the tests will fail.
+ miniClusterResource.after();
+ miniClusterResource.before();
+ runKeyedState(new RocksDBStateBackend((StateBackend) new MemoryStateBackend()));
+ }
+
+ private void runKeyedState(StateBackend backend) throws Exception {
+ StreamExecutionEnvironment streamEnv = StreamExecutionEnvironment.getExecutionEnvironment();
+ streamEnv.setStateBackend(backend);
+ streamEnv.setParallelism(4);
+
+ streamEnv
+ .addSource(new SavepointSource())
+ .rebalance()
+ .keyBy(id -> id)
+ .process(new KeyedStatefulOperator())
+ .uid(uid)
+ .addSink(new DiscardingSink<>());
+
+ JobGraph jobGraph = streamEnv.getStreamGraph().getJobGraph();
+
+ String path = takeSavepoint(jobGraph);
+
+ ExecutionEnvironment batchEnv = ExecutionEnvironment.getExecutionEnvironment();
+ ExistingSavepoint savepoint = Savepoint.load(batchEnv, path, backend);
+
+ List<Integer> results = savepoint
+ .readKeyedState(uid, new Reader())
+ .collect();
+
+ results.sort(Comparator.naturalOrder());
+
+ List<Integer> expected = SavepointSource.getElements();
+
+ Assert.assertEquals("Unexpected results from keyed state", expected, results);
+ }
+
+ private String takeSavepoint(JobGraph jobGraph) throws Exception {
+ SavepointSource.initializeForTest();
+
+ ClusterClient<?> client = miniClusterResource.getClusterClient();
+ client.setDetached(true);
+
+ JobID jobId = jobGraph.getJobID();
+
+ Deadline deadline = Deadline.fromNow(Duration.ofMinutes(5));
+
+ String dirPath = getTempDirPath(new AbstractID().toHexString());
+
+ try {
+ client.setDetached(true);
+ JobSubmissionResult result = client.submitJob(jobGraph, getClass().getClassLoader());
+
+ boolean finished = false;
+ while (deadline.hasTimeLeft()) {
+ if (SavepointSource.isFinished()) {
+ finished = true;
+
+ break;
+ }
+ }
+
+ if (!finished) {
+ Assert.fail("Failed to initialize state within deadline");
+ }
+
+ CompletableFuture<String> path = client.triggerSavepoint(result.getJobID(), dirPath);
+ return path.get(deadline.timeLeft().toMillis(), TimeUnit.MILLISECONDS);
+ } finally {
+ client.cancel(jobId);
+ }
+ }
+
+ private static class SavepointSource implements SourceFunction<Integer> {
+ private static volatile boolean finished;
+
+ private volatile boolean running = true;
+
+ private static final Integer[] elements = {1, 2, 3};
+
+ @Override
+ public void run(SourceContext<Integer> ctx) {
+ synchronized (ctx.getCheckpointLock()) {
+ for (Integer element : elements) {
+ ctx.collect(element);
+ }
+
+ finished = true;
+ }
+
+ while (running) {
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ // ignore
+ }
+ }
+ }
+
+ @Override
+ public void cancel() {
+ running = false;
+ }
+
+ private static void initializeForTest() {
+ finished = false;
+ }
+
+ private static boolean isFinished() {
+ return finished;
+ }
+
+ private static List<Integer> getElements() {
+ return Arrays.asList(elements);
+ }
+ }
+
+ private static class KeyedStatefulOperator extends KeyedProcessFunction<Integer, Integer, Void> {
+
+ private transient ValueState<Integer> state;
+
+ @Override
+ public void open(Configuration parameters) {
+ state = getRuntimeContext().getState(valueState);
+ }
+
+ @Override
+ public void processElement(Integer value, Context ctx, Collector<Void> out) throws Exception {
+ state.update(value);
+ }
+ }
+
+ private static class Reader extends KeyedStateReaderFunction<Integer, Integer> {
+
+ private transient ValueState<Integer> state;
+
+ @Override
+ public void open(Configuration parameters) {
+ state = getRuntimeContext().getState(valueState);
+ }
+
+ @Override
+ public void readKey(Integer key, Context ctx, Collector<Integer> out) throws Exception {
+ out.collect(state.value());
+ }
+ }
+}
diff --git a/flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/input/BufferingCollectorTest.java b/flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/input/BufferingCollectorTest.java
new file mode 100644
index 0000000..13e3b18
--- /dev/null
+++ b/flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/input/BufferingCollectorTest.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.state.api.input;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * Test of the buffering collector.
+ */
+public class BufferingCollectorTest {
+
+ @Test
+ public void testNestRemovesElement() {
+ BufferingCollector<Integer> collector = new BufferingCollector<>();
+
+ collector.collect(1);
+
+ Assert.assertTrue("Failed to add element to collector", collector.hasNext());
+ Assert.assertEquals("Incorrect element removed from collector", Integer.valueOf(1), collector.next());
+ Assert.assertFalse("Failed to drop element from collector", collector.hasNext());
+ }
+
+ @Test
+ public void testEmptyCollectorReturnsNull() {
+ BufferingCollector<Integer> collector = new BufferingCollector<>();
+ Assert.assertNull("Empty collector did not return null", collector.next());
+ }
+}
diff --git a/flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/input/KeyedStateInputFormatTest.java b/flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/input/KeyedStateInputFormatTest.java
new file mode 100644
index 0000000..2824b34
--- /dev/null
+++ b/flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/input/KeyedStateInputFormatTest.java
@@ -0,0 +1,250 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.state.api.input;
+
+import org.apache.flink.api.common.functions.RichFlatMapFunction;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.common.typeutils.base.VoidSerializer;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.checkpoint.OperatorState;
+import org.apache.flink.runtime.checkpoint.OperatorSubtaskState;
+import org.apache.flink.runtime.jobgraph.OperatorID;
+import org.apache.flink.runtime.state.memory.MemoryStateBackend;
+import org.apache.flink.state.api.functions.KeyedStateReaderFunction;
+import org.apache.flink.state.api.input.splits.KeyGroupRangeInputSplit;
+import org.apache.flink.state.api.runtime.OperatorIDGenerator;
+import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.api.operators.StreamFlatMap;
+import org.apache.flink.streaming.util.KeyedOneInputStreamOperatorTestHarness;
+import org.apache.flink.streaming.util.MockStreamingRuntimeContext;
+import org.apache.flink.util.Collector;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import javax.annotation.Nonnull;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Tests for keyed state input format.
+ */
+public class KeyedStateInputFormatTest {
+ private static ValueStateDescriptor<Integer> stateDescriptor = new ValueStateDescriptor<>("state", Types.INT);
+
+ @Test
+ public void testCreatePartitionedInputSplits() throws Exception {
+ OperatorID operatorID = OperatorIDGenerator.fromUid("uid");
+
+ OperatorSubtaskState state = createOperatorSubtaskState(new StreamFlatMap<>(new StatefulFunction()));
+ OperatorState operatorState = new OperatorState(operatorID, 1, 128);
+ operatorState.putState(0, state);
+
+ KeyedStateInputFormat<?, ?> format = new KeyedStateInputFormat<>(operatorState, new MemoryStateBackend(), Types.INT, new ReaderFunction());
+ KeyGroupRangeInputSplit[] splits = format.createInputSplits(4);
+ Assert.assertEquals("Failed to properly partition operator state into input splits", 4, splits.length);
+ }
+
+ @Test
+ public void testMaxParallelismRespected() throws Exception {
+ OperatorID operatorID = OperatorIDGenerator.fromUid("uid");
+
+ OperatorSubtaskState state = createOperatorSubtaskState(new StreamFlatMap<>(new StatefulFunction()));
+ OperatorState operatorState = new OperatorState(operatorID, 1, 128);
+ operatorState.putState(0, state);
+
+ KeyedStateInputFormat<?, ?> format = new KeyedStateInputFormat<>(operatorState, new MemoryStateBackend(), Types.INT, new ReaderFunction());
+ KeyGroupRangeInputSplit[] splits = format.createInputSplits(129);
+ Assert.assertEquals("Failed to properly partition operator state into input splits", 128, splits.length);
+ }
+
+ @Test
+ public void testReadState() throws Exception {
+ OperatorID operatorID = OperatorIDGenerator.fromUid("uid");
+
+ OperatorSubtaskState state = createOperatorSubtaskState(new StreamFlatMap<>(new StatefulFunction()));
+ OperatorState operatorState = new OperatorState(operatorID, 1, 128);
+ operatorState.putState(0, state);
+
+ KeyedStateInputFormat<?, ?> format = new KeyedStateInputFormat<>(operatorState, new MemoryStateBackend(), Types.INT, new ReaderFunction());
+ KeyGroupRangeInputSplit split = format.createInputSplits(1)[0];
+
+ KeyedStateReaderFunction<Integer, Integer> userFunction = new ReaderFunction();
+
+ List<Integer> data = readInputSplit(split, userFunction);
+
+ Assert.assertEquals("Incorrect data read from input split", Arrays.asList(1, 2, 3), data);
+ }
+
+ @Test
+ public void testReadMultipleOutputPerKey() throws Exception {
+ OperatorID operatorID = OperatorIDGenerator.fromUid("uid");
+
+ OperatorSubtaskState state = createOperatorSubtaskState(new StreamFlatMap<>(new StatefulFunction()));
+ OperatorState operatorState = new OperatorState(operatorID, 1, 128);
+ operatorState.putState(0, state);
+
+ KeyedStateInputFormat<?, ?> format = new KeyedStateInputFormat<>(operatorState, new MemoryStateBackend(), Types.INT, new ReaderFunction());
+ KeyGroupRangeInputSplit split = format.createInputSplits(1)[0];
+
+ KeyedStateReaderFunction<Integer, Integer> userFunction = new DoubleReaderFunction();
+
+ List<Integer> data = readInputSplit(split, userFunction);
+
+ Assert.assertEquals("Incorrect data read from input split", Arrays.asList(1, 1, 2, 2, 3, 3), data);
+ }
+
+ @Test(expected = IOException.class)
+ public void testInvalidProcessReaderFunctionFails() throws Exception {
+ OperatorID operatorID = OperatorIDGenerator.fromUid("uid");
+
+ OperatorSubtaskState state = createOperatorSubtaskState(new StreamFlatMap<>(new StatefulFunction()));
+ OperatorState operatorState = new OperatorState(operatorID, 1, 128);
+ operatorState.putState(0, state);
+
+ KeyedStateInputFormat<?, ?> format = new KeyedStateInputFormat<>(operatorState, new MemoryStateBackend(), Types.INT, new ReaderFunction());
+ KeyGroupRangeInputSplit split = format.createInputSplits(1)[0];
+
+ KeyedStateReaderFunction<Integer, Integer> userFunction = new InvalidReaderFunction();
+
+ readInputSplit(split, userFunction);
+
+ Assert.fail("KeyedStateReaderFunction did not fail on invalid RuntimeContext use");
+ }
+
+ @Nonnull
+ private List<Integer> readInputSplit(KeyGroupRangeInputSplit split, KeyedStateReaderFunction<Integer, Integer> userFunction) throws IOException {
+ KeyedStateInputFormat<Integer, Integer> format = new KeyedStateInputFormat<>(
+ new OperatorState(OperatorIDGenerator.fromUid("uid"), 1, 4),
+ new MemoryStateBackend(),
+ Types.INT,
+ userFunction);
+
+ List<Integer> data = new ArrayList<>();
+
+ format.setRuntimeContext(new MockStreamingRuntimeContext(false, 1, 0));
+
+ format.openInputFormat();
+ format.open(split);
+
+ while (!format.reachedEnd()) {
+ data.add(format.nextRecord(0));
+ }
+
+ format.close();
+ format.closeInputFormat();
+
+ data.sort(Comparator.comparingInt(id -> id));
+ return data;
+ }
+
+ private OperatorSubtaskState createOperatorSubtaskState(OneInputStreamOperator<Integer, Void> operator) throws Exception {
+ try (KeyedOneInputStreamOperatorTestHarness<Integer, Integer, Void> testHarness =
+ new KeyedOneInputStreamOperatorTestHarness<>(operator, id -> id, Types.INT, 128, 1, 0)) {
+
+ testHarness.setup(VoidSerializer.INSTANCE);
+ testHarness.open();
+
+ testHarness.processElement(1, 0);
+ testHarness.processElement(2, 0);
+ testHarness.processElement(3, 0);
+
+ return testHarness.snapshot(0, 0);
+ }
+ }
+
+ static class ReaderFunction extends KeyedStateReaderFunction<Integer, Integer> {
+ ValueState<Integer> state;
+
+ @Override
+ public void open(Configuration parameters) {
+ state = getRuntimeContext().getState(stateDescriptor);
+ }
+
+ @Override
+ public void readKey(Integer key, KeyedStateReaderFunction.Context ctx, Collector<Integer> out) throws Exception {
+ out.collect(state.value());
+ }
+ }
+
+ static class DoubleReaderFunction extends KeyedStateReaderFunction<Integer, Integer> {
+ ValueState<Integer> state;
+
+ @Override
+ public void open(Configuration parameters) {
+ state = getRuntimeContext().getState(stateDescriptor);
+ }
+
+ @Override
+ public void readKey(Integer key, KeyedStateReaderFunction.Context ctx, Collector<Integer> out) throws Exception {
+ out.collect(state.value());
+ out.collect(state.value());
+ }
+ }
+
+ static class InvalidReaderFunction extends KeyedStateReaderFunction<Integer, Integer> {
+
+ @Override
+ public void open(Configuration parameters) {
+ getRuntimeContext().getState(stateDescriptor);
+ }
+
+ @Override
+ public void readKey(Integer key, KeyedStateReaderFunction.Context ctx, Collector<Integer> out) throws Exception {
+ ValueState<Integer> state = getRuntimeContext().getState(stateDescriptor);
+ out.collect(state.value());
+ }
+ }
+
+ static class StatefulFunction extends RichFlatMapFunction<Integer, Void> {
+ ValueState<Integer> state;
+
+ @Override
+ public void open(Configuration parameters) {
+ state = getRuntimeContext().getState(stateDescriptor);
+ }
+
+ @Override
+ public void flatMap(Integer value, Collector<Void> out) throws Exception {
+ state.update(value);
+ }
+ }
+
+ static class StatefulFunctionWithTime extends KeyedProcessFunction<Integer, Integer, Void> {
+ ValueState<Integer> state;
+
+ @Override
+ public void open(Configuration parameters) {
+ state = getRuntimeContext().getState(stateDescriptor);
+ }
+
+ @Override
+ public void processElement(Integer value, Context ctx, Collector<Void> out) throws Exception {
+ state.update(value);
+ ctx.timerService().registerEventTimeTimer(value);
+ }
+ }
+}
diff --git a/flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/input/MultiStateKeyIteratorTest.java b/flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/input/MultiStateKeyIteratorTest.java
new file mode 100644
index 0000000..f69acf9
--- /dev/null
+++ b/flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/input/MultiStateKeyIteratorTest.java
@@ -0,0 +1,126 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.state.api.input;
+
+import org.apache.flink.api.common.JobID;
+import org.apache.flink.api.common.state.StateDescriptor;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.common.typeutils.base.IntSerializer;
+import org.apache.flink.core.fs.CloseableRegistry;
+import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
+import org.apache.flink.runtime.operators.testutils.DummyEnvironment;
+import org.apache.flink.runtime.state.AbstractKeyedStateBackend;
+import org.apache.flink.runtime.state.KeyGroupRange;
+import org.apache.flink.runtime.state.VoidNamespace;
+import org.apache.flink.runtime.state.VoidNamespaceSerializer;
+import org.apache.flink.runtime.state.ttl.TtlTimeProvider;
+import org.apache.flink.runtime.state.ttl.mock.MockStateBackend;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Test for the mulit-state key iterator.
+ */
+public class MultiStateKeyIteratorTest {
+ private static final List<ValueStateDescriptor<Integer>> descriptors;
+
+ static {
+ descriptors = new ArrayList<>(2);
+ descriptors.add(new ValueStateDescriptor<>("state-1", Types.INT));
+ descriptors.add(new ValueStateDescriptor<>("state-2", Types.INT));
+ }
+
+ private static AbstractKeyedStateBackend<Integer> createKeyedStateBackend() {
+ MockStateBackend backend = new MockStateBackend();
+
+ return backend.createKeyedStateBackend(
+ new DummyEnvironment(),
+ new JobID(),
+ "mock-backend",
+ IntSerializer.INSTANCE,
+ 129,
+ KeyGroupRange.of(0, 128),
+ null,
+ TtlTimeProvider.DEFAULT,
+ UnregisteredMetricGroups.createUnregisteredTaskMetricGroup(),
+ Collections.emptyList(),
+ new CloseableRegistry());
+ }
+
+ private static void setKey(
+ AbstractKeyedStateBackend<Integer> backend,
+ ValueStateDescriptor<Integer> descriptor,
+ int key) throws Exception {
+ backend.setCurrentKey(key);
+ backend
+ .getPartitionedState(VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, descriptor)
+ .update(0);
+ }
+
+ @Test
+ public void testIteratorPullsKeyFromAllDescriptors() throws Exception {
+ AbstractKeyedStateBackend<Integer> keyedStateBackend = createKeyedStateBackend();
+
+ setKey(keyedStateBackend, descriptors.get(0), 1);
+ setKey(keyedStateBackend, descriptors.get(1), 2);
+
+ MultiStateKeyIterator<Integer> iterator = new MultiStateKeyIterator<>(descriptors, keyedStateBackend);
+
+ List<Integer> keys = new ArrayList<>();
+
+ while (iterator.hasNext()) {
+ keys.add(iterator.next());
+ }
+
+ Assert.assertEquals("Unexpected number of keys", 2, keys.size());
+ Assert.assertEquals("Unexpected keys found", Arrays.asList(1, 2), keys);
+ }
+
+ @Test
+ public void testIteratorRemovesFromAllDescriptors() throws Exception {
+ AbstractKeyedStateBackend<Integer> keyedStateBackend = createKeyedStateBackend();
+
+ setKey(keyedStateBackend, descriptors.get(0), 1);
+ setKey(keyedStateBackend, descriptors.get(1), 1);
+
+ MultiStateKeyIterator<Integer> iterator =
+ new MultiStateKeyIterator<>(descriptors, keyedStateBackend);
+
+ int key = iterator.next();
+ Assert.assertEquals("Unexpected keys pulled from state backend", 1, key);
+
+ iterator.remove();
+ Assert.assertFalse("Failed to drop key from all descriptors in state backend", iterator.hasNext());
+
+ for (StateDescriptor<?, ?> descriptor : descriptors) {
+ Assert.assertEquals(
+ "Failed to drop key for state descriptor",
+ 0,
+ keyedStateBackend.getKeys(descriptor.getName(), VoidNamespace.INSTANCE).count());
+ }
+ }
+}
+