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 2018/02/06 19:03:11 UTC

[11/28] flink git commit: [FLINK-8484] [kinesis] Synchronize local shard metainfo's on restore

[FLINK-8484] [kinesis] Synchronize local shard metainfo's on restore

Ensure that a metainfo change in the StreamShardMetadata other than
`StreamShardMetadata.shardId` or `StreamShardMetadata.streamName` does
not result in the shard not being able to be restored. This handles the
corner case where a shard might have been closed (ending sequence number
set to not-null) since the last savepoint or checkpoint when a job is
restarted from a snapshot state.


Project: http://git-wip-us.apache.org/repos/asf/flink/repo
Commit: http://git-wip-us.apache.org/repos/asf/flink/commit/426cf469
Tree: http://git-wip-us.apache.org/repos/asf/flink/tree/426cf469
Diff: http://git-wip-us.apache.org/repos/asf/flink/diff/426cf469

Branch: refs/heads/release-1.4
Commit: 426cf46970630d6606938ecb9c19fcecbb2c80f5
Parents: ca1e525
Author: Philip Luppens <ph...@gmail.com>
Authored: Tue Jan 23 10:00:23 2018 +0200
Committer: Tzu-Li (Gordon) Tai <tz...@apache.org>
Committed: Tue Feb 6 17:31:32 2018 +0100

----------------------------------------------------------------------
 .../kinesis/FlinkKinesisConsumer.java           |  49 ++++++++
 .../kinesis/FlinkKinesisConsumerTest.java       | 125 +++++++++++++++++++
 2 files changed, 174 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/flink/blob/426cf469/flink-connectors/flink-connector-kinesis/src/main/java/org/apache/flink/streaming/connectors/kinesis/FlinkKinesisConsumer.java
----------------------------------------------------------------------
diff --git a/flink-connectors/flink-connector-kinesis/src/main/java/org/apache/flink/streaming/connectors/kinesis/FlinkKinesisConsumer.java b/flink-connectors/flink-connector-kinesis/src/main/java/org/apache/flink/streaming/connectors/kinesis/FlinkKinesisConsumer.java
index a3681ec..de66f93 100644
--- a/flink-connectors/flink-connector-kinesis/src/main/java/org/apache/flink/streaming/connectors/kinesis/FlinkKinesisConsumer.java
+++ b/flink-connectors/flink-connector-kinesis/src/main/java/org/apache/flink/streaming/connectors/kinesis/FlinkKinesisConsumer.java
@@ -208,6 +208,16 @@ public class FlinkKinesisConsumer<T> extends RichParallelSourceFunction<T> imple
 		for (StreamShardHandle shard : allShards) {
 			StreamShardMetadata kinesisStreamShard = KinesisDataFetcher.convertToStreamShardMetadata(shard);
 			if (sequenceNumsToRestore != null) {
+
+				// We need to do this to make sure that a shard that was closed after this restored state was taken will be properly
+				// detected and have its sequence numbers restored. A shard will be closed when re-sharding, which can happen when
+				// scaling up & down the Kinesis stream, and if the state is not synchronized, then the equality check of the current
+				// Kinesis shard will not match the stored state, which will cause us to re-read the entire shard from the event horizon.
+				if (updateKinesisShardStateWithMissingEndingSequenceNumber(kinesisStreamShard, sequenceNumsToRestore)) {
+					if (LOG.isInfoEnabled()) {
+						LOG.info("Updated local stored state for shard {} with a new ending number: {}", kinesisStreamShard.getShardId(), sequenceNumsToRestore.get(kinesisStreamShard));
+					}
+				}
 				if (sequenceNumsToRestore.containsKey(kinesisStreamShard)) {
 					// if the shard was already seen and is contained in the state,
 					// just use the sequence number stored in the state
@@ -265,6 +275,45 @@ public class FlinkKinesisConsumer<T> extends RichParallelSourceFunction<T> imple
 		sourceContext.close();
 	}
 
+	/**
+	 * Synchronizes the Kinesis shard information from the current Kinesis shard with the restored state, if we find
+	 * a shard that match the shardId and streamName. If we find one, and its ending key is different that what we
+	 * have in our stored state, then we update the stored's shard's metadata's ending number.
+	 *
+	 * @param current				the current Kinesis shard we're trying to synchronize.
+	 * @param sequenceNumsToRestore	the (re)stored shard metadata and their sequence numbers.
+	 * @return {@code true} if the local state was updated with the current Kinesis shard's ending number.
+	 */
+	@VisibleForTesting
+	boolean updateKinesisShardStateWithMissingEndingSequenceNumber(StreamShardMetadata current, HashMap<StreamShardMetadata, SequenceNumber> sequenceNumsToRestore) {
+		checkNotNull(current.getStreamName(), "Stream name not set on the current metadata shard");
+		checkNotNull(current.getShardId(), "Shard id not set on the current metadata shard");
+
+		// short-circuit: if the current shard doesn't have an ending sequence number, then there's no point in trying to update the local state
+		// since that's the only property that can change.
+		if (current.getEndingSequenceNumber() == null) {
+			return false;
+		}
+
+		// try to find the matching shard based on the id & stream name
+		for (Map.Entry<StreamShardMetadata, SequenceNumber> entry : sequenceNumsToRestore.entrySet()) {
+			if (current.getStreamName().equals(entry.getKey().getStreamName())
+				&& current.getShardId().equals(entry.getKey().getShardId())) {
+				// synchronize the local state if the ending sequence number is different
+				if (!current.getEndingSequenceNumber().equals(entry.getKey().getEndingSequenceNumber())) {
+					// ugly, but since the hashcode will change, we'll need to remove it and add it back
+					sequenceNumsToRestore.remove(entry.getKey());
+					entry.getKey().setEndingSequenceNumber(current.getEndingSequenceNumber());
+					sequenceNumsToRestore.put(entry.getKey(), entry.getValue());
+					return true;
+				}
+				// we already found the matching shard
+				break;
+			}
+		}
+		return false;
+	}
+
 	@Override
 	public void cancel() {
 		running = false;

http://git-wip-us.apache.org/repos/asf/flink/blob/426cf469/flink-connectors/flink-connector-kinesis/src/test/java/org/apache/flink/streaming/connectors/kinesis/FlinkKinesisConsumerTest.java
----------------------------------------------------------------------
diff --git a/flink-connectors/flink-connector-kinesis/src/test/java/org/apache/flink/streaming/connectors/kinesis/FlinkKinesisConsumerTest.java b/flink-connectors/flink-connector-kinesis/src/test/java/org/apache/flink/streaming/connectors/kinesis/FlinkKinesisConsumerTest.java
index 2b1fcf4..a142b26 100644
--- a/flink-connectors/flink-connector-kinesis/src/test/java/org/apache/flink/streaming/connectors/kinesis/FlinkKinesisConsumerTest.java
+++ b/flink-connectors/flink-connector-kinesis/src/test/java/org/apache/flink/streaming/connectors/kinesis/FlinkKinesisConsumerTest.java
@@ -63,12 +63,14 @@ import org.powermock.modules.junit4.PowerMockRunner;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 import java.util.UUID;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.mock;
@@ -522,6 +524,129 @@ public class FlinkKinesisConsumerTest {
 		assertTrue(typeInformation.createSerializer(new ExecutionConfig()) instanceof PojoSerializer);
 	}
 
+	/**
+	 * FLINK-8484: ensure that a state change in the StreamShardMetadata other than {@link StreamShardMetadata#shardId} or
+	 * {@link StreamShardMetadata#streamName} does not result in the shard not being able to be restored.
+	 * This handles the corner case where the stored shard metadata is open (no ending sequence number), but after the
+	 * job restore, the shard has been closed (ending number set) due to re-sharding, and we can no longer rely on
+	 * {@link StreamShardMetadata#equals(Object)} to find back the sequence number in the collection of restored shard metadata.
+	 * <p></p>
+	 * Therefore, we will rely on synchronizing the snapshot's state with the Kinesis shard before attempting to find back
+	 * the sequence number to restore.
+	 */
+	@Test
+	public void testFindSequenceNumberToRestoreFromIfTheShardHasBeenClosedSinceTheStateWasStored() throws Exception {
+		// ----------------------------------------------------------------------
+		// setup initial state
+		// ----------------------------------------------------------------------
+
+		HashMap<StreamShardHandle, SequenceNumber> fakeRestoredState = getFakeRestoredStore("all");
+
+		// ----------------------------------------------------------------------
+		// mock operator state backend and initial state for initializeState()
+		// ----------------------------------------------------------------------
+
+		TestingListState<Tuple2<StreamShardMetadata, SequenceNumber>> listState = new TestingListState<>();
+		for (Map.Entry<StreamShardHandle, SequenceNumber> state : fakeRestoredState.entrySet()) {
+			listState.add(Tuple2.of(KinesisDataFetcher.convertToStreamShardMetadata(state.getKey()), state.getValue()));
+		}
+
+		OperatorStateStore operatorStateStore = mock(OperatorStateStore.class);
+		when(operatorStateStore.getUnionListState(Matchers.any(ListStateDescriptor.class))).thenReturn(listState);
+
+		StateInitializationContext initializationContext = mock(StateInitializationContext.class);
+		when(initializationContext.getOperatorStateStore()).thenReturn(operatorStateStore);
+		when(initializationContext.isRestored()).thenReturn(true);
+
+		// ----------------------------------------------------------------------
+		// mock fetcher
+		// ----------------------------------------------------------------------
+
+		KinesisDataFetcher mockedFetcher = Mockito.mock(KinesisDataFetcher.class);
+		List<StreamShardHandle> shards = new ArrayList<>();
+
+		// create a fake stream shard handle based on the first entry in the restored state
+		final StreamShardHandle originalStreamShardHandle = fakeRestoredState.keySet().iterator().next();
+		final StreamShardHandle closedStreamShardHandle = new StreamShardHandle(originalStreamShardHandle.getStreamName(), originalStreamShardHandle.getShard());
+		// close the shard handle by setting an ending sequence number
+		final SequenceNumberRange sequenceNumberRange = new SequenceNumberRange();
+		sequenceNumberRange.setEndingSequenceNumber("1293844");
+		closedStreamShardHandle.getShard().setSequenceNumberRange(sequenceNumberRange);
+
+		shards.add(closedStreamShardHandle);
+
+		when(mockedFetcher.discoverNewShardsToSubscribe()).thenReturn(shards);
+		PowerMockito.whenNew(KinesisDataFetcher.class).withAnyArguments().thenReturn(mockedFetcher);
+
+		// assume the given config is correct
+		PowerMockito.mockStatic(KinesisConfigUtil.class);
+		PowerMockito.doNothing().when(KinesisConfigUtil.class);
+
+		// ----------------------------------------------------------------------
+		// start to test fetcher's initial state seeding
+		// ----------------------------------------------------------------------
+
+		TestableFlinkKinesisConsumer consumer = new TestableFlinkKinesisConsumer(
+			"fakeStream", new Properties(), 10, 2);
+		consumer.initializeState(initializationContext);
+		consumer.open(new Configuration());
+		consumer.run(Mockito.mock(SourceFunction.SourceContext.class));
+
+		Mockito.verify(mockedFetcher).registerNewSubscribedShardState(
+			new KinesisStreamShardState(KinesisDataFetcher.convertToStreamShardMetadata(closedStreamShardHandle),
+				closedStreamShardHandle, fakeRestoredState.get(closedStreamShardHandle)));
+	}
+
+	@Test
+	public void testUpdateKinesisShardStateWithMissingEndingSequenceNumber() {
+		final String streamName = "fakeStream1";
+		final String shardId = "shard-000001";
+
+		Properties config = TestUtils.getStandardProperties();
+		FlinkKinesisConsumer<String> consumer = new FlinkKinesisConsumer<>(streamName, new SimpleStringSchema(), config);
+
+		// having the current Kinesis shard we're trying to find the restored state for
+		final StreamShardMetadata current = new StreamShardMetadata();
+		current.setShardId(shardId);
+		current.setStreamName(streamName);
+		current.setEndingSequenceNumber(null);
+
+		final HashMap<StreamShardMetadata, SequenceNumber> sequenceNumsToRestore = new LinkedHashMap<>();
+		assertFalse("Current shard is open, expecting a short-circuit", consumer.updateKinesisShardStateWithMissingEndingSequenceNumber(current, sequenceNumsToRestore));
+
+		// create some non-matching shards
+		final StreamShardMetadata differentStreamName = new StreamShardMetadata();
+		differentStreamName.setStreamName("fakeStream2");
+		differentStreamName.setShardId(shardId);
+
+		final StreamShardMetadata differentShardId = new StreamShardMetadata();
+		differentShardId.setStreamName(streamName);
+		differentShardId.setShardId("shard-000002");
+
+		// create the matching shard
+		final StreamShardMetadata match = new StreamShardMetadata();
+		match.setStreamName(streamName);
+		match.setShardId(shardId);
+		// ensure the sequence number isn't set (shard is considered in open state)
+		match.setEndingSequenceNumber(null);
+
+		sequenceNumsToRestore.put(differentStreamName, new SequenceNumber("123"));
+		sequenceNumsToRestore.put(differentShardId, new SequenceNumber("456"));
+		sequenceNumsToRestore.put(match, new SequenceNumber("789"));
+
+		assertFalse("No ending sequence number was set, so no synchronisation was done.", consumer.updateKinesisShardStateWithMissingEndingSequenceNumber(current, sequenceNumsToRestore));
+
+		// alter the ending sequence number (indicating the shard is now closed)
+		final String endingSequenceNumber = "99999";
+		current.setEndingSequenceNumber(endingSequenceNumber);
+		assertTrue("Shard was closed (ending number set).", consumer.updateKinesisShardStateWithMissingEndingSequenceNumber(current, sequenceNumsToRestore));
+		assertEquals(endingSequenceNumber, match.getEndingSequenceNumber());
+		assertEquals(current, match);
+		assertTrue("Make sure we can still find back our match in the restored sequences ", sequenceNumsToRestore.containsKey(match));
+
+		assertFalse("Ending number was already set, no more need for synchronisation", consumer.updateKinesisShardStateWithMissingEndingSequenceNumber(current, sequenceNumsToRestore));
+	}
+
 	private static final class TestingListState<T> implements ListState<T> {
 
 		private final List<T> list = new ArrayList<>();