You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by se...@apache.org on 2020/11/16 09:22:05 UTC
[flink] branch release-1.11 updated (c24185d -> 1a8ff89)
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a change to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git.
from c24185d [hotfix] Adjust japicmp exclusion to permit adding methods to SourceReaderContext and SplitEnumeratorContext interfaces
new 9190335 [backport] Backport some core changes that were part of the FLIP-27 File Source commit
new ecc6a8a [backport] Relevant test mock changes from "[FLINK-18907][test] Refactor MockSourceReader"
new f79a3a7 [backport] Relevant test mock changes from "[FLINK-18907][task] Add test coverage for watermarks with chained sources"
new cd3ffa5 [backport] Relevant test mock changes from "[FLINK-18907][task] Fix and add test coverage for watermarks gauges with chained sources"
new 242ced9 [backport] Relevant test mock changes from "[FLINK-18907][test] Add stream status forwarding test for chained sources"
new 7916ad7 [refactor][tests] Move some source test utils from flink-connector-base to flink-core
new 09ea814 [FLINK-19457][core] Add a number sequence generating source for the FLIP-27 source API.
new 301046a [FLINK-19492][core] Consolidate Source Events between Source API and Split Reader API
new cdc0721 [FLINK-19448][connector base] Explicitly check for un-expected condition that would leave an inconsistent state
new dd2ac7a [FLINK-19427][FLINK-19489][tests] Fix test conditions for 'SplitFetcherTest.testNotifiesWhenGoingIdleConcurrent()'
new 5b2cc0e [FLINK-18044][Connectors/Common] Add the subtask index information to the SourceReaderContext. (#12647)
new 1f823bd [hotfix][runtime] Remove commented-out annotation in SourceOperator
new b3ea6da [FLINK-18820] Emit MAX_WATERMARK at the end in SourceOperator
new 8ad5da9 [hotfix] Replace finally block with JUnit After method in SourceOperatorTest.
new 3463da5 [hotfix] Only close the SourceReader and EventTimeLogic in the SourceOperator if they are not null.
new 5787a70 [hotfix] Add a waitUntil() method to the CommonTestUtils.
new 5f63e34 Backport of "[FLINK-19698][connector/common] Let SplitEnumerator/SourceReader/SourceCoordinator implement CheckpointListener."
new 2a77589 [FLINK-19698][connector/common] Add a close() method to the SplitReader.
new abe4c4b [FLINK-19384][core] Add common permissive exception signatures to all methods of Source.
new 9cb2419 [build] Add exclusions for added default methods in SourceReader and SplitEnumerator interfaces.
new 1a8ff89 [refactor][DataStream API] Make DataStreamUtils.collect() methods more flexible.
The 21 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../SingleThreadMultiplexSourceReaderBase.java | 63 ++++-
.../base/source/reader/SourceReaderBase.java | 11 +-
.../base/source/reader/fetcher/SplitFetcher.java | 10 +-
.../source/reader/splitreader/SplitReader.java | 7 +
.../base/source/reader/SourceReaderBaseTest.java | 16 +-
.../base/source/reader/SourceReaderTestBase.java | 2 +-
.../reader/fetcher/SplitFetcherManagerTest.java | 22 ++
.../source/reader/fetcher/SplitFetcherTest.java | 63 ++---
.../base/source/reader/mocks/MockSourceReader.java | 5 +
.../source/reader/mocks/MockSplitEnumerator.java | 2 +-
.../base/source/reader/mocks/MockSplitReader.java | 3 +
.../source/reader/mocks/TestingSplitReader.java | 20 ++
flink-core/pom.xml | 5 +-
.../apache/flink/api/connector/source/Source.java | 16 +-
.../flink/api/connector/source/SourceReader.java | 19 +-
.../api/connector/source/SourceReaderContext.java | 5 +
.../api/connector/source/SplitEnumerator.java | 17 +-
.../connector}/source/event/NoMoreSplitsEvent.java | 2 +-
.../connector}/source/event/RequestSplitEvent.java | 15 +-
.../connector/source/lib/NumberSequenceSource.java | 253 +++++++++++++++++++++
.../source/lib/util/IteratorSourceEnumerator.java | 90 ++++++++
.../source/lib/util/IteratorSourceReader.java | 148 ++++++++++++
.../source/lib/util/IteratorSourceSplit.java | 34 ++-
.../source/lib/NumberSequenceSourceTest.java | 91 ++++++++
.../api/connector/source/mocks/MockSource.java | 12 +-
.../connector/source/mocks/MockSourceReader.java | 98 ++++++--
.../source/mocks/MockSplitEnumerator.java | 21 +-
.../source}/mocks/TestingReaderContext.java | 11 +-
.../source}/mocks/TestingReaderOutput.java | 2 +-
.../runtime/checkpoint/CheckpointCoordinator.java | 7 +-
.../OperatorCoordinatorCheckpointContext.java | 19 +-
.../coordination/OperatorCoordinator.java | 42 ++--
.../coordination/OperatorCoordinatorHolder.java | 22 +-
.../RecreateOnResetOperatorCoordinator.java | 13 +-
.../source/coordinator/SourceCoordinator.java | 24 +-
.../coordinator/SourceCoordinatorProvider.java | 2 +-
.../checkpoint/CheckpointCoordinatorTest.java | 53 +++++
.../CheckpointCoordinatorTestingUtils.java | 19 +-
.../CoordinatorEventsExactlyOnceITCase.java | 2 +-
.../coordination/MockOperatorCoordinator.java | 2 +-
.../OperatorCoordinatorHolderTest.java | 2 +-
.../RecreateOnResetOperatorCoordinatorTest.java | 3 +-
.../coordination/TestingOperatorCoordinator.java | 2 +-
.../coordinator/SourceCoordinatorProviderTest.java | 2 +-
.../source/coordinator/SourceCoordinatorTest.java | 12 +-
.../coordinator/SourceCoordinatorTestBase.java | 5 +-
.../streaming/api/datastream/DataStreamUtils.java | 136 ++++++++++-
.../streaming/api/operators/SourceOperator.java | 55 ++++-
.../api/operators/SourceOperatorFactory.java | 10 +-
.../collect/CollectSinkOperatorCoordinator.java | 2 +-
.../runtime/tasks/SourceOperatorStreamTask.java | 8 +-
.../api/operators/SourceOperatorTest.java | 156 ++++++++-----
.../source/SourceOperatorEventTimeTest.java | 14 +-
.../operators/source/TestingSourceOperator.java | 13 ++
.../tasks/SourceOperatorStreamTaskTest.java | 57 +++--
.../flink/core/testutils/CommonTestUtils.java | 29 +++
.../source/lib/IteratorSourcesITCase.java | 90 ++++++++
57 files changed, 1590 insertions(+), 274 deletions(-)
rename {flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base => flink-core/src/main/java/org/apache/flink/api/connector}/source/event/NoMoreSplitsEvent.java (96%)
rename {flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base => flink-core/src/main/java/org/apache/flink/api/connector}/source/event/RequestSplitEvent.java (83%)
create mode 100644 flink-core/src/main/java/org/apache/flink/api/connector/source/lib/NumberSequenceSource.java
create mode 100644 flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceEnumerator.java
create mode 100644 flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceReader.java
copy flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingSourceSplit.java => flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceSplit.java (55%)
create mode 100644 flink-core/src/test/java/org/apache/flink/api/connector/source/lib/NumberSequenceSourceTest.java
rename {flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader => flink-core/src/test/java/org/apache/flink/api/connector/source}/mocks/TestingReaderContext.java (93%)
rename {flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader => flink-core/src/test/java/org/apache/flink/api/connector/source}/mocks/TestingReaderOutput.java (96%)
create mode 100644 flink-tests/src/test/java/org/apache/flink/api/connector/source/lib/IteratorSourcesITCase.java
[flink] 11/21: [FLINK-18044][Connectors/Common] Add the subtask
index information to the SourceReaderContext. (#12647)
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 5b2cc0e566150026f359af884dfa201145a1dea7
Author: fangliang <56...@qq.com>
AuthorDate: Wed Oct 28 09:08:38 2020 +0800
[FLINK-18044][Connectors/Common] Add the subtask index information to the SourceReaderContext. (#12647)
---
.../org/apache/flink/api/connector/source/SourceReaderContext.java | 5 +++++
.../flink/api/connector/source/mocks/TestingReaderContext.java | 5 +++++
.../org/apache/flink/streaming/api/operators/SourceOperator.java | 5 +++++
3 files changed, 15 insertions(+)
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceReaderContext.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceReaderContext.java
index c8ed36d..4d9e53a 100644
--- a/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceReaderContext.java
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceReaderContext.java
@@ -45,6 +45,11 @@ public interface SourceReaderContext {
String getLocalHostName();
/**
+ * @return The index of this subtask.
+ */
+ int getIndexOfSubtask();
+
+ /**
* Send a source event to the source coordinator.
*
* @param sourceEvent the source event to coordinator.
diff --git a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/TestingReaderContext.java b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/TestingReaderContext.java
index cee4654..3f254e4 100644
--- a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/TestingReaderContext.java
+++ b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/TestingReaderContext.java
@@ -64,6 +64,11 @@ public class TestingReaderContext implements SourceReaderContext {
}
@Override
+ public int getIndexOfSubtask() {
+ return 0;
+ }
+
+ @Override
public void sendSourceEventToCoordinator(SourceEvent sourceEvent) {
sentEvents.add(sourceEvent);
}
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
index 05b3216..d925b23 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
@@ -151,6 +151,11 @@ public class SourceOperator<OUT, SplitT extends SourceSplit>
}
@Override
+ public int getIndexOfSubtask() {
+ return getRuntimeContext().getIndexOfThisSubtask();
+ }
+
+ @Override
public void sendSourceEventToCoordinator(SourceEvent event) {
operatorEventGateway.sendEventToCoordinator(new SourceEventWrapper(event));
}
[flink] 06/21: [refactor][tests] Move some source test utils from
flink-connector-base to flink-core
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 7916ad7680ee048353b58c37db263dfff3cb18bb
Author: Stephan Ewen <se...@apache.org>
AuthorDate: Tue Sep 29 22:25:37 2020 +0200
[refactor][tests] Move some source test utils from flink-connector-base to flink-core
This makes them reusable in unit tests for simple sources that are implemented in flink-core
---
.../flink/connector/base/source/reader/SourceReaderBaseTest.java | 4 ++--
.../flink/api/connector/source}/mocks/TestingReaderContext.java | 2 +-
.../apache/flink/api/connector/source}/mocks/TestingReaderOutput.java | 2 +-
3 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderBaseTest.java b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderBaseTest.java
index ce32521..6396b2e 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderBaseTest.java
+++ b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderBaseTest.java
@@ -21,12 +21,12 @@ package org.apache.flink.connector.base.source.reader;
import org.apache.flink.api.connector.source.Boundedness;
import org.apache.flink.api.connector.source.SourceReader;
import org.apache.flink.api.connector.source.mocks.MockSourceSplit;
+import org.apache.flink.api.connector.source.mocks.TestingReaderContext;
+import org.apache.flink.api.connector.source.mocks.TestingReaderOutput;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.base.source.reader.mocks.MockSourceReader;
import org.apache.flink.connector.base.source.reader.mocks.MockSplitReader;
import org.apache.flink.connector.base.source.reader.mocks.PassThroughRecordEmitter;
-import org.apache.flink.connector.base.source.reader.mocks.TestingReaderContext;
-import org.apache.flink.connector.base.source.reader.mocks.TestingReaderOutput;
import org.apache.flink.connector.base.source.reader.mocks.TestingRecordsWithSplitIds;
import org.apache.flink.connector.base.source.reader.mocks.TestingSourceSplit;
import org.apache.flink.connector.base.source.reader.mocks.TestingSplitReader;
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingReaderContext.java b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/TestingReaderContext.java
similarity index 97%
rename from flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingReaderContext.java
rename to flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/TestingReaderContext.java
index 5bb9b59..cee4654 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingReaderContext.java
+++ b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/TestingReaderContext.java
@@ -16,7 +16,7 @@
* limitations under the License.
*/
-package org.apache.flink.connector.base.source.reader.mocks;
+package org.apache.flink.api.connector.source.mocks;
import org.apache.flink.api.connector.source.SourceEvent;
import org.apache.flink.api.connector.source.SourceReaderContext;
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingReaderOutput.java b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/TestingReaderOutput.java
similarity index 96%
rename from flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingReaderOutput.java
rename to flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/TestingReaderOutput.java
index 4483819..1847cc4 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingReaderOutput.java
+++ b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/TestingReaderOutput.java
@@ -16,7 +16,7 @@
* limitations under the License.
*/
-package org.apache.flink.connector.base.source.reader.mocks;
+package org.apache.flink.api.connector.source.mocks;
import org.apache.flink.api.common.eventtime.Watermark;
import org.apache.flink.api.connector.source.ReaderOutput;
[flink] 02/21: [backport] Relevant test mock changes from
"[FLINK-18907][test] Refactor MockSourceReader"
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit ecc6a8aa30d761e0cf2174d8ef00f168b1d45d84
Author: Piotr Nowojski <pi...@gmail.com>
AuthorDate: Tue Sep 22 11:43:58 2020 +0200
[backport] Relevant test mock changes from "[FLINK-18907][test] Refactor MockSourceReader"
Make the synchronisation around availability easier to understand.
---
.../connector/source/mocks/MockSourceReader.java | 53 +++++++++++++---------
1 file changed, 32 insertions(+), 21 deletions(-)
diff --git a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
index bdccf88..d474e1f 100644
--- a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
+++ b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
@@ -23,28 +23,30 @@ import org.apache.flink.api.connector.source.SourceEvent;
import org.apache.flink.api.connector.source.SourceReader;
import org.apache.flink.core.io.InputStatus;
+import javax.annotation.concurrent.GuardedBy;
+
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.atomic.AtomicReference;
/**
* A mock {@link SourceReader} for unit tests.
*/
public class MockSourceReader implements SourceReader<Integer, MockSourceSplit> {
- private final AtomicReference<CompletableFuture<Void>> availableRef;
- private List<MockSourceSplit> assignedSplits;
- private List<SourceEvent> receivedSourceEvents;
+ private final List<MockSourceSplit> assignedSplits = new ArrayList<>();
+ private final List<SourceEvent> receivedSourceEvents = new ArrayList<>();
+
private int currentSplitIndex = 0;
private boolean started;
private boolean closed;
+ @GuardedBy("this")
+ private CompletableFuture<Void> availableFuture;
+
public MockSourceReader() {
- this.assignedSplits = new ArrayList<>();
- this.receivedSourceEvents = new ArrayList<>();
this.started = false;
this.closed = false;
- this.availableRef = new AtomicReference<>();
+ this.availableFuture = CompletableFuture.completedFuture(null);
}
@Override
@@ -66,9 +68,13 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
if (currentSplitIndex < assignedSplits.size()) {
sourceOutput.collect(assignedSplits.get(currentSplitIndex).getNext(false)[0]);
return InputStatus.MORE_AVAILABLE;
- } else {
+ } else if (finished) {
// In case no split has available record, return depending on whether all the splits has finished.
- return finished ? InputStatus.END_OF_INPUT : InputStatus.NOTHING_AVAILABLE;
+ return InputStatus.END_OF_INPUT;
+ }
+ else {
+ markUnavailable();
+ return InputStatus.NOTHING_AVAILABLE;
}
}
@@ -78,19 +84,14 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
}
@Override
- public CompletableFuture<Void> isAvailable() {
- if (currentSplitIndex >= assignedSplits.size()) {
- CompletableFuture<Void> future = new CompletableFuture<>();
- availableRef.compareAndSet(null, future);
- return availableRef.get();
- } else {
- return CompletableFuture.completedFuture(null);
- }
+ public synchronized CompletableFuture<Void> isAvailable() {
+ return availableFuture;
}
@Override
public void addSplits(List<MockSourceSplit> splits) {
assignedSplits.addAll(splits);
+ markAvailable();
}
@Override
@@ -103,13 +104,23 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
this.closed = true;
}
+ private synchronized void markUnavailable() {
+ if (availableFuture.isDone()) {
+ availableFuture = new CompletableFuture<>();
+ }
+ }
+
// --------------- methods for unit tests ---------------
public void markAvailable() {
- CompletableFuture<Void> future = availableRef.get();
- if (future != null) {
- future.complete(null);
- availableRef.set(null);
+ CompletableFuture<?> toNotify = null;
+ synchronized (this) {
+ if (!availableFuture.isDone()) {
+ toNotify = availableFuture;
+ }
+ }
+ if (toNotify != null) {
+ toNotify.complete(null);
}
}
[flink] 18/21: [FLINK-19698][connector/common] Add a close() method
to the SplitReader.
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 2a775894dc2144af9b6d7361a06d15afedb5945f
Author: Jiangjie (Becket) Qin <ji...@alibaba-inc.com>
AuthorDate: Sun Oct 25 11:07:27 2020 +0800
[FLINK-19698][connector/common] Add a close() method to the SplitReader.
---
.../base/source/reader/fetcher/SplitFetcher.java | 10 ++++++++--
.../source/reader/splitreader/SplitReader.java | 7 +++++++
.../base/source/reader/SourceReaderBaseTest.java | 6 ++++--
.../reader/fetcher/SplitFetcherManagerTest.java | 22 ++++++++++++++++++++++
.../source/reader/fetcher/SplitFetcherTest.java | 9 +++++++++
.../base/source/reader/mocks/MockSplitReader.java | 3 +++
.../source/reader/mocks/TestingSplitReader.java | 20 ++++++++++++++++++++
7 files changed, 73 insertions(+), 4 deletions(-)
diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcher.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcher.java
index 633c452..96663ab 100644
--- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcher.java
+++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcher.java
@@ -22,6 +22,7 @@ import org.apache.flink.api.connector.source.SourceSplit;
import org.apache.flink.connector.base.source.reader.RecordsWithSplitIds;
import org.apache.flink.connector.base.source.reader.splitreader.SplitReader;
import org.apache.flink.connector.base.source.reader.synchronization.FutureCompletingBlockingQueue;
+import org.apache.flink.util.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -49,7 +50,7 @@ public class SplitFetcher<E, SplitT extends SourceSplit> implements Runnable {
private final Runnable shutdownHook;
private final AtomicBoolean wakeUp;
private final AtomicBoolean closed;
- private FetchTask<E, SplitT> fetchTask;
+ private final FetchTask<E, SplitT> fetchTask;
private volatile SplitFetcherTask runningTask = null;
/** Flag whether this fetcher has no work assigned at the moment.
@@ -91,8 +92,13 @@ public class SplitFetcher<E, SplitT extends SourceSplit> implements Runnable {
runOnce();
}
} finally {
- shutdownHook.run();
LOG.info("Split fetcher {} exited.", id);
+ shutdownHook.run();
+ try {
+ splitReader.close();
+ } catch (Exception e) {
+ ExceptionUtils.rethrow(e);
+ }
}
}
diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/splitreader/SplitReader.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/splitreader/SplitReader.java
index 7504452..87deeb9 100644
--- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/splitreader/SplitReader.java
+++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/splitreader/SplitReader.java
@@ -57,4 +57,11 @@ public interface SplitReader<E, SplitT extends SourceSplit> {
* {@link #fetch()}.
*/
void wakeUp();
+
+ /**
+ * Close the split reader.
+ *
+ * @throws Exception if closing the split reader failed.
+ */
+ void close() throws Exception;
}
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderBaseTest.java b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderBaseTest.java
index da057da..f14ddb1 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderBaseTest.java
+++ b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderBaseTest.java
@@ -75,8 +75,10 @@ public class SourceReaderBaseTest extends SourceReaderTestBase<MockSourceSplit>
public void handleSplitsChanges(SplitsChange<MockSourceSplit> splitsChanges) {}
@Override
- public void wakeUp() {
- }
+ public void wakeUp() {}
+
+ @Override
+ public void close() throws Exception {}
},
getConfig(),
null)) {
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherManagerTest.java b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherManagerTest.java
index 6d7b8b1..3fd6a792 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherManagerTest.java
+++ b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherManagerTest.java
@@ -22,11 +22,13 @@ import org.apache.flink.api.connector.source.SourceSplit;
import org.apache.flink.connector.base.source.reader.RecordsWithSplitIds;
import org.apache.flink.connector.base.source.reader.mocks.TestingRecordsWithSplitIds;
import org.apache.flink.connector.base.source.reader.mocks.TestingSourceSplit;
+import org.apache.flink.connector.base.source.reader.mocks.TestingSplitReader;
import org.apache.flink.connector.base.source.reader.splitreader.SplitReader;
import org.apache.flink.connector.base.source.reader.splitreader.SplitsChange;
import org.apache.flink.connector.base.source.reader.synchronization.FutureCompletingBlockingQueue;
import org.apache.flink.core.testutils.OneShotLatch;
+import org.apache.commons.lang3.exception.ExceptionUtils;
import org.junit.Test;
import java.io.IOException;
@@ -35,6 +37,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.Queue;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
@@ -57,6 +60,22 @@ public class SplitFetcherManagerTest {
);
}
+ @Test
+ public void testCloseFetcherWithException() throws Exception {
+ TestingSplitReader<Object, TestingSourceSplit> reader = new TestingSplitReader<>();
+ reader.setCloseWithException();
+ SplitFetcherManager<Object, TestingSourceSplit> fetcherManager =
+ createFetcher("test-split", new FutureCompletingBlockingQueue<>(), reader);
+ fetcherManager.close(1000L);
+ try {
+ fetcherManager.checkErrors();
+ } catch (Exception e) {
+ assertEquals(
+ "Artificial exception on closing the split reader.",
+ ExceptionUtils.getRootCause(e).getMessage());
+ }
+ }
+
// the final modifier is important so that '@SafeVarargs' is accepted on Java 8
@SuppressWarnings("FinalPrivateMethod")
@SafeVarargs
@@ -146,6 +165,9 @@ public class SplitFetcherManagerTest {
@Override
public void wakeUp() {}
+ @Override
+ public void close() throws Exception {}
+
public void awaitAllRecordsReturned() throws InterruptedException {
inBlocking.await();
}
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherTest.java b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherTest.java
index 5082ebf..d96d495 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherTest.java
+++ b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherTest.java
@@ -227,6 +227,15 @@ public class SplitFetcherTest {
}
}
+ @Test
+ public void testClose() {
+ TestingSplitReader<Object, TestingSourceSplit> splitReader = new TestingSplitReader<>();
+ final SplitFetcher<Object, TestingSourceSplit> fetcher = createFetcher(splitReader);
+ fetcher.shutdown();
+ fetcher.run();
+ assertTrue(splitReader.isClosed());
+ }
+
// ------------------------------------------------------------------------
// testing utils
// ------------------------------------------------------------------------
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/MockSplitReader.java b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/MockSplitReader.java
index f3d15f6..e991b9c 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/MockSplitReader.java
+++ b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/MockSplitReader.java
@@ -77,6 +77,9 @@ public class MockSplitReader implements SplitReader<int[], MockSourceSplit> {
}
}
+ @Override
+ public void close() throws Exception {}
+
private RecordsBySplits<int[]> getRecords() {
final RecordsBySplits.Builder<int[]> records = new RecordsBySplits.Builder<>();
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingSplitReader.java b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingSplitReader.java
index 2e6c760..505e797 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingSplitReader.java
+++ b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingSplitReader.java
@@ -33,11 +33,15 @@ import java.util.Arrays;
public class TestingSplitReader<E, SplitT extends SourceSplit> implements SplitReader<E, SplitT> {
private final ArrayDeque<RecordsWithSplitIds<E>> fetches;
+ private volatile boolean closed;
+ private volatile boolean closeWithException;
@SafeVarargs
public TestingSplitReader(RecordsWithSplitIds<E>... fetches) {
this.fetches = new ArrayDeque<>(fetches.length);
this.fetches.addAll(Arrays.asList(fetches));
+ this.closed = false;
+ this.closeWithException = false;
}
@Override
@@ -66,4 +70,20 @@ public class TestingSplitReader<E, SplitT extends SourceSplit> implements SplitR
fetches.notifyAll();
}
}
+
+ @Override
+ public void close() throws Exception {
+ if (closeWithException) {
+ throw new Exception("Artificial exception on closing the split reader.");
+ }
+ closed = true;
+ }
+
+ public void setCloseWithException() {
+ closeWithException = true;
+ }
+
+ public boolean isClosed() {
+ return closed;
+ }
}
[flink] 17/21: Backport of "[FLINK-19698][connector/common] Let
SplitEnumerator/SourceReader/SourceCoordinator implement
CheckpointListener."
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 5f63e346d2bdb3f2d5de341e2de880c07ca81c16
Author: Jiangjie (Becket) Qin <ji...@alibaba-inc.com>
AuthorDate: Sun Oct 25 10:07:16 2020 +0800
Backport of "[FLINK-19698][connector/common] Let SplitEnumerator/SourceReader/SourceCoordinator implement CheckpointListener."
The backport does not move the 'CheckpointListener' interface, to not break this between minor versions.
Instead, it lets the Reader and Enumerator offer the same methods directly. This is compatible with inheriting
these methods in 1.12 (and 1.12 adds the interface to the class inheritance signature, which is also non-breaking).
---
.../base/source/reader/SourceReaderBase.java | 2 +-
.../base/source/reader/SourceReaderBaseTest.java | 6 ++-
.../base/source/reader/SourceReaderTestBase.java | 2 +-
.../base/source/reader/mocks/MockSourceReader.java | 5 ++
.../flink/api/connector/source/SourceReader.java | 19 +++++++-
.../api/connector/source/SplitEnumerator.java | 17 ++++++-
.../source/lib/util/IteratorSourceReader.java | 2 +-
.../source/lib/NumberSequenceSourceTest.java | 2 +-
.../connector/source/mocks/MockSourceReader.java | 22 ++++++++-
.../source/mocks/MockSplitEnumerator.java | 21 +++++++--
.../runtime/checkpoint/CheckpointCoordinator.java | 7 ++-
.../OperatorCoordinatorCheckpointContext.java | 19 +++++++-
.../coordination/OperatorCoordinator.java | 40 +++++++---------
.../coordination/OperatorCoordinatorHolder.java | 18 +++++---
.../RecreateOnResetOperatorCoordinator.java | 4 +-
.../source/coordinator/SourceCoordinator.java | 22 +++++++--
.../checkpoint/CheckpointCoordinatorTest.java | 53 ++++++++++++++++++++++
.../CheckpointCoordinatorTestingUtils.java | 19 +++++++-
.../CoordinatorEventsExactlyOnceITCase.java | 2 +-
.../coordination/MockOperatorCoordinator.java | 2 +-
.../OperatorCoordinatorHolderTest.java | 2 +-
.../coordination/TestingOperatorCoordinator.java | 2 +-
.../source/coordinator/SourceCoordinatorTest.java | 12 ++++-
.../streaming/api/operators/SourceOperator.java | 17 ++++++-
.../collect/CollectSinkOperatorCoordinator.java | 2 +-
.../api/operators/SourceOperatorTest.java | 53 +++++++++++++++++++++-
.../source/SourceOperatorEventTimeTest.java | 2 +-
.../operators/source/TestingSourceOperator.java | 13 ++++++
28 files changed, 321 insertions(+), 66 deletions(-)
diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderBase.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderBase.java
index e1da654..2c6c1812 100644
--- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderBase.java
+++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderBase.java
@@ -204,7 +204,7 @@ public abstract class SourceReaderBase<E, T, SplitT extends SourceSplit, SplitSt
}
@Override
- public List<SplitT> snapshotState() {
+ public List<SplitT> snapshotState(long checkpointId) {
List<SplitT> splits = new ArrayList<>();
splitStates.forEach((id, context) -> splits.add(toSplitType(id, context.state)));
return splits;
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderBaseTest.java b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderBaseTest.java
index 6396b2e..da057da 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderBaseTest.java
+++ b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderBaseTest.java
@@ -185,8 +185,10 @@ public class SourceReaderBaseTest extends SourceReaderTestBase<MockSourceSplit>
new TestingReaderContext()) {
@Override
- protected void onSplitFinished(Collection<String> finishedSplitIds) {
- }
+ public void notifyCheckpointComplete(long checkpointId) throws Exception {}
+
+ @Override
+ protected void onSplitFinished(Collection<String> finishedSplitIds) {}
@Override
protected TestingSourceSplit initializedState(TestingSourceSplit split) {
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderTestBase.java b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderTestBase.java
index 22dda52..015cd89 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderTestBase.java
+++ b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/SourceReaderTestBase.java
@@ -132,7 +132,7 @@ public abstract class SourceReaderTestBase<SplitT extends SourceSplit> extends T
List<SplitT> splits = getSplits(NUM_SPLITS, NUM_RECORDS_PER_SPLIT, Boundedness.CONTINUOUS_UNBOUNDED);
try (SourceReader<Integer, SplitT> reader =
consumeRecords(splits, output, NUM_SPLITS * NUM_RECORDS_PER_SPLIT)) {
- List<SplitT> state = reader.snapshotState();
+ List<SplitT> state = reader.snapshotState(1L);
assertEquals("The snapshot should only have 10 splits. ", NUM_SPLITS, state.size());
for (int i = 0; i < NUM_SPLITS; i++) {
assertEquals("The first four splits should have been fully consumed.",
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/MockSourceReader.java b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/MockSourceReader.java
index 66022db..9de22aa 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/MockSourceReader.java
+++ b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/MockSourceReader.java
@@ -57,4 +57,9 @@ public class MockSourceReader
protected MockSourceSplit toSplitType(String splitId, AtomicInteger splitState) {
return new MockSourceSplit(Integer.parseInt(splitId), splitState.get());
}
+
+ @Override
+ public void notifyCheckpointComplete(long checkpointId) throws Exception {
+
+ }
}
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceReader.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceReader.java
index 3e623dd..0aac1b1 100644
--- a/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceReader.java
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceReader.java
@@ -32,7 +32,8 @@ import java.util.concurrent.CompletableFuture;
* @param <SplitT> The type of the the source splits.
*/
@PublicEvolving
-public interface SourceReader<T, SplitT extends SourceSplit> extends AutoCloseable {
+public interface SourceReader<T, SplitT extends SourceSplit>
+ extends AutoCloseable {
/**
* Start the reader.
@@ -58,7 +59,7 @@ public interface SourceReader<T, SplitT extends SourceSplit> extends AutoCloseab
*
* @return the state of the source.
*/
- List<SplitT> snapshotState();
+ List<SplitT> snapshotState(long checkpointId);
/**
* @return a future that will be completed once there is a record available to poll.
@@ -78,4 +79,18 @@ public interface SourceReader<T, SplitT extends SourceSplit> extends AutoCloseab
* @param sourceEvent the event sent by the {@link SplitEnumerator}.
*/
void handleSourceEvents(SourceEvent sourceEvent);
+
+ /**
+ * We have an empty default implementation here because most source readers do not have
+ * to implement the method.
+ */
+ default void notifyCheckpointComplete(long checkpointId) throws Exception {}
+
+ /**
+ * Called when a checkpoint is aborted.
+ *
+ * <p>NOTE: This method is here only in the backport to the Flink 1.11 branch.
+ * In 1.12, this default method is inherited from the CheckpointListener interface.
+ */
+ default void notifyCheckpointAborted(long checkpointId) {}
}
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/SplitEnumerator.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/SplitEnumerator.java
index 1e429bb..e97f5e1 100644
--- a/flink-core/src/main/java/org/apache/flink/api/connector/source/SplitEnumerator.java
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/SplitEnumerator.java
@@ -29,7 +29,8 @@ import java.util.List;
* 2. assign the splits to the source reader.
*/
@PublicEvolving
-public interface SplitEnumerator<SplitT extends SourceSplit, CheckpointT> extends AutoCloseable {
+public interface SplitEnumerator<SplitT extends SourceSplit, CheckpointT>
+ extends AutoCloseable {
/**
* Start the split enumerator.
@@ -76,4 +77,18 @@ public interface SplitEnumerator<SplitT extends SourceSplit, CheckpointT> extend
*/
@Override
void close() throws IOException;
+
+ /**
+ * We have an empty default implementation here because most source readers do not have
+ * to implement the method.
+ */
+ default void notifyCheckpointComplete(long checkpointId) throws Exception {}
+
+ /**
+ * Called when a checkpoint is aborted.
+ *
+ * <p>NOTE: This method is here only in the backport to the Flink 1.11 branch.
+ * In 1.12, this default method is inherited from the CheckpointListener interface.
+ */
+ default void notifyCheckpointAborted(long checkpointId) {}
}
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceReader.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceReader.java
index 54ddb35..3af75e1 100644
--- a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceReader.java
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceReader.java
@@ -122,7 +122,7 @@ public class IteratorSourceReader<E, IterT extends Iterator<E>, SplitT extends I
}
@Override
- public List<SplitT> snapshotState() {
+ public List<SplitT> snapshotState(long checkpointId) {
final ArrayList<SplitT> allSplits = new ArrayList<>(1 + remainingSplits.size());
if (iterator != null) {
@SuppressWarnings("unchecked")
diff --git a/flink-core/src/test/java/org/apache/flink/api/connector/source/lib/NumberSequenceSourceTest.java b/flink-core/src/test/java/org/apache/flink/api/connector/source/lib/NumberSequenceSourceTest.java
index 450983e..48cda2d 100644
--- a/flink-core/src/test/java/org/apache/flink/api/connector/source/lib/NumberSequenceSourceTest.java
+++ b/flink-core/src/test/java/org/apache/flink/api/connector/source/lib/NumberSequenceSourceTest.java
@@ -54,7 +54,7 @@ public class NumberSequenceSourceTest {
if (--remainingInCycle <= 0) {
remainingInCycle = elementsPerCycle;
// checkpoint
- List<NumberSequenceSource.NumberSequenceSplit> splits = reader.snapshotState();
+ List<NumberSequenceSource.NumberSequenceSplit> splits = reader.snapshotState(1L);
// re-create and restore
reader = createReader();
diff --git a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
index e48f827..b0a24dd 100644
--- a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
+++ b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
@@ -35,6 +35,8 @@ import java.util.concurrent.CompletableFuture;
public class MockSourceReader implements SourceReader<Integer, MockSourceSplit> {
private final List<MockSourceSplit> assignedSplits = new ArrayList<>();
private final List<SourceEvent> receivedSourceEvents = new ArrayList<>();
+ private final List<Long> completedCheckpoints = new ArrayList<>();
+ private final List<Long> abortedCheckpoints = new ArrayList<>();
private final boolean markIdleOnNoSplits;
private int currentSplitIndex = 0;
@@ -90,7 +92,7 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
}
@Override
- public List<MockSourceSplit> snapshotState() {
+ public List<MockSourceSplit> snapshotState(long checkpointId) {
return assignedSplits;
}
@@ -119,6 +121,16 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
this.closed = true;
}
+ @Override
+ public void notifyCheckpointComplete(long checkpointId) {
+ completedCheckpoints.add(checkpointId);
+ }
+
+ @Override
+ public void notifyCheckpointAborted(long checkpointId) {
+ abortedCheckpoints.add(checkpointId);
+ }
+
private synchronized void markUnavailable() {
if (availableFuture.isDone()) {
availableFuture = new CompletableFuture<>();
@@ -155,6 +167,14 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
return receivedSourceEvents;
}
+ public List<Long> getCompletedCheckpoints() {
+ return completedCheckpoints;
+ }
+
+ public List<Long> getAbortedCheckpoints() {
+ return abortedCheckpoints;
+ }
+
/**
* Simple event allowing {@link MockSourceReader} to finish when requested.
*/
diff --git a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSplitEnumerator.java b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSplitEnumerator.java
index 93f6c77..0525533 100644
--- a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSplitEnumerator.java
+++ b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSplitEnumerator.java
@@ -39,11 +39,12 @@ import java.util.TreeSet;
* A mock {@link SplitEnumerator} for unit tests.
*/
public class MockSplitEnumerator implements SplitEnumerator<MockSourceSplit, Set<MockSourceSplit>> {
- private SortedSet<MockSourceSplit> unassignedSplits;
- private SplitEnumeratorContext<MockSourceSplit> enumContext;
- private List<SourceEvent> handledSourceEvent;
- private boolean started;
- private boolean closed;
+ private final SortedSet<MockSourceSplit> unassignedSplits;
+ private final SplitEnumeratorContext<MockSourceSplit> enumContext;
+ private final List<SourceEvent> handledSourceEvent;
+ private final List<Long> successfulCheckpoints;
+ private volatile boolean started;
+ private volatile boolean closed;
public MockSplitEnumerator(int numSplits, SplitEnumeratorContext<MockSourceSplit> enumContext) {
this(new HashSet<>(), enumContext);
@@ -59,6 +60,7 @@ public class MockSplitEnumerator implements SplitEnumerator<MockSourceSplit, Set
this.unassignedSplits.addAll(unassignedSplits);
this.enumContext = enumContext;
this.handledSourceEvent = new ArrayList<>();
+ this.successfulCheckpoints = new ArrayList<>();
this.started = false;
this.closed = false;
}
@@ -96,6 +98,11 @@ public class MockSplitEnumerator implements SplitEnumerator<MockSourceSplit, Set
}
@Override
+ public void notifyCheckpointComplete(long checkpointId) {
+ successfulCheckpoints.add(checkpointId);
+ }
+
+ @Override
public void close() throws IOException {
this.closed = true;
}
@@ -123,6 +130,10 @@ public class MockSplitEnumerator implements SplitEnumerator<MockSourceSplit, Set
return handledSourceEvent;
}
+ public List<Long> getSuccessfulCheckpoints() {
+ return successfulCheckpoints;
+ }
+
// --------------------
private void assignAllSplits() {
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java
index 26cf391..0e61a11 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java
@@ -1144,7 +1144,7 @@ public class CheckpointCoordinator {
// commit coordinators
for (OperatorCoordinatorCheckpointContext coordinatorContext : coordinatorsToCheckpoint) {
- coordinatorContext.checkpointComplete(checkpointId);
+ coordinatorContext.notifyCheckpointComplete(checkpointId);
}
}
@@ -1159,6 +1159,11 @@ public class CheckpointCoordinator {
}
}
});
+
+ // commit coordinators
+ for (OperatorCoordinatorCheckpointContext coordinatorContext : coordinatorsToCheckpoint) {
+ coordinatorContext.notifyCheckpointAborted(checkpointId);
+ }
}
/**
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/OperatorCoordinatorCheckpointContext.java b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/OperatorCoordinatorCheckpointContext.java
index 94d4e07..f5f72d8 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/OperatorCoordinatorCheckpointContext.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/OperatorCoordinatorCheckpointContext.java
@@ -20,6 +20,7 @@ package org.apache.flink.runtime.checkpoint;
import org.apache.flink.runtime.operators.coordination.OperatorCoordinator;
import org.apache.flink.runtime.operators.coordination.OperatorInfo;
+import org.apache.flink.runtime.state.CheckpointListener;
import java.util.concurrent.CompletableFuture;
@@ -27,7 +28,7 @@ import java.util.concurrent.CompletableFuture;
* This context is the interface through which the {@link CheckpointCoordinator} interacts with an
* {@link OperatorCoordinator} during checkpointing and checkpoint restoring.
*/
-public interface OperatorCoordinatorCheckpointContext extends OperatorInfo {
+public interface OperatorCoordinatorCheckpointContext extends OperatorInfo, CheckpointListener {
void checkpointCoordinator(long checkpointId, CompletableFuture<byte[]> result) throws Exception;
@@ -35,7 +36,21 @@ public interface OperatorCoordinatorCheckpointContext extends OperatorInfo {
void abortCurrentTriggering();
- void checkpointComplete(long checkpointId);
+ /**
+ * We override the method here to remove the checked exception. Please check the
+ * Java docs of {@link CheckpointListener#notifyCheckpointComplete(long)} for more
+ * detail semantic of the method.
+ */
+ @Override
+ void notifyCheckpointComplete(long checkpointId);
+
+ /**
+ * We override the method here to remove the checked exception. Please check the
+ * Java docs of {@link CheckpointListener#notifyCheckpointAborted(long)} for more
+ * detail semantic of the method.
+ */
+ @Override
+ default void notifyCheckpointAborted(long checkpointId) {}
void resetToCheckpoint(byte[] checkpointData) throws Exception;
}
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinator.java
index fff88c7..bc280f0 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinator.java
@@ -20,6 +20,7 @@ package org.apache.flink.runtime.operators.coordination;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.messages.Acknowledge;
+import org.apache.flink.runtime.state.CheckpointListener;
import javax.annotation.Nullable;
@@ -43,7 +44,7 @@ import java.util.concurrent.CompletableFuture;
* The methods on the {@link Context} are safe to be called from another thread than the thread that
* calls the Coordinator's methods.
*/
-public interface OperatorCoordinator extends AutoCloseable {
+public interface OperatorCoordinator extends CheckpointListener, AutoCloseable {
/**
* Starts the coordinator. This method is called once at the beginning, before any other methods.
@@ -102,27 +103,20 @@ public interface OperatorCoordinator extends AutoCloseable {
void checkpointCoordinator(long checkpointId, CompletableFuture<byte[]> resultFuture) throws Exception;
/**
- * Notifies the coordinator that the checkpoint with the given checkpointId completes and
- * was committed.
- *
- * <h3>Checkpoint Subsuming</h3>
- *
- * <p>Checkpoint IDs are strictly increasing. A checkpoint with higher ID always subsumes
- * a checkpoint with lower ID. For example, when checkpoint T is confirmed complete, the
- * code should treat all checkpoints with lower ID (T-1, T-2, etc.) also as confirmed.
- *
- * <h3>Exceptions</h3>
- *
- * <p>This method is not supposed to throw an exception indicating the the checkpoint cannot
- * be completed. By the time we notify that the checkpoint is complete, the checkpoint is
- * committed and cannot be aborted any more.
- *
- * <p>If the coordinator gets into an inconsistent state internally, as a result of logic that
- * runs after this notification, it should fail the job ({@link Context#failJob(Throwable)})
- * instead. Any exception propagating from this method may be treated as a fatal error for the
- * JobManager, crashing the JobManager, and leading to an expensive "master failover" procedure.
+ * We override the method here to remove the checked exception. Please check the
+ * Java docs of {@link CheckpointListener#notifyCheckpointComplete(long)} for more
+ * detail semantic of the method.
*/
- void checkpointComplete(long checkpointId);
+ @Override
+ void notifyCheckpointComplete(long checkpointId);
+
+ /**
+ * We override the method here to remove the checked exception. Please check the
+ * Java docs of {@link CheckpointListener#notifyCheckpointAborted(long)} for more
+ * detail semantic of the method.
+ */
+ @Override
+ default void notifyCheckpointAborted(long checkpointId) {}
/**
* Resets the coordinator to the given checkpoint.
@@ -139,9 +133,9 @@ public interface OperatorCoordinator extends AutoCloseable {
* It is safe to commit side-effects that are predicated on checkpoint completion after this
* call.
*
- * <p>Even if no call to {@link #checkpointComplete(long)} happened, the checkpoint can still be
+ * <p>Even if no call to {@link #notifyCheckpointComplete(long)} happened, the checkpoint can still be
* complete (for example when a system failure happened directly after committing the checkpoint,
- * before calling the {@link #checkpointComplete(long)} method).
+ * before calling the {@link #notifyCheckpointComplete(long)} method).
*/
void resetToCheckpoint(byte[] checkpointData) throws Exception;
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorHolder.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorHolder.java
index 4e4e8f5..9819754 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorHolder.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorHolder.java
@@ -208,12 +208,21 @@ public class OperatorCoordinatorHolder implements OperatorCoordinator, OperatorC
}
@Override
- public void checkpointComplete(long checkpointId) {
+ public void notifyCheckpointComplete(long checkpointId) {
// unfortunately, this method does not run in the scheduler executor, but in the
// checkpoint coordinator time thread.
// we can remove the delegation once the checkpoint coordinator runs fully in the scheduler's
// main thread executor
- mainThreadExecutor.execute(() -> checkpointCompleteInternal(checkpointId));
+ mainThreadExecutor.execute(() -> coordinator.notifyCheckpointComplete(checkpointId));
+ }
+
+ @Override
+ public void notifyCheckpointAborted(long checkpointId) {
+ // unfortunately, this method does not run in the scheduler executor, but in the
+ // checkpoint coordinator time thread.
+ // we can remove the delegation once the checkpoint coordinator runs fully in the scheduler's
+ // main thread executor
+ mainThreadExecutor.execute(() -> coordinator.notifyCheckpointAborted(checkpointId));
}
@Override
@@ -225,11 +234,6 @@ public class OperatorCoordinatorHolder implements OperatorCoordinator, OperatorC
coordinator.resetToCheckpoint(checkpointData);
}
- private void checkpointCompleteInternal(long checkpointId) {
- mainThreadExecutor.assertRunningInMainThread();
- coordinator.checkpointComplete(checkpointId);
- }
-
private void checkpointCoordinatorInternal(final long checkpointId, final CompletableFuture<byte[]> result) {
mainThreadExecutor.assertRunningInMainThread();
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/RecreateOnResetOperatorCoordinator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/RecreateOnResetOperatorCoordinator.java
index ea91156..c19997c 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/RecreateOnResetOperatorCoordinator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/RecreateOnResetOperatorCoordinator.java
@@ -73,8 +73,8 @@ public class RecreateOnResetOperatorCoordinator implements OperatorCoordinator {
}
@Override
- public void checkpointComplete(long checkpointId) {
- coordinator.checkpointComplete(checkpointId);
+ public void notifyCheckpointComplete(long checkpointId) {
+ coordinator.notifyCheckpointComplete(checkpointId);
}
@Override
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/source/coordinator/SourceCoordinator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/source/coordinator/SourceCoordinator.java
index 3aa095d..a22a239 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/source/coordinator/SourceCoordinator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/source/coordinator/SourceCoordinator.java
@@ -181,15 +181,31 @@ public class SourceCoordinator<SplitT extends SourceSplit, EnumChkT> implements
}
@Override
- public void checkpointComplete(long checkpointId) {
+ public void notifyCheckpointComplete(long checkpointId) {
ensureStarted();
coordinatorExecutor.execute(() -> {
try {
LOG.info("Marking checkpoint {} as completed for source {}.", checkpointId, operatorName);
context.onCheckpointComplete(checkpointId);
+ enumerator.notifyCheckpointComplete(checkpointId);
} catch (Exception e) {
- LOG.error("Failing the job due to exception when completing the checkpoint {} for source {}.",
- checkpointId, operatorName, e);
+ LOG.error("Failing the job due to exception when notifying the completion of the "
+ + "checkpoint {} for source {}.", checkpointId, operatorName, e);
+ context.failJob(e);
+ }
+ });
+ }
+
+ @Override
+ public void notifyCheckpointAborted(long checkpointId) {
+ ensureStarted();
+ coordinatorExecutor.execute(() -> {
+ try {
+ LOG.info("Marking checkpoint {} as aborted for source {}.", checkpointId, operatorName);
+ enumerator.notifyCheckpointAborted(checkpointId);
+ } catch (Exception e) {
+ LOG.error("Failing the job due to exception when notifying abortion of the "
+ + "checkpoint {} for source {}.", checkpointId, operatorName, e);
context.failJob(e);
}
});
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinatorTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinatorTest.java
index 78e5336..1d89596 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinatorTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinatorTest.java
@@ -32,6 +32,7 @@ import org.apache.flink.runtime.executiongraph.Execution;
import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
import org.apache.flink.runtime.executiongraph.ExecutionJobVertex;
import org.apache.flink.runtime.executiongraph.ExecutionVertex;
+import org.apache.flink.runtime.executiongraph.utils.SimpleAckingTaskManagerGateway;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration;
@@ -94,6 +95,7 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static org.apache.flink.runtime.checkpoint.CheckpointCoordinatorTestingUtils.mockExecutionJobVertex;
@@ -2562,6 +2564,57 @@ public class CheckpointCoordinatorTest extends TestLogger {
assertTrue(checkpointCoordinator.getSuccessfulCheckpoints().isEmpty());
}
+ @Test
+ public void testNotifyCheckpointAbortionInOperatorCoordinator() throws Exception {
+ JobID jobId = new JobID();
+ final ExecutionAttemptID attemptID = new ExecutionAttemptID();
+ ExecutionVertex executionVertex = mockExecutionVertex(attemptID);
+
+ CheckpointCoordinatorTestingUtils.MockOperatorCoordinatorCheckpointContext context =
+ new CheckpointCoordinatorTestingUtils.MockOperatorCheckpointCoordinatorContextBuilder()
+ .setOperatorID(new OperatorID())
+ .setOnCallingCheckpointCoordinator((ignored, future) -> future.complete(new byte[0]))
+ .build();
+
+ // set up the coordinator and validate the initial state
+ CheckpointCoordinator checkpointCoordinator = new CheckpointCoordinatorBuilder()
+ .setJobId(jobId)
+ .setTasks(new ExecutionVertex[]{executionVertex})
+ .setCheckpointCoordinatorConfiguration(
+ CheckpointCoordinatorConfiguration
+ .builder()
+ .setMaxConcurrentCheckpoints(Integer.MAX_VALUE)
+ .build())
+ .setTimer(manuallyTriggeredScheduledExecutor)
+ .setCoordinatorsToCheckpoint(Collections.singleton(context))
+ .build();
+ try {
+ // Trigger checkpoint 1.
+ checkpointCoordinator.triggerCheckpoint(false);
+ manuallyTriggeredScheduledExecutor.triggerAll();
+ long checkpointId1 = Collections.max(checkpointCoordinator
+ .getPendingCheckpoints()
+ .keySet());
+ // Trigger checkpoint 2.
+ checkpointCoordinator.triggerCheckpoint(false);
+ manuallyTriggeredScheduledExecutor.triggerAll();
+
+ // Acknowledge checkpoint 2. This should abort checkpoint 1.
+ long checkpointId2 = Collections.max(checkpointCoordinator
+ .getPendingCheckpoints()
+ .keySet());
+ AcknowledgeCheckpoint acknowledgeCheckpoint1 = new AcknowledgeCheckpoint(
+ jobId, attemptID, checkpointId2, new CheckpointMetrics(), null);
+ checkpointCoordinator.receiveAcknowledgeMessage(acknowledgeCheckpoint1, "");
+
+ // OperatorCoordinator should have been notified of the abortion of checkpoint 1.
+ assertEquals(Collections.singletonList(1L), context.getAbortedCheckpoints());
+ assertEquals(Collections.singletonList(2L), context.getCompletedCheckpoints());
+ } finally {
+ checkpointCoordinator.shutdown(JobStatus.FINISHED);
+ }
+ }
+
private CheckpointCoordinator getCheckpointCoordinator(
JobID jobId,
ExecutionVertex vertex1,
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinatorTestingUtils.java b/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinatorTestingUtils.java
index df1395f..7e7e731 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinatorTestingUtils.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinatorTestingUtils.java
@@ -791,6 +791,8 @@ public class CheckpointCoordinatorTestingUtils {
private final BiConsumer<Long, CompletableFuture<byte[]>> onCallingCheckpointCoordinator;
private final Consumer<Long> onCallingAfterSourceBarrierInjection;
private final OperatorID operatorID;
+ private final List<Long> completedCheckpoints;
+ private final List<Long> abortedCheckpoints;
private MockOperatorCoordinatorCheckpointContext(
BiConsumer<Long, CompletableFuture<byte[]>> onCallingCheckpointCoordinator,
@@ -799,6 +801,8 @@ public class CheckpointCoordinatorTestingUtils {
this.onCallingCheckpointCoordinator = onCallingCheckpointCoordinator;
this.onCallingAfterSourceBarrierInjection = onCallingAfterSourceBarrierInjection;
this.operatorID = operatorID;
+ this.completedCheckpoints = new ArrayList<>();
+ this.abortedCheckpoints = new ArrayList<>();
}
@Override
@@ -821,8 +825,13 @@ public class CheckpointCoordinatorTestingUtils {
}
@Override
- public void checkpointComplete(long checkpointId) {
+ public void notifyCheckpointComplete(long checkpointId) {
+ completedCheckpoints.add(checkpointId);
+ }
+ @Override
+ public void notifyCheckpointAborted(long checkpointId) {
+ abortedCheckpoints.add(checkpointId);
}
@Override
@@ -844,6 +853,14 @@ public class CheckpointCoordinatorTestingUtils {
public int currentParallelism() {
return 1;
}
+
+ public List<Long> getCompletedCheckpoints() {
+ return completedCheckpoints;
+ }
+
+ public List<Long> getAbortedCheckpoints() {
+ return abortedCheckpoints;
+ }
}
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/CoordinatorEventsExactlyOnceITCase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/CoordinatorEventsExactlyOnceITCase.java
index be6f07c..e3047d0 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/CoordinatorEventsExactlyOnceITCase.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/CoordinatorEventsExactlyOnceITCase.java
@@ -299,7 +299,7 @@ public class CoordinatorEventsExactlyOnceITCase extends TestLogger {
}
@Override
- public void checkpointComplete(long checkpointId) {}
+ public void notifyCheckpointComplete(long checkpointId) {}
@SuppressWarnings("CallToPrintStackTrace")
@Override
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/MockOperatorCoordinator.java b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/MockOperatorCoordinator.java
index f4e8444..8c2c6ff 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/MockOperatorCoordinator.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/MockOperatorCoordinator.java
@@ -54,7 +54,7 @@ public final class MockOperatorCoordinator implements OperatorCoordinator {
}
@Override
- public void checkpointComplete(long checkpointId) {
+ public void notifyCheckpointComplete(long checkpointId) {
throw new UnsupportedOperationException();
}
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorHolderTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorHolderTest.java
index 29ec382..2c34de6 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorHolderTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorHolderTest.java
@@ -532,7 +532,7 @@ public class OperatorCoordinatorHolderTest extends TestLogger {
public abstract void checkpointCoordinator(long checkpointId, CompletableFuture<byte[]> result) throws Exception;
@Override
- public void checkpointComplete(long checkpointId) {}
+ public void notifyCheckpointComplete(long checkpointId) {}
@Override
public void resetToCheckpoint(byte[] checkpointData) throws Exception {}
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/TestingOperatorCoordinator.java b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/TestingOperatorCoordinator.java
index e91bce3..e4d8b04 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/TestingOperatorCoordinator.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/TestingOperatorCoordinator.java
@@ -81,7 +81,7 @@ class TestingOperatorCoordinator implements OperatorCoordinator {
}
@Override
- public void checkpointComplete(long checkpointId) {
+ public void notifyCheckpointComplete(long checkpointId) {
lastCheckpointComplete.offer(checkpointId);
}
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorTest.java
index 3e48a93..6f6b5ba 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorTest.java
@@ -30,12 +30,14 @@ import org.apache.flink.runtime.source.event.SourceEventWrapper;
import org.junit.Test;
import java.io.IOException;
+import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
+import static org.apache.flink.core.testutils.CommonTestUtils.waitUtil;
import static org.apache.flink.runtime.source.coordinator.CoordinatorTestUtils.verifyAssignment;
import static org.apache.flink.runtime.source.coordinator.CoordinatorTestUtils.verifyException;
import static org.junit.Assert.assertEquals;
@@ -52,7 +54,7 @@ public class SourceCoordinatorTest extends SourceCoordinatorTestBase {
public void testThrowExceptionWhenNotStarted() {
// The following methods should only be invoked after the source coordinator has started.
String failureMessage = "Call should fail when source coordinator has not started yet.";
- verifyException(() -> sourceCoordinator.checkpointComplete(100L),
+ verifyException(() -> sourceCoordinator.notifyCheckpointComplete(100L),
failureMessage, "The coordinator has not started yet.");
verifyException(() -> sourceCoordinator.handleEventFromOperator(0, null),
failureMessage, "The coordinator has not started yet.");
@@ -209,7 +211,13 @@ public class SourceCoordinatorTest extends SourceCoordinatorTestBase {
checkpointFuture.get();
// Complete checkpoint 100.
- sourceCoordinator.checkpointComplete(100L);
+ sourceCoordinator.notifyCheckpointComplete(100L);
+ waitUtil(
+ () -> !enumerator.getSuccessfulCheckpoints().isEmpty(),
+ Duration.ofMillis(1000L),
+ "The enumerator failed to process the successful checkpoint "
+ + "before times out.");
+ assertEquals(100L, (long) enumerator.getSuccessfulCheckpoints().get(0));
// Fail reader 0.
sourceCoordinator.subtaskFailed(0, null);
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
index 46d4239..b18d85e 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
@@ -225,8 +225,9 @@ public class SourceOperator<OUT, SplitT extends SourceSplit>
@Override
public void snapshotState(StateSnapshotContext context) throws Exception {
- LOG.debug("Taking a snapshot for checkpoint {}", context.getCheckpointId());
- readerState.update(sourceReader.snapshotState());
+ long checkpointId = context.getCheckpointId();
+ LOG.debug("Taking a snapshot for checkpoint {}", checkpointId);
+ readerState.update(sourceReader.snapshotState(checkpointId));
}
@Override
@@ -241,6 +242,18 @@ public class SourceOperator<OUT, SplitT extends SourceSplit>
readerState = new SimpleVersionedListState<>(rawState, splitSerializer);
}
+ @Override
+ public void notifyCheckpointComplete(long checkpointId) throws Exception {
+ super.notifyCheckpointComplete(checkpointId);
+ sourceReader.notifyCheckpointComplete(checkpointId);
+ }
+
+ @Override
+ public void notifyCheckpointAborted(long checkpointId) throws Exception {
+ super.notifyCheckpointAborted(checkpointId);
+ sourceReader.notifyCheckpointAborted(checkpointId);
+ }
+
@SuppressWarnings("unchecked")
public void handleOperatorEvent(OperatorEvent event) {
if (event instanceof AddSplitEvent) {
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/collect/CollectSinkOperatorCoordinator.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/collect/CollectSinkOperatorCoordinator.java
index 695e4bd..1423415 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/collect/CollectSinkOperatorCoordinator.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/collect/CollectSinkOperatorCoordinator.java
@@ -199,7 +199,7 @@ public class CollectSinkOperatorCoordinator implements OperatorCoordinator, Coor
}
@Override
- public void checkpointComplete(long checkpointId) {
+ public void notifyCheckpointComplete(long checkpointId) {
}
@Override
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/SourceOperatorTest.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/SourceOperatorTest.java
index 3b381fd..65228f0 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/SourceOperatorTest.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/SourceOperatorTest.java
@@ -18,17 +18,21 @@
package org.apache.flink.streaming.api.operators;
+import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.state.OperatorStateStore;
import org.apache.flink.api.connector.source.SourceEvent;
import org.apache.flink.api.connector.source.mocks.MockSourceReader;
import org.apache.flink.api.connector.source.mocks.MockSourceSplit;
import org.apache.flink.api.connector.source.mocks.MockSourceSplitSerializer;
+import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.fs.CloseableRegistry;
import org.apache.flink.core.io.SimpleVersionedSerialization;
+import org.apache.flink.runtime.execution.Environment;
import org.apache.flink.runtime.operators.coordination.MockOperatorEventGateway;
import org.apache.flink.runtime.operators.coordination.OperatorEvent;
import org.apache.flink.runtime.operators.testutils.MockEnvironment;
import org.apache.flink.runtime.operators.testutils.MockEnvironmentBuilder;
+import org.apache.flink.runtime.operators.testutils.MockInputSplitProvider;
import org.apache.flink.runtime.source.event.AddSplitEvent;
import org.apache.flink.runtime.source.event.ReaderRegistrationEvent;
import org.apache.flink.runtime.source.event.SourceEventWrapper;
@@ -36,10 +40,15 @@ import org.apache.flink.runtime.state.AbstractStateBackend;
import org.apache.flink.runtime.state.StateInitializationContext;
import org.apache.flink.runtime.state.StateInitializationContextImpl;
import org.apache.flink.runtime.state.StateSnapshotContextSynchronousImpl;
+import org.apache.flink.runtime.state.TestTaskStateManager;
import org.apache.flink.runtime.state.memory.MemoryStateBackend;
import org.apache.flink.streaming.api.operators.source.TestingSourceOperator;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput;
+import org.apache.flink.streaming.runtime.tasks.SourceOperatorStreamTask;
+import org.apache.flink.streaming.runtime.tasks.StreamMockEnvironment;
+import org.apache.flink.streaming.util.MockOutput;
+import org.apache.flink.streaming.util.MockStreamConfig;
import org.apache.flink.util.CollectionUtil;
import org.junit.After;
@@ -47,6 +56,7 @@ import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -69,15 +79,24 @@ public class SourceOperatorTest {
private SourceOperator<Integer, MockSourceSplit> operator;
@Before
- public void setup() {
+ public void setup() throws Exception {
this.mockSourceReader = new MockSourceReader();
this.mockGateway = new MockOperatorEventGateway();
this.operator = new TestingSourceOperator<>(mockSourceReader, mockGateway, SUBTASK_INDEX);
+ Environment env = getTestingEnvironment();
+ this.operator.setup(
+ new SourceOperatorStreamTask<Integer>(env),
+ new MockStreamConfig(new Configuration(), 1),
+ new MockOutput<>(new ArrayList<>()));
+ this.operator.initializeState(new StreamTaskStateInitializerImpl(env, new MemoryStateBackend()));
}
@After
public void cleanUp() throws Exception {
operator.close();
+ if (((TestingSourceOperator<Integer>) operator).isReaderCreated()) {
+ assertTrue(mockSourceReader.isClosed());
+ }
}
@Test
@@ -104,7 +123,6 @@ public class SourceOperatorTest {
OperatorEvent operatorEvent = mockGateway.getEventsSent().get(0);
assertTrue(operatorEvent instanceof ReaderRegistrationEvent);
assertEquals(SUBTASK_INDEX, ((ReaderRegistrationEvent) operatorEvent).subtaskId());
- assertTrue(mockSourceReader.isClosed());
}
@Test
@@ -155,6 +173,26 @@ public class SourceOperatorTest {
assertEquals(Arrays.asList(MOCK_SPLIT, newSplit), splitsInState);
}
+ @Test
+ public void testNotifyCheckpointComplete() throws Exception {
+ StateInitializationContext stateContext = getStateContext();
+ operator.initializeState(stateContext);
+ operator.open();
+ operator.snapshotState(new StateSnapshotContextSynchronousImpl(100L, 100L));
+ operator.notifyCheckpointComplete(100L);
+ assertEquals(100L, (long) mockSourceReader.getCompletedCheckpoints().get(0));
+ }
+
+ @Test
+ public void testNotifyCheckpointAborted() throws Exception {
+ StateInitializationContext stateContext = getStateContext();
+ operator.initializeState(stateContext);
+ operator.open();
+ operator.snapshotState(new StateSnapshotContextSynchronousImpl(100L, 100L));
+ operator.notifyCheckpointAborted(100L);
+ assertEquals(100L, (long) mockSourceReader.getAbortedCheckpoints().get(0));
+ }
+
// ---------------- helper methods -------------------------
private StateInitializationContext getStateContext() throws Exception {
@@ -190,4 +228,15 @@ public class SourceOperatorTest {
return abstractStateBackend.createOperatorStateBackend(
env, "test-operator", Collections.emptyList(), cancelStreamRegistry);
}
+
+ private Environment getTestingEnvironment() {
+ return new StreamMockEnvironment(
+ new Configuration(),
+ new Configuration(),
+ new ExecutionConfig(),
+ 1L,
+ new MockInputSplitProvider(),
+ 1,
+ new TestTaskStateManager());
+ }
}
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/source/SourceOperatorEventTimeTest.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/source/SourceOperatorEventTimeTest.java
index c189001..d48ed13 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/source/SourceOperatorEventTimeTest.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/source/SourceOperatorEventTimeTest.java
@@ -239,7 +239,7 @@ public class SourceOperatorEventTimeTest {
}
@Override
- public List<MockSourceSplit> snapshotState() {
+ public List<MockSourceSplit> snapshotState(long checkpointId) {
throw new UnsupportedOperationException();
}
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/source/TestingSourceOperator.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/source/TestingSourceOperator.java
index a133ace..14b94eb 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/source/TestingSourceOperator.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/source/TestingSourceOperator.java
@@ -43,6 +43,8 @@ public class TestingSourceOperator<T> extends SourceOperator<T, MockSourceSplit
private final int subtaskIndex;
private final int parallelism;
+ private volatile boolean readerCreated;
+
public TestingSourceOperator(
SourceReader<T, MockSourceSplit> reader,
WatermarkStrategy<T> watermarkStrategy,
@@ -79,6 +81,13 @@ public class TestingSourceOperator<T> extends SourceOperator<T, MockSourceSplit
this.subtaskIndex = subtaskIndex;
this.parallelism = parallelism;
this.metrics = UnregisteredMetricGroups.createUnregisteredOperatorMetricGroup();
+ this.readerCreated = false;
+ }
+
+ @Override
+ public void open() throws Exception {
+ super.open();
+ readerCreated = true;
}
@Override
@@ -93,4 +102,8 @@ public class TestingSourceOperator<T> extends SourceOperator<T, MockSourceSplit
cfg.setAutoWatermarkInterval(100);
return cfg;
}
+
+ public boolean isReaderCreated() {
+ return readerCreated;
+ }
}
[flink] 20/21: [build] Add exclusions for added default methods in
SourceReader and SplitEnumerator interfaces.
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 9cb241958e8c7f0e13ba856b0cbeb1419d296cd3
Author: Stephan Ewen <se...@apache.org>
AuthorDate: Sun Nov 15 23:22:38 2020 +0100
[build] Add exclusions for added default methods in SourceReader and SplitEnumerator interfaces.
Default methods don't break compatibility, but it seems that the japicmp plugin does not
recognize this properly.
---
flink-core/pom.xml | 2 ++
1 file changed, 2 insertions(+)
diff --git a/flink-core/pom.xml b/flink-core/pom.xml
index 9a7b53e..79fdb44 100644
--- a/flink-core/pom.xml
+++ b/flink-core/pom.xml
@@ -189,6 +189,8 @@ under the License.
<exclude>org.apache.flink.api.connector.source.SourceReaderContext</exclude>
<exclude>org.apache.flink.api.connector.source.SplitEnumeratorContext</exclude>
<exclude>org.apache.flink.api.connector.source.Source</exclude>
+ <exclude>org.apache.flink.api.connector.source.SourceReader</exclude>
+ <exclude>org.apache.flink.api.connector.source.SplitEnumerator</exclude>
</excludes>
</parameter>
</configuration>
[flink] 10/21: [FLINK-19427][FLINK-19489][tests] Fix test
conditions for 'SplitFetcherTest.testNotifiesWhenGoingIdleConcurrent()'
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit dd2ac7af895ab117877a361fdafaeb19f8a65bd5
Author: Stephan Ewen <se...@apache.org>
AuthorDate: Mon Oct 12 13:43:57 2020 +0200
[FLINK-19427][FLINK-19489][tests] Fix test conditions for 'SplitFetcherTest.testNotifiesWhenGoingIdleConcurrent()'
The changed logic also fixes flaky thread shutdown logic as a side effect, because it no longer relies
on thread interrupting.
This closes #13593
---
.../source/reader/fetcher/SplitFetcherTest.java | 54 +++++++++++-----------
1 file changed, 26 insertions(+), 28 deletions(-)
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherTest.java b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherTest.java
index 5027e3f..5082ebf 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherTest.java
+++ b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherTest.java
@@ -120,16 +120,16 @@ public class SplitFetcherTest {
final SplitFetcher<Object, TestingSourceSplit> fetcher = createFetcherWithSplit(
"test-split", queue, new TestingSplitReader<>(finishedSplitFetch("test-split")));
- final QueueDrainerThread queueDrainer = new QueueDrainerThread(queue);
+ final QueueDrainerThread queueDrainer = new QueueDrainerThread(queue, fetcher, 1);
queueDrainer.start();
- try {
- fetcher.runOnce();
+ fetcher.runOnce();
- assertTrue(queue.getAvailabilityFuture().isDone());
- } finally {
- queueDrainer.shutdown();
- }
+ queueDrainer.sync();
+
+ // either we got the notification that the fetcher went idle after the queue was drained (thread finished)
+ // or the fetcher was already idle when the thread drained the queue (then we need no additional notification)
+ assertTrue(queue.getAvailabilityFuture().isDone() || queueDrainer.wasIdleWhenFinished());
}
@Test
@@ -139,18 +139,15 @@ public class SplitFetcherTest {
final SplitFetcher<Object, TestingSourceSplit> fetcher = createFetcherWithSplit(
"test-split", queue, new TestingSplitReader<>(finishedSplitFetch("test-split")));
- final QueueDrainerThread queueDrainer = new QueueDrainerThread(queue);
+ final QueueDrainerThread queueDrainer = new QueueDrainerThread(queue, fetcher, 1);
queueDrainer.start();
final CompletableFuture<?> future = queue.getAvailabilityFuture();
- try {
- fetcher.runOnce();
+ fetcher.runOnce();
+ assertTrue(future.isDone());
- assertTrue(future.isDone());
- } finally {
- queueDrainer.shutdown();
- }
+ queueDrainer.sync();
}
@Test
@@ -274,31 +271,32 @@ public class SplitFetcherTest {
private static final class QueueDrainerThread extends CheckedThread {
private final FutureCompletingBlockingQueue<?> queue;
- private volatile boolean running = true;
+ private final SplitFetcher<?, ?> fetcher;
+ private final int numFetchesToTake;
- QueueDrainerThread(FutureCompletingBlockingQueue<?> queue) {
+ private volatile boolean wasIdleWhenFinished;
+
+ QueueDrainerThread(FutureCompletingBlockingQueue<?> queue, SplitFetcher<?, ?> fetcher, int numFetchesToTake) {
super("Queue Drainer");
setPriority(Thread.MAX_PRIORITY);
this.queue = queue;
+ this.fetcher = fetcher;
+ this.numFetchesToTake = numFetchesToTake;
}
@Override
public void go() throws Exception {
- while (running) {
- try {
- queue.take();
- }
- catch (InterruptedException ignored) {
- Thread.currentThread().interrupt();
- // fall through the loop
- }
+ int remaining = numFetchesToTake;
+ while (remaining > 0) {
+ remaining--;
+ queue.take();
}
+
+ wasIdleWhenFinished = fetcher.isIdle();
}
- public void shutdown() throws Exception {
- running = false;
- interrupt();
- sync();
+ public boolean wasIdleWhenFinished() {
+ return wasIdleWhenFinished;
}
}
}
[flink] 15/21: [hotfix] Only close the SourceReader and
EventTimeLogic in the SourceOperator if they are not null.
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 3463da5056da44c8fc99404306c8a42ba170ac63
Author: Jiangjie (Becket) Qin <ji...@alibaba-inc.com>
AuthorDate: Sun Oct 25 18:12:34 2020 +0800
[hotfix] Only close the SourceReader and EventTimeLogic in the SourceOperator if they are not null.
---
.../org/apache/flink/streaming/api/operators/SourceOperator.java | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
index eaf5481..46d4239 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
@@ -189,8 +189,12 @@ public class SourceOperator<OUT, SplitT extends SourceSplit>
@Override
public void close() throws Exception {
- sourceReader.close();
- eventTimeLogic.stopPeriodicWatermarkEmits();
+ if (sourceReader != null) {
+ sourceReader.close();
+ }
+ if (eventTimeLogic != null) {
+ eventTimeLogic.stopPeriodicWatermarkEmits();
+ }
super.close();
}
[flink] 08/21: [FLINK-19492][core] Consolidate Source Events
between Source API and Split Reader API
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 301046ad36aeb2de0c97aeecc4fabc9dd2eb1520
Author: Stephan Ewen <se...@apache.org>
AuthorDate: Fri Oct 2 13:49:38 2020 +0200
[FLINK-19492][core] Consolidate Source Events between Source API and Split Reader API
---
.../base/source/reader/SourceReaderBase.java | 2 +-
.../source/reader/mocks/MockSplitEnumerator.java | 2 +-
.../connector}/source/event/NoMoreSplitsEvent.java | 2 +-
.../connector}/source/event/RequestSplitEvent.java | 15 ++++++++++-
.../source/lib/util/IteratorSourceEnumerator.java | 6 +++--
.../source/lib/util/IteratorSourceReader.java | 6 +++--
.../source/lib/util/NoSplitAvailableEvent.java | 31 ----------------------
.../source/lib/util/SplitRequestEvent.java | 31 ----------------------
8 files changed, 25 insertions(+), 70 deletions(-)
diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderBase.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderBase.java
index 97a6a95..1182cae 100644
--- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderBase.java
+++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderBase.java
@@ -24,8 +24,8 @@ import org.apache.flink.api.connector.source.SourceOutput;
import org.apache.flink.api.connector.source.SourceReader;
import org.apache.flink.api.connector.source.SourceReaderContext;
import org.apache.flink.api.connector.source.SourceSplit;
+import org.apache.flink.api.connector.source.event.NoMoreSplitsEvent;
import org.apache.flink.configuration.Configuration;
-import org.apache.flink.connector.base.source.event.NoMoreSplitsEvent;
import org.apache.flink.connector.base.source.reader.fetcher.SplitFetcherManager;
import org.apache.flink.connector.base.source.reader.splitreader.SplitReader;
import org.apache.flink.connector.base.source.reader.synchronization.FutureCompletingBlockingQueue;
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/MockSplitEnumerator.java b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/MockSplitEnumerator.java
index 2c84a70..8df3394 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/MockSplitEnumerator.java
+++ b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/MockSplitEnumerator.java
@@ -22,8 +22,8 @@ import org.apache.flink.api.connector.source.SourceEvent;
import org.apache.flink.api.connector.source.SplitEnumerator;
import org.apache.flink.api.connector.source.SplitEnumeratorContext;
import org.apache.flink.api.connector.source.SplitsAssignment;
+import org.apache.flink.api.connector.source.event.NoMoreSplitsEvent;
import org.apache.flink.api.connector.source.mocks.MockSourceSplit;
-import org.apache.flink.connector.base.source.event.NoMoreSplitsEvent;
import java.io.IOException;
import java.util.ArrayList;
diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/event/NoMoreSplitsEvent.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/event/NoMoreSplitsEvent.java
similarity index 96%
rename from flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/event/NoMoreSplitsEvent.java
rename to flink-core/src/main/java/org/apache/flink/api/connector/source/event/NoMoreSplitsEvent.java
index e2ca2e4..aa26808 100644
--- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/event/NoMoreSplitsEvent.java
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/event/NoMoreSplitsEvent.java
@@ -16,7 +16,7 @@
* limitations under the License.
*/
-package org.apache.flink.connector.base.source.event;
+package org.apache.flink.api.connector.source.event;
import org.apache.flink.api.connector.source.SourceEvent;
diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/event/RequestSplitEvent.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/event/RequestSplitEvent.java
similarity index 83%
rename from flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/event/RequestSplitEvent.java
rename to flink-core/src/main/java/org/apache/flink/api/connector/source/event/RequestSplitEvent.java
index 4bdb92a..9ff2293 100644
--- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/event/RequestSplitEvent.java
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/event/RequestSplitEvent.java
@@ -16,7 +16,7 @@
* limitations under the License.
*/
-package org.apache.flink.connector.base.source.event;
+package org.apache.flink.api.connector.source.event;
import org.apache.flink.api.connector.source.SourceEvent;
@@ -26,6 +26,9 @@ import java.util.Objects;
/**
* An event to request splits, sent typically from the Source Reader to the Source Enumerator.
+ *
+ * <p>This event optionally carries the hostname of the location where the reader runs, to support
+ * locality-aware work assignment.
*/
public final class RequestSplitEvent implements SourceEvent {
@@ -34,6 +37,16 @@ public final class RequestSplitEvent implements SourceEvent {
@Nullable
private final String hostName;
+ /**
+ * Creates a new {@code RequestSplitEvent} with no host information.
+ */
+ public RequestSplitEvent() {
+ this(null);
+ }
+
+ /**
+ * Creates a new {@code RequestSplitEvent} with a hostname.
+ */
public RequestSplitEvent(@Nullable String hostName) {
this.hostName = hostName;
}
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceEnumerator.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceEnumerator.java
index 3ee2597..91bc283 100644
--- a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceEnumerator.java
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceEnumerator.java
@@ -21,6 +21,8 @@ package org.apache.flink.api.connector.source.lib.util;
import org.apache.flink.api.connector.source.SourceEvent;
import org.apache.flink.api.connector.source.SplitEnumerator;
import org.apache.flink.api.connector.source.SplitEnumeratorContext;
+import org.apache.flink.api.connector.source.event.NoMoreSplitsEvent;
+import org.apache.flink.api.connector.source.event.RequestSplitEvent;
import org.apache.flink.util.FlinkRuntimeException;
import java.util.ArrayDeque;
@@ -56,7 +58,7 @@ public class IteratorSourceEnumerator<SplitT extends IteratorSourceSplit<?, ?>>
@Override
public void handleSourceEvent(int subtaskId, SourceEvent sourceEvent) {
- if (!(sourceEvent instanceof SplitRequestEvent)) {
+ if (!(sourceEvent instanceof RequestSplitEvent)) {
throw new FlinkRuntimeException("Unrecognized event: " + sourceEvent);
}
@@ -64,7 +66,7 @@ public class IteratorSourceEnumerator<SplitT extends IteratorSourceSplit<?, ?>>
if (nextSplit != null) {
context.assignSplit(nextSplit, subtaskId);
} else {
- context.sendEventToSourceReader(subtaskId, new NoSplitAvailableEvent());
+ context.sendEventToSourceReader(subtaskId, new NoMoreSplitsEvent());
}
}
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceReader.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceReader.java
index f9d7461..54ddb35 100644
--- a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceReader.java
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceReader.java
@@ -22,6 +22,8 @@ import org.apache.flink.api.connector.source.ReaderOutput;
import org.apache.flink.api.connector.source.SourceEvent;
import org.apache.flink.api.connector.source.SourceReader;
import org.apache.flink.api.connector.source.SourceReaderContext;
+import org.apache.flink.api.connector.source.event.NoMoreSplitsEvent;
+import org.apache.flink.api.connector.source.event.RequestSplitEvent;
import org.apache.flink.core.io.InputStatus;
import org.apache.flink.util.FlinkRuntimeException;
@@ -84,7 +86,7 @@ public class IteratorSourceReader<E, IterT extends Iterator<E>, SplitT extends I
public void start() {
// request a split only if we did not get one during restore
if (iterator == null) {
- context.sendSourceEventToCoordinator(new SplitRequestEvent());
+ context.sendSourceEventToCoordinator(new RequestSplitEvent());
}
}
@@ -133,7 +135,7 @@ public class IteratorSourceReader<E, IterT extends Iterator<E>, SplitT extends I
@Override
public void handleSourceEvents(SourceEvent sourceEvent) {
- if (sourceEvent instanceof NoSplitAvailableEvent) {
+ if (sourceEvent instanceof NoMoreSplitsEvent) {
// non-null queue signals splits were assigned, in this case no splits
remainingSplits = new ArrayDeque<>();
} else {
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/NoSplitAvailableEvent.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/NoSplitAvailableEvent.java
deleted file mode 100644
index 5a28565..0000000
--- a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/NoSplitAvailableEvent.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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.api.connector.source.lib.util;
-
-import org.apache.flink.api.connector.source.SourceEvent;
-import org.apache.flink.api.connector.source.SourceReader;
-import org.apache.flink.api.connector.source.SplitEnumerator;
-
-/**
- * A simple {@link SourceEvent} indicating that there is no split available for the reader (any more).
- * This event is typically sent from the {@link SplitEnumerator} to the {@link SourceReader}.
- */
-public final class NoSplitAvailableEvent implements SourceEvent {
- private static final long serialVersionUID = 1L;
-}
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/SplitRequestEvent.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/SplitRequestEvent.java
deleted file mode 100644
index 3e561b7..0000000
--- a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/SplitRequestEvent.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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.api.connector.source.lib.util;
-
-import org.apache.flink.api.connector.source.SourceEvent;
-import org.apache.flink.api.connector.source.SourceReader;
-import org.apache.flink.api.connector.source.SplitEnumerator;
-
-/**
- * A {@link SourceEvent} representing the request for a split, typically sent from the
- * {@link SourceReader} to the {@link SplitEnumerator}.
- */
-public final class SplitRequestEvent implements SourceEvent {
- private static final long serialVersionUID = 1L;
-}
[flink] 14/21: [hotfix] Replace finally block with JUnit After
method in SourceOperatorTest.
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 8ad5da9be6c1af7c089081c328ef6f344900e077
Author: Jiangjie (Becket) Qin <ji...@alibaba-inc.com>
AuthorDate: Sun Oct 25 18:04:19 2020 +0800
[hotfix] Replace finally block with JUnit After method in SourceOperatorTest.
---
.../api/operators/SourceOperatorTest.java | 83 +++++++++-------------
1 file changed, 34 insertions(+), 49 deletions(-)
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/SourceOperatorTest.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/SourceOperatorTest.java
index 8fbcf19..3b381fd 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/SourceOperatorTest.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/SourceOperatorTest.java
@@ -42,6 +42,7 @@ import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput;
import org.apache.flink.util.CollectionUtil;
+import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -74,6 +75,11 @@ public class SourceOperatorTest {
this.operator = new TestingSourceOperator<>(mockSourceReader, mockGateway, SUBTASK_INDEX);
}
+ @After
+ public void cleanUp() throws Exception {
+ operator.close();
+ }
+
@Test
public void testInitializeState() throws Exception {
StateInitializationContext stateContext = getStateContext();
@@ -88,22 +94,16 @@ public class SourceOperatorTest {
operator.initializeState(getStateContext());
// Open the operator.
operator.open();
- try {
- // The source reader should have been assigned a split.
- assertEquals(Collections.singletonList(MOCK_SPLIT), mockSourceReader.getAssignedSplits());
- // The source reader should have started.
- assertTrue(mockSourceReader.isStarted());
-
- // A ReaderRegistrationRequest should have been sent.
- assertEquals(1, mockGateway.getEventsSent().size());
- OperatorEvent operatorEvent = mockGateway.getEventsSent().get(0);
- assertTrue(operatorEvent instanceof ReaderRegistrationEvent);
- assertEquals(SUBTASK_INDEX, ((ReaderRegistrationEvent) operatorEvent).subtaskId());
-
- }
- finally {
- operator.close();
- }
+ // The source reader should have been assigned a split.
+ assertEquals(Collections.singletonList(MOCK_SPLIT), mockSourceReader.getAssignedSplits());
+ // The source reader should have started.
+ assertTrue(mockSourceReader.isStarted());
+
+ // A ReaderRegistrationRequest should have been sent.
+ assertEquals(1, mockGateway.getEventsSent().size());
+ OperatorEvent operatorEvent = mockGateway.getEventsSent().get(0);
+ assertTrue(operatorEvent instanceof ReaderRegistrationEvent);
+ assertEquals(SUBTASK_INDEX, ((ReaderRegistrationEvent) operatorEvent).subtaskId());
assertTrue(mockSourceReader.isClosed());
}
@@ -111,32 +111,22 @@ public class SourceOperatorTest {
public void testHandleAddSplitsEvent() throws Exception {
operator.initializeState(getStateContext());
operator.open();
- try {
- MockSourceSplit newSplit = new MockSourceSplit((2));
- operator.handleOperatorEvent(new AddSplitEvent<>(
- Collections.singletonList(newSplit), new MockSourceSplitSerializer()));
- // The source reader should have been assigned two splits.
- assertEquals(Arrays.asList(MOCK_SPLIT, newSplit), mockSourceReader.getAssignedSplits());
- }
- finally {
- operator.close();
- }
+ MockSourceSplit newSplit = new MockSourceSplit((2));
+ operator.handleOperatorEvent(new AddSplitEvent<>(
+ Collections.singletonList(newSplit), new MockSourceSplitSerializer()));
+ // The source reader should have been assigned two splits.
+ assertEquals(Arrays.asList(MOCK_SPLIT, newSplit), mockSourceReader.getAssignedSplits());
}
@Test
public void testHandleAddSourceEvent() throws Exception {
operator.initializeState(getStateContext());
operator.open();
- try {
- SourceEvent event = new SourceEvent() {
- };
- operator.handleOperatorEvent(new SourceEventWrapper(event));
- // The source reader should have been assigned two splits.
- assertEquals(Collections.singletonList(event), mockSourceReader.getReceivedSourceEvents());
- }
- finally {
- operator.close();
- }
+ SourceEvent event = new SourceEvent() {
+ };
+ operator.handleOperatorEvent(new SourceEventWrapper(event));
+ // The source reader should have been assigned two splits.
+ assertEquals(Collections.singletonList(event), mockSourceReader.getReceivedSourceEvents());
}
@Test
@@ -155,19 +145,14 @@ public class SourceOperatorTest {
StateInitializationContext stateContext = getStateContext();
operator.initializeState(stateContext);
operator.open();
- try {
- MockSourceSplit newSplit = new MockSourceSplit((2));
- operator.handleOperatorEvent(new AddSplitEvent<>(
- Collections.singletonList(newSplit), new MockSourceSplitSerializer()));
- operator.snapshotState(new StateSnapshotContextSynchronousImpl(100L, 100L));
-
- // Verify the splits in state.
- List<MockSourceSplit> splitsInState = CollectionUtil.iterableToList(operator.getReaderState().get());
- assertEquals(Arrays.asList(MOCK_SPLIT, newSplit), splitsInState);
- }
- finally {
- operator.close();
- }
+ MockSourceSplit newSplit = new MockSourceSplit((2));
+ operator.handleOperatorEvent(new AddSplitEvent<>(
+ Collections.singletonList(newSplit), new MockSourceSplitSerializer()));
+ operator.snapshotState(new StateSnapshotContextSynchronousImpl(100L, 100L));
+
+ // Verify the splits in state.
+ List<MockSourceSplit> splitsInState = CollectionUtil.iterableToList(operator.getReaderState().get());
+ assertEquals(Arrays.asList(MOCK_SPLIT, newSplit), splitsInState);
}
// ---------------- helper methods -------------------------
[flink] 13/21: [FLINK-18820] Emit MAX_WATERMARK at the end in
SourceOperator
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit b3ea6da49582af66a6182c27cfcfde772dc67dde
Author: sxnan <su...@gmail.com>
AuthorDate: Wed Aug 5 13:00:36 2020 +0800
[FLINK-18820] Emit MAX_WATERMARK at the end in SourceOperator
Starting from this commit we emit a MAX_WATERMARK when all records are
produced in SourceOperator or a stop with savepoint was triggered.
---
.../streaming/api/operators/SourceOperator.java | 13 ++++-
.../runtime/tasks/SourceOperatorStreamTask.java | 8 ++-
.../api/operators/SourceOperatorTest.java | 20 +++++++-
.../source/SourceOperatorEventTimeTest.java | 12 +++--
.../tasks/SourceOperatorStreamTaskTest.java | 57 ++++++++++++++++------
5 files changed, 87 insertions(+), 23 deletions(-)
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
index 742d7ce..eaf5481 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
@@ -42,6 +42,7 @@ import org.apache.flink.runtime.state.StateInitializationContext;
import org.apache.flink.runtime.state.StateSnapshotContext;
import org.apache.flink.streaming.api.operators.source.TimestampsAndWatermarks;
import org.apache.flink.streaming.api.operators.util.SimpleVersionedListState;
+import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput;
import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService;
import org.apache.flink.util.CollectionUtil;
@@ -201,13 +202,21 @@ public class SourceOperator<OUT, SplitT extends SourceSplit>
// short circuit the common case (every invocation except the first)
if (currentMainOutput != null) {
- return sourceReader.pollNext(currentMainOutput);
+ return pollNextRecord(output);
}
// this creates a batch or streaming output based on the runtime mode
currentMainOutput = eventTimeLogic.createMainOutput(output);
lastInvokedOutput = output;
- return sourceReader.pollNext(currentMainOutput);
+ return pollNextRecord(output);
+ }
+
+ private InputStatus pollNextRecord(DataOutput<OUT> output) throws Exception {
+ InputStatus inputStatus = sourceReader.pollNext(currentMainOutput);
+ if (inputStatus == InputStatus.END_OF_INPUT) {
+ output.emitWatermark(Watermark.MAX_WATERMARK);
+ }
+ return inputStatus;
}
@Override
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/SourceOperatorStreamTask.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/SourceOperatorStreamTask.java
index 47a1d73..c461dca 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/SourceOperatorStreamTask.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/SourceOperatorStreamTask.java
@@ -39,6 +39,7 @@ import static org.apache.flink.util.Preconditions.checkNotNull;
*/
@Internal
public class SourceOperatorStreamTask<T> extends StreamTask<T, SourceOperator<T, ?>> {
+ private AsyncDataOutputToOutput<T> output;
public SourceOperatorStreamTask(Environment env) throws Exception {
super(env);
@@ -47,7 +48,7 @@ public class SourceOperatorStreamTask<T> extends StreamTask<T, SourceOperator<T,
@Override
public void init() {
StreamTaskInput<T> input = new StreamTaskSourceInput<>(headOperator);
- DataOutput<T> output = new AsyncDataOutputToOutput<>(
+ output = new AsyncDataOutputToOutput<>(
operatorChain.getChainEntryPoint(),
getStreamStatusMaintainer());
@@ -57,6 +58,11 @@ public class SourceOperatorStreamTask<T> extends StreamTask<T, SourceOperator<T,
operatorChain);
}
+ @Override
+ protected void advanceToEndOfEventTime() {
+ output.emitWatermark(Watermark.MAX_WATERMARK);
+ }
+
/**
* Implementation of {@link DataOutput} that wraps a specific {@link Output}.
*/
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/SourceOperatorTest.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/SourceOperatorTest.java
index 44a5d44..8fbcf19 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/SourceOperatorTest.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/SourceOperatorTest.java
@@ -38,10 +38,13 @@ import org.apache.flink.runtime.state.StateInitializationContextImpl;
import org.apache.flink.runtime.state.StateSnapshotContextSynchronousImpl;
import org.apache.flink.runtime.state.memory.MemoryStateBackend;
import org.apache.flink.streaming.api.operators.source.TestingSourceOperator;
+import org.apache.flink.streaming.api.watermark.Watermark;
+import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput;
import org.apache.flink.util.CollectionUtil;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.Mockito;
import java.util.Arrays;
import java.util.Collections;
@@ -137,6 +140,17 @@ public class SourceOperatorTest {
}
@Test
+ public void testCloseWillSendMaxWatermark() throws Exception {
+ MockSourceSplit mockSplit = new MockSourceSplit(1, 0, 0);
+ operator.initializeState(getStateContext(mockSplit));
+ PushingAsyncDataInput.DataOutput<Integer> dataOutput =
+ Mockito.mock(PushingAsyncDataInput.DataOutput.class);
+ operator.open();
+ operator.emitNext(dataOutput);
+ Mockito.verify(dataOutput, Mockito.times(1)).emitWatermark(Watermark.MAX_WATERMARK);
+ }
+
+ @Test
public void testSnapshotState() throws Exception {
StateInitializationContext stateContext = getStateContext();
operator.initializeState(stateContext);
@@ -159,9 +173,13 @@ public class SourceOperatorTest {
// ---------------- helper methods -------------------------
private StateInitializationContext getStateContext() throws Exception {
+ return getStateContext(MOCK_SPLIT);
+ }
+
+ private StateInitializationContext getStateContext(MockSourceSplit mockSplit) throws Exception {
// Create a mock split.
byte[] serializedSplitWithVersion = SimpleVersionedSerialization
- .writeVersionAndSerialize(new MockSourceSplitSerializer(), MOCK_SPLIT);
+ .writeVersionAndSerialize(new MockSourceSplitSerializer(), mockSplit);
// Crate the state context.
OperatorStateStore operatorStateStore = createOperatorStateStore();
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/source/SourceOperatorEventTimeTest.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/source/SourceOperatorEventTimeTest.java
index 8d05336..c189001 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/source/SourceOperatorEventTimeTest.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/source/SourceOperatorEventTimeTest.java
@@ -68,7 +68,8 @@ public class SourceOperatorEventTimeTest {
assertThat(result, contains(
new Watermark(100L),
- new Watermark(120L)
+ new Watermark(120L),
+ Watermark.MAX_WATERMARK
));
}
@@ -86,7 +87,8 @@ public class SourceOperatorEventTimeTest {
assertThat(result, contains(
new Watermark(100L),
- new Watermark(120L)
+ new Watermark(120L),
+ Watermark.MAX_WATERMARK
));
}
@@ -111,7 +113,8 @@ public class SourceOperatorEventTimeTest {
assertThat(result, contains(
new Watermark(100L),
new Watermark(150L),
- new Watermark(200L)
+ new Watermark(200L),
+ Watermark.MAX_WATERMARK
));
}
@@ -136,7 +139,8 @@ public class SourceOperatorEventTimeTest {
assertThat(result, contains(
new Watermark(100L),
new Watermark(150L),
- new Watermark(200L)
+ new Watermark(200L),
+ Watermark.MAX_WATERMARK
));
}
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/SourceOperatorStreamTaskTest.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/SourceOperatorStreamTaskTest.java
index 56475ed..189bdff 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/SourceOperatorStreamTaskTest.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/SourceOperatorStreamTaskTest.java
@@ -29,12 +29,15 @@ import org.apache.flink.api.connector.source.mocks.MockSourceSplitSerializer;
import org.apache.flink.core.testutils.OneShotLatch;
import org.apache.flink.runtime.checkpoint.CheckpointMetaData;
import org.apache.flink.runtime.checkpoint.CheckpointOptions;
+import org.apache.flink.runtime.checkpoint.CheckpointType;
import org.apache.flink.runtime.checkpoint.TaskStateSnapshot;
import org.apache.flink.runtime.io.network.api.CheckpointBarrier;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.source.event.AddSplitEvent;
+import org.apache.flink.runtime.state.CheckpointStorageLocationReference;
import org.apache.flink.streaming.api.operators.SourceOperator;
import org.apache.flink.streaming.api.operators.SourceOperatorFactory;
+import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.util.SerializedValue;
@@ -78,6 +81,24 @@ public class SourceOperatorStreamTaskTest {
IntStream.range(NUM_RECORDS, NUM_RECORDS * 2));
}
+ @Test
+ public void testSnapshotAndAdvanceToEndOfEventTime() throws Exception {
+ final int checkpointId = 1;
+ try (StreamTaskMailboxTestHarness<Integer> testHarness = createTestHarness(checkpointId, null)) {
+ getAndMaybeAssignSplit(testHarness);
+
+ final CheckpointOptions checkpointOptions = new CheckpointOptions(CheckpointType.SYNC_SAVEPOINT,
+ CheckpointStorageLocationReference.getDefault());
+ triggerCheckpointWaitForFinish(testHarness, checkpointId, checkpointOptions);
+
+ Queue<Object> expectedOutput = new LinkedList<>();
+ expectedOutput.add(Watermark.MAX_WATERMARK);
+ expectedOutput.add(new CheckpointBarrier(checkpointId, checkpointId, checkpointOptions));
+
+ assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput());
+ }
+ }
+
private TaskStateSnapshot executeAndWaitForCheckpoint(
long checkpointId,
TaskStateSnapshot initialSnapshot,
@@ -91,22 +112,8 @@ public class SourceOperatorStreamTaskTest {
// Process all the records.
processUntil(testHarness, () -> !testHarness.getStreamTask().inputProcessor.getAvailableFuture().isDone());
- // Trigger a checkpoint.
CheckpointOptions checkpointOptions = CheckpointOptions.forCheckpointWithDefaultLocation();
- OneShotLatch waitForAcknowledgeLatch = new OneShotLatch();
- testHarness.taskStateManager.setWaitForReportLatch(waitForAcknowledgeLatch);
- CheckpointMetaData checkpointMetaData = new CheckpointMetaData(checkpointId, checkpointId);
- Future<Boolean> checkpointFuture =
- testHarness
- .getStreamTask()
- .triggerCheckpointAsync(checkpointMetaData, checkpointOptions, false);
-
- // Wait until the checkpoint finishes.
- // We have to mark the source reader as available here, otherwise the runMailboxStep() call after
- // checkpiont is completed will block.
- getSourceReaderFromTask(testHarness).markAvailable();
- processUntil(testHarness, checkpointFuture::isDone);
- waitForAcknowledgeLatch.await();
+ triggerCheckpointWaitForFinish(testHarness, checkpointId, checkpointOptions);
// Build expected output to verify the results
Queue<Object> expectedOutput = new LinkedList<>();
@@ -121,6 +128,26 @@ public class SourceOperatorStreamTaskTest {
}
}
+ private void triggerCheckpointWaitForFinish(StreamTaskMailboxTestHarness<Integer> testHarness,
+ long checkpointId,
+ CheckpointOptions checkpointOptions) throws Exception {
+ // Trigger a checkpoint.
+ OneShotLatch waitForAcknowledgeLatch = new OneShotLatch();
+ testHarness.taskStateManager.setWaitForReportLatch(waitForAcknowledgeLatch);
+ CheckpointMetaData checkpointMetaData = new CheckpointMetaData(checkpointId, checkpointId);
+ Future<Boolean> checkpointFuture =
+ testHarness
+ .getStreamTask()
+ .triggerCheckpointAsync(checkpointMetaData, checkpointOptions, true);
+
+ // Wait until the checkpoint finishes.
+ // We have to mark the source reader as available here, otherwise the runMailboxStep() call after
+ // checkpiont is completed will block.
+ getSourceReaderFromTask(testHarness).markAvailable();
+ processUntil(testHarness, checkpointFuture::isDone);
+ waitForAcknowledgeLatch.await();
+ }
+
private void processUntil(StreamTaskMailboxTestHarness testHarness, Supplier<Boolean> condition) throws Exception {
do {
testHarness.getStreamTask().runMailboxStep();
[flink] 21/21: [refactor][DataStream API] Make
DataStreamUtils.collect() methods more flexible.
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 1a8ff89466b1f13e1f624c4046ed7f5db8212e6d
Author: Stephan Ewen <se...@apache.org>
AuthorDate: Wed Sep 2 15:23:27 2020 +0200
[refactor][DataStream API] Make DataStreamUtils.collect() methods more flexible.
This supports simple ways of pulling bounded streams to the client, as well as a defined number of
elements from an unbounded stream.
---
.../streaming/api/datastream/DataStreamUtils.java | 136 +++++++++++++++++++--
1 file changed, 124 insertions(+), 12 deletions(-)
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStreamUtils.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStreamUtils.java
index a4f1560..a1acc9b 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStreamUtils.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStreamUtils.java
@@ -31,9 +31,14 @@ import org.apache.flink.streaming.api.operators.collect.CollectStreamSink;
import org.apache.flink.streaming.api.transformations.PartitionTransformation;
import org.apache.flink.streaming.runtime.partitioner.ForwardPartitioner;
+import java.util.ArrayList;
import java.util.Iterator;
+import java.util.List;
import java.util.UUID;
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
/**
* A collection of utilities for {@link DataStream DataStreams}.
*/
@@ -41,34 +46,124 @@ import java.util.UUID;
public final class DataStreamUtils {
/**
- * Returns an iterator to iterate over the elements of the DataStream.
- * @return The iterator
+ * Triggers the distributed execution of the streaming dataflow and returns an iterator over the elements
+ * of the given DataStream.
+ *
+ * <p>The DataStream application is executed in the regular distributed manner on the target environment,
+ * and the events from the stream are polled back to this application process and thread through
+ * Flink's REST API.
*/
public static <OUT> Iterator<OUT> collect(DataStream<OUT> stream) {
+ return collect(stream, "Data Stream Collect");
+ }
+
+ /**
+ * Triggers the distributed execution of the streaming dataflow and returns an iterator over the elements
+ * of the given DataStream.
+ *
+ * <p>The DataStream application is executed in the regular distributed manner on the target environment,
+ * and the events from the stream are polled back to this application process and thread through
+ * Flink's REST API.
+ */
+ public static <OUT> Iterator<OUT> collect(DataStream<OUT> stream, String executionJobName) {
+ try {
+ return collectWithClient(stream, executionJobName).iterator;
+ } catch (Exception e) {
+ // this "wrap as unchecked" step is here only to preserve the exception signature
+ // backwards compatible.
+ throw new RuntimeException("Failed to execute data stream", e);
+ }
+ }
+
+ /**
+ * Starts the execution of the program and returns an iterator to read the result of the
+ * given data stream, plus a {@link JobClient} to interact with the application execution.
+ */
+ public static <OUT> ClientAndIterator<OUT> collectWithClient(
+ DataStream<OUT> stream,
+ String jobExecutionName) throws Exception {
+
TypeSerializer<OUT> serializer = stream.getType().createSerializer(
- stream.getExecutionEnvironment().getConfig());
+ stream.getExecutionEnvironment().getConfig());
String accumulatorName = "dataStreamCollect_" + UUID.randomUUID().toString();
+ StreamExecutionEnvironment env = stream.getExecutionEnvironment();
CollectSinkOperatorFactory<OUT> factory = new CollectSinkOperatorFactory<>(serializer, accumulatorName);
CollectSinkOperator<OUT> operator = (CollectSinkOperator<OUT>) factory.getOperator();
CollectResultIterator<OUT> iterator = new CollectResultIterator<>(
- operator.getOperatorIdFuture(), serializer, accumulatorName);
+ operator.getOperatorIdFuture(), serializer, accumulatorName);
CollectStreamSink<OUT> sink = new CollectStreamSink<>(stream, factory);
sink.name("Data stream collect sink");
-
- StreamExecutionEnvironment env = stream.getExecutionEnvironment();
env.addOperator(sink.getTransformation());
- try {
- JobClient jobClient = env.executeAsync("Data Stream Collect");
- iterator.setJobClient(jobClient);
- } catch (Exception e) {
- throw new RuntimeException("Failed to execute data stream", e);
+ final JobClient jobClient = env.executeAsync(jobExecutionName);
+ iterator.setJobClient(jobClient);
+
+ return new ClientAndIterator<>(jobClient, iterator);
+ }
+
+ /**
+ * Collects contents the given DataStream into a list, assuming that the stream is a bounded stream.
+ *
+ * <p>This method blocks until the job execution is complete. By the time the method returns, the
+ * job will have reached its FINISHED status.
+ *
+ * <p>Note that if the stream is unbounded, this method will never return and might fail with an
+ * Out-of-Memory Error because it attempts to collect an infinite stream into a list.
+ *
+ * @throws Exception Exceptions that occur during the execution are forwarded.
+ */
+ public static <E> List<E> collectBoundedStream(DataStream<E> stream, String jobName) throws Exception {
+ final ArrayList<E> list = new ArrayList<>();
+ final Iterator<E> iter = collectWithClient(stream, jobName).iterator;
+ while (iter.hasNext()) {
+ list.add(iter.next());
}
+ list.trimToSize();
+ return list;
+ }
+
+ /**
+ * Triggers execution of the DataStream application and collects the given number of records from the stream.
+ * After the records are received, the execution is canceled.
+ */
+ public static <E> List<E> collectUnboundedStream(DataStream<E> stream, int numElements, String jobName) throws Exception {
+ final ClientAndIterator<E> clientAndIterator = collectWithClient(stream, jobName);
+ final List<E> result = collectRecordsFromUnboundedStream(clientAndIterator, numElements);
- return iterator;
+ // cancel the job not that we have received enough elements
+ clientAndIterator.client.cancel().get();
+
+ return result;
}
+ public static <E> List<E> collectRecordsFromUnboundedStream(
+ final ClientAndIterator<E> client,
+ final int numElements) {
+
+ checkNotNull(client, "client");
+ checkArgument(numElements > 0, "numElement must be > 0");
+
+ final ArrayList<E> result = new ArrayList<>(numElements);
+ final Iterator<E> iterator = client.iterator;
+
+ while (iterator.hasNext()) {
+ result.add(iterator.next());
+ if (result.size() == numElements) {
+ return result;
+ }
+ }
+
+ throw new IllegalArgumentException(String.format(
+ "The stream ended before reaching the requested %d records. Only %d records were received.",
+ numElements, result.size()));
+ }
+
+ // ------------------------------------------------------------------------
+ // Deriving a KeyedStream from a stream already partitioned by key
+ // without a shuffle
+ // ------------------------------------------------------------------------
+
/**
* Reinterprets the given {@link DataStream} as a {@link KeyedStream}, which extracts keys with the given
* {@link KeySelector}.
@@ -130,4 +225,21 @@ public final class DataStreamUtils {
* Private constructor to prevent instantiation.
*/
private DataStreamUtils() {}
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * A pair of an {@link Iterator} to receive results from a streaming application and a
+ * {@link JobClient} to interact with the program.
+ */
+ public static final class ClientAndIterator<E> {
+
+ public final JobClient client;
+ public final Iterator<E> iterator;
+
+ ClientAndIterator(JobClient client, Iterator<E> iterator) {
+ this.client = checkNotNull(client);
+ this.iterator = checkNotNull(iterator);
+ }
+ }
}
[flink] 01/21: [backport] Backport some core changes that were part
of the FLIP-27 File Source commit
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 91903351ad1c8e13bbe2cfe5d8383ad915b5887f
Author: Stephan Ewen <se...@apache.org>
AuthorDate: Mon Jun 29 11:00:59 2020 +0200
[backport] Backport some core changes that were part of the FLIP-27 File Source commit
---
.../SingleThreadMultiplexSourceReaderBase.java | 63 ++++++++++++++++++----
.../source/reader/mocks/TestingReaderContext.java | 4 +-
.../streaming/api/operators/SourceOperator.java | 5 +-
3 files changed, 59 insertions(+), 13 deletions(-)
diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SingleThreadMultiplexSourceReaderBase.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SingleThreadMultiplexSourceReaderBase.java
index ab87db0..f5806d1 100644
--- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SingleThreadMultiplexSourceReaderBase.java
+++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SingleThreadMultiplexSourceReaderBase.java
@@ -26,24 +26,67 @@ import org.apache.flink.connector.base.source.reader.fetcher.SingleThreadFetcher
import org.apache.flink.connector.base.source.reader.splitreader.SplitReader;
import org.apache.flink.connector.base.source.reader.synchronization.FutureCompletingBlockingQueue;
+import java.util.Collection;
import java.util.function.Supplier;
/**
- * A abstract {@link SourceReader} implementation that assign all the splits to a single thread to consume.
- * @param <E>
- * @param <T>
- * @param <SplitT>
- * @param <SplitStateT>
+ * A base for {@link SourceReader}s that read splits with one thread using one {@link SplitReader}.
+ * The splits can be read either one after the other (like in a file source) or concurrently by changing
+ * the subscription in the split reader (like in the Kafka Source).
+ *
+ * <p>To implement a source reader based on this class, implementors need to supply the following:
+ * <ul>
+ * <li>A {@link SplitReader}, which connects to the source and reads/polls data. The split reader
+ * gets notified whenever there is a new split. The split reader would read files, contain a
+ * Kafka or other source client, etc.</li>
+ * <li>A {@link RecordEmitter} that takes a record from the Split Reader and updates the checkpointing
+ * state and converts it into the final form. For example for Kafka, the Record Emitter takes a
+ * {@code ConsumerRecord}, puts the offset information into state, transforms the records with the
+ * deserializers into the final type, and emits the record.</li>
+ * <li>The class must override the methods to convert back and forth between the immutable splits
+ * ({@code SplitT}) and the mutable split state representation ({@code SplitStateT}).</li>
+ * <li>Finally, the reader must decide what to do when it starts ({@link #start()}) or when a split is
+ * finished ({@link #onSplitFinished(Collection)}).</li>
+ * </ul>
+ *
+ * @param <E> The type of the records (the raw type that typically contains checkpointing information).
+ * @param <T> The final type of the records emitted by the source.
+ * @param <SplitT> The type of the splits processed by the source.
+ * @param <SplitStateT> The type of the mutable state per split.
*/
public abstract class SingleThreadMultiplexSourceReaderBase<E, T, SplitT extends SourceSplit, SplitStateT>
extends SourceReaderBase<E, T, SplitT, SplitStateT> {
+ /**
+ * The primary constructor for the source reader.
+ *
+ * <p>The reader will use a handover queue sized as configured via
+ * {@link SourceReaderOptions#ELEMENT_QUEUE_CAPACITY}.
+ */
+ public SingleThreadMultiplexSourceReaderBase(
+ Supplier<SplitReader<E, SplitT>> splitReaderSupplier,
+ RecordEmitter<E, T, SplitStateT> recordEmitter,
+ Configuration config,
+ SourceReaderContext context) {
+ this(
+ new FutureCompletingBlockingQueue<>(config.getInteger(SourceReaderOptions.ELEMENT_QUEUE_CAPACITY)),
+ splitReaderSupplier,
+ recordEmitter,
+ config,
+ context);
+ }
+
+ /**
+ * This constructor behaves like
+ * {@link #SingleThreadMultiplexSourceReaderBase(Supplier, RecordEmitter, Configuration, SourceReaderContext)},
+ * but accepts a specific {@link FutureCompletingBlockingQueue}.
+ */
public SingleThreadMultiplexSourceReaderBase(
- FutureCompletingBlockingQueue<RecordsWithSplitIds<E>> elementsQueue,
- Supplier<SplitReader<E, SplitT>> splitReaderSupplier,
- RecordEmitter<E, T, SplitStateT> recordEmitter,
- Configuration config,
- SourceReaderContext context) {
+ FutureCompletingBlockingQueue<RecordsWithSplitIds<E>> elementsQueue,
+ Supplier<SplitReader<E, SplitT>> splitReaderSupplier,
+ RecordEmitter<E, T, SplitStateT> recordEmitter,
+ Configuration config,
+ SourceReaderContext context) {
super(
elementsQueue,
new SingleThreadFetcherManager<>(elementsQueue, splitReaderSupplier),
diff --git a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingReaderContext.java b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingReaderContext.java
index 02faf1f..5bb9b59 100644
--- a/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingReaderContext.java
+++ b/flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/mocks/TestingReaderContext.java
@@ -64,7 +64,9 @@ public class TestingReaderContext implements SourceReaderContext {
}
@Override
- public void sendSourceEventToCoordinator(SourceEvent sourceEvent) {}
+ public void sendSourceEventToCoordinator(SourceEvent sourceEvent) {
+ sentEvents.add(sourceEvent);
+ }
// ------------------------------------------------------------------------
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
index 1af572c..05b3216 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
@@ -173,11 +173,12 @@ public class SourceOperator<OUT, SplitT extends SourceSplit>
sourceReader.addSplits(splits);
}
- // Start the reader.
- sourceReader.start();
// Register the reader to the coordinator.
registerReader();
+ // Start the reader after registration, sending messages in start is allowed.
+ sourceReader.start();
+
eventTimeLogic.startPeriodicWatermarkEmits();
}
[flink] 19/21: [FLINK-19384][core] Add common permissive exception
signatures to all methods of Source.
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit abe4c4b6995cf5cefcc2384937d25f62dd6d492c
Author: Stephan Ewen <se...@apache.org>
AuthorDate: Wed Nov 4 15:48:19 2020 +0100
[FLINK-19384][core] Add common permissive exception signatures to all methods of Source.
This makes the exception signatures consistent within the class and with the exception philisophy
in other API classes, like transformation functions: Allow users to simply throw or forward any
type of checked exceptions.
---
flink-core/pom.xml | 3 ++-
.../org/apache/flink/api/connector/source/Source.java | 16 ++++++++++++----
.../operators/coordination/OperatorCoordinator.java | 2 +-
.../coordination/OperatorCoordinatorHolder.java | 4 ++--
.../coordination/RecreateOnResetOperatorCoordinator.java | 9 +++++----
.../runtime/source/coordinator/SourceCoordinator.java | 2 +-
.../source/coordinator/SourceCoordinatorProvider.java | 2 +-
.../RecreateOnResetOperatorCoordinatorTest.java | 3 ++-
.../coordinator/SourceCoordinatorProviderTest.java | 2 +-
.../source/coordinator/SourceCoordinatorTestBase.java | 5 +++--
.../flink/streaming/api/operators/SourceOperator.java | 6 +++---
.../streaming/api/operators/SourceOperatorFactory.java | 10 +++++-----
12 files changed, 38 insertions(+), 26 deletions(-)
diff --git a/flink-core/pom.xml b/flink-core/pom.xml
index 9fb9448..9a7b53e 100644
--- a/flink-core/pom.xml
+++ b/flink-core/pom.xml
@@ -185,9 +185,10 @@ under the License.
<exclude>org.apache.flink.api.common.typeinfo.TypeHint</exclude>
<exclude>org.apache.flink.api.java.typeutils.TypeInfoParser</exclude>
- <!-- additions to Source API context interfaces -->
+ <!-- additions to Source API context interfaces and exception signatures -->
<exclude>org.apache.flink.api.connector.source.SourceReaderContext</exclude>
<exclude>org.apache.flink.api.connector.source.SplitEnumeratorContext</exclude>
+ <exclude>org.apache.flink.api.connector.source.Source</exclude>
</excludes>
</parameter>
</configuration>
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/Source.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/Source.java
index fe81db8..38a2578 100644
--- a/flink-core/src/main/java/org/apache/flink/api/connector/source/Source.java
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/Source.java
@@ -21,7 +21,6 @@ package org.apache.flink.api.connector.source;
import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.core.io.SimpleVersionedSerializer;
-import java.io.IOException;
import java.io.Serializable;
/**
@@ -49,16 +48,22 @@ public interface Source<T, SplitT extends SourceSplit, EnumChkT> extends Seriali
*
* @param readerContext The {@link SourceReaderContext context} for the source reader.
* @return A new SourceReader.
+ *
+ * @throws Exception The implementor is free to forward all exceptions directly.
+ * Exceptions thrown from this method cause task failure/recovery.
*/
- SourceReader<T, SplitT> createReader(SourceReaderContext readerContext);
+ SourceReader<T, SplitT> createReader(SourceReaderContext readerContext) throws Exception;
/**
* Creates a new SplitEnumerator for this source, starting a new input.
*
* @param enumContext The {@link SplitEnumeratorContext context} for the split enumerator.
* @return A new SplitEnumerator.
+ *
+ * @throws Exception The implementor is free to forward all exceptions directly.
+ * * Exceptions thrown from this method cause JobManager failure/recovery.
*/
- SplitEnumerator<SplitT, EnumChkT> createEnumerator(SplitEnumeratorContext<SplitT> enumContext);
+ SplitEnumerator<SplitT, EnumChkT> createEnumerator(SplitEnumeratorContext<SplitT> enumContext) throws Exception;
/**
* Restores an enumerator from a checkpoint.
@@ -66,10 +71,13 @@ public interface Source<T, SplitT extends SourceSplit, EnumChkT> extends Seriali
* @param enumContext The {@link SplitEnumeratorContext context} for the restored split enumerator.
* @param checkpoint The checkpoint to restore the SplitEnumerator from.
* @return A SplitEnumerator restored from the given checkpoint.
+ *
+ * @throws Exception The implementor is free to forward all exceptions directly.
+ * * Exceptions thrown from this method cause JobManager failure/recovery.
*/
SplitEnumerator<SplitT, EnumChkT> restoreEnumerator(
SplitEnumeratorContext<SplitT> enumContext,
- EnumChkT checkpoint) throws IOException;
+ EnumChkT checkpoint) throws Exception;
// ------------------------------------------------------------------------
// serializers for the metadata
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinator.java
index bc280f0..b40e4f6 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinator.java
@@ -197,6 +197,6 @@ public interface OperatorCoordinator extends CheckpointListener, AutoCloseable {
/**
* Creates the {@code OperatorCoordinator}, using the given context.
*/
- OperatorCoordinator create(Context context);
+ OperatorCoordinator create(Context context) throws Exception;
}
}
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorHolder.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorHolder.java
index 9819754..a4c43a8 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorHolder.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/OperatorCoordinatorHolder.java
@@ -302,7 +302,7 @@ public class OperatorCoordinatorHolder implements OperatorCoordinator, OperatorC
public static OperatorCoordinatorHolder create(
SerializedValue<OperatorCoordinator.Provider> serializedProvider,
ExecutionJobVertex jobVertex,
- ClassLoader classLoader) throws IOException, ClassNotFoundException {
+ ClassLoader classLoader) throws Exception {
try (TemporaryClassLoaderContext ignored = TemporaryClassLoaderContext.of(classLoader)) {
final OperatorCoordinator.Provider provider = serializedProvider.deserializeValue(classLoader);
@@ -331,7 +331,7 @@ public class OperatorCoordinatorHolder implements OperatorCoordinator, OperatorC
final BiFunction<SerializedValue<OperatorEvent>, Integer, CompletableFuture<Acknowledge>> eventSender,
final String operatorName,
final int operatorParallelism,
- final int operatorMaxParallelism) {
+ final int operatorMaxParallelism) throws Exception {
final OperatorEventValve valve = new OperatorEventValve(eventSender);
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/RecreateOnResetOperatorCoordinator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/RecreateOnResetOperatorCoordinator.java
index c19997c..03861b1 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/RecreateOnResetOperatorCoordinator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/coordination/RecreateOnResetOperatorCoordinator.java
@@ -23,6 +23,7 @@ import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.messages.Acknowledge;
import javax.annotation.Nullable;
+
import java.util.concurrent.CompletableFuture;
/**
@@ -39,7 +40,7 @@ public class RecreateOnResetOperatorCoordinator implements OperatorCoordinator {
private RecreateOnResetOperatorCoordinator(
QuiesceableContext context,
- Provider provider) {
+ Provider provider) throws Exception {
this.quiesceableContext = context;
this.provider = provider;
this.coordinator = provider.getCoordinator(context);
@@ -107,7 +108,7 @@ public class RecreateOnResetOperatorCoordinator implements OperatorCoordinator {
// ---------------------
- public static abstract class Provider implements OperatorCoordinator.Provider {
+ public abstract static class Provider implements OperatorCoordinator.Provider {
private static final long serialVersionUID = 3002837631612629071L;
private final OperatorID operatorID;
@@ -121,12 +122,12 @@ public class RecreateOnResetOperatorCoordinator implements OperatorCoordinator {
}
@Override
- public OperatorCoordinator create(Context context) {
+ public OperatorCoordinator create(Context context) throws Exception {
QuiesceableContext quiesceableContext = new QuiesceableContext(context);
return new RecreateOnResetOperatorCoordinator(quiesceableContext, this);
}
- protected abstract OperatorCoordinator getCoordinator(OperatorCoordinator.Context context);
+ protected abstract OperatorCoordinator getCoordinator(OperatorCoordinator.Context context) throws Exception;
}
// ----------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/source/coordinator/SourceCoordinator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/source/coordinator/SourceCoordinator.java
index a22a239..3e3af76 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/source/coordinator/SourceCoordinator.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/source/coordinator/SourceCoordinator.java
@@ -89,7 +89,7 @@ public class SourceCoordinator<SplitT extends SourceSplit, EnumChkT> implements
String operatorName,
ExecutorService coordinatorExecutor,
Source<?, SplitT, EnumChkT> source,
- SourceCoordinatorContext<SplitT> context) {
+ SourceCoordinatorContext<SplitT> context) throws Exception {
this.operatorName = operatorName;
this.coordinatorExecutor = coordinatorExecutor;
this.source = source;
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorProvider.java b/flink-runtime/src/main/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorProvider.java
index 44d7671..0304a88 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorProvider.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorProvider.java
@@ -64,7 +64,7 @@ public class SourceCoordinatorProvider<SplitT extends SourceSplit> extends Recre
}
@Override
- public OperatorCoordinator getCoordinator(OperatorCoordinator.Context context) {
+ public OperatorCoordinator getCoordinator(OperatorCoordinator.Context context) throws Exception {
final String coordinatorThreadName = "SourceCoordinator-" + operatorName;
CoordinatorExecutorThreadFactory coordinatorThreadFactory =
new CoordinatorExecutorThreadFactory(coordinatorThreadName);
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/RecreateOnResetOperatorCoordinatorTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/RecreateOnResetOperatorCoordinatorTest.java
index f4298ce..7ff487f 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/RecreateOnResetOperatorCoordinatorTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/RecreateOnResetOperatorCoordinatorTest.java
@@ -19,6 +19,7 @@
package org.apache.flink.runtime.operators.coordination;
import org.apache.flink.runtime.jobgraph.OperatorID;
+
import org.junit.Test;
import java.util.Collections;
@@ -90,7 +91,7 @@ public class RecreateOnResetOperatorCoordinatorTest {
private RecreateOnResetOperatorCoordinator createCoordinator(
TestingCoordinatorProvider provider,
- OperatorCoordinator.Context context) {
+ OperatorCoordinator.Context context) throws Exception {
return (RecreateOnResetOperatorCoordinator) provider.create(context);
}
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorProviderTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorProviderTest.java
index c86981c..3e736bb 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorProviderTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorProviderTest.java
@@ -55,7 +55,7 @@ public class SourceCoordinatorProviderTest {
}
@Test
- public void testCreate() {
+ public void testCreate() throws Exception {
OperatorCoordinator coordinator =
provider.create(new MockOperatorCoordinatorContext(OPERATOR_ID, NUM_SPLITS));
assertTrue(coordinator instanceof RecreateOnResetOperatorCoordinator);
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorTestBase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorTestBase.java
index a14c868..a46b1ad 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorTestBase.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorTestBase.java
@@ -52,7 +52,7 @@ public abstract class SourceCoordinatorTestBase {
protected MockSplitEnumerator enumerator;
@Before
- public void setup() {
+ public void setup() throws Exception {
operatorCoordinatorContext = new MockOperatorCoordinatorContext(TEST_OPERATOR_ID, NUM_SUBTASKS);
splitSplitAssignmentTracker = new SplitAssignmentTracker<>();
String coordinatorThreadName = TEST_OPERATOR_ID.toHexString();
@@ -80,9 +80,10 @@ public abstract class SourceCoordinatorTestBase {
// --------------------------
- protected SourceCoordinator getNewSourceCoordinator() {
+ protected SourceCoordinator getNewSourceCoordinator() throws Exception {
Source<Integer, MockSourceSplit, Set<MockSourceSplit>> mockSource =
new MockSource(Boundedness.BOUNDED, NUM_SUBTASKS * 2);
+
return new SourceCoordinator<>(OPERATOR_NAME, coordinatorExecutor, mockSource, context);
}
}
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
index b18d85e..799b2a1 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
@@ -47,11 +47,11 @@ import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput;
import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService;
import org.apache.flink.util.CollectionUtil;
import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.function.FunctionWithException;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
-import java.util.function.Function;
import static org.apache.flink.util.Preconditions.checkNotNull;
@@ -79,7 +79,7 @@ public class SourceOperator<OUT, SplitT extends SourceSplit>
/** The factory for the source reader. This is a workaround, because currently the SourceReader
* must be lazily initialized, which is mainly because the metrics groups that the reader relies on is
* lazily initialized. */
- private final Function<SourceReaderContext, SourceReader<OUT, SplitT>> readerFactory;
+ private final FunctionWithException<SourceReaderContext, SourceReader<OUT, SplitT>, Exception> readerFactory;
/** The serializer for the splits, applied to the split types before storing them in the reader state. */
private final SimpleVersionedSerializer<SplitT> splitSerializer;
@@ -113,7 +113,7 @@ public class SourceOperator<OUT, SplitT extends SourceSplit>
private TimestampsAndWatermarks<OUT> eventTimeLogic;
public SourceOperator(
- Function<SourceReaderContext, SourceReader<OUT, SplitT>> readerFactory,
+ FunctionWithException<SourceReaderContext, SourceReader<OUT, SplitT>, Exception> readerFactory,
OperatorEventGateway operatorEventGateway,
SimpleVersionedSerializer<SplitT> splitSerializer,
WatermarkStrategy<OUT> watermarkStrategy,
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperatorFactory.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperatorFactory.java
index 1d7aed7..ac7b031 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperatorFactory.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperatorFactory.java
@@ -31,8 +31,7 @@ import org.apache.flink.runtime.operators.coordination.OperatorEventGateway;
import org.apache.flink.runtime.source.coordinator.SourceCoordinatorProvider;
import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService;
import org.apache.flink.streaming.runtime.tasks.ProcessingTimeServiceAware;
-
-import java.util.function.Function;
+import org.apache.flink.util.function.FunctionWithException;
import static org.apache.flink.util.Preconditions.checkNotNull;
@@ -114,7 +113,7 @@ public class SourceOperatorFactory<OUT> extends AbstractStreamOperatorFactory<OU
*/
@SuppressWarnings("unchecked")
private static <T, SplitT extends SourceSplit> SourceOperator<T, SplitT> instantiateSourceOperator(
- Function<SourceReaderContext, SourceReader<T, ?>> readerFactory,
+ FunctionWithException<SourceReaderContext, SourceReader<T, ?>, Exception> readerFactory,
OperatorEventGateway eventGateway,
SimpleVersionedSerializer<?> splitSerializer,
WatermarkStrategy<T> watermarkStrategy,
@@ -123,8 +122,9 @@ public class SourceOperatorFactory<OUT> extends AbstractStreamOperatorFactory<OU
String localHostName) {
// jumping through generics hoops: cast the generics away to then cast them back more strictly typed
- final Function<SourceReaderContext, SourceReader<T, SplitT>> typedReaderFactory =
- (Function<SourceReaderContext, SourceReader<T, SplitT>>) (Function<?, ?>) readerFactory;
+ final FunctionWithException<SourceReaderContext, SourceReader<T, SplitT>, Exception> typedReaderFactory =
+ (FunctionWithException<SourceReaderContext, SourceReader<T, SplitT>, Exception>)
+ (FunctionWithException<?, ?, ?>) readerFactory;
final SimpleVersionedSerializer<SplitT> typedSplitSerializer = (SimpleVersionedSerializer<SplitT>) splitSerializer;
[flink] 16/21: [hotfix] Add a waitUntil() method to the
CommonTestUtils.
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 5787a70fcd54f3c23b6d26b5d48bc5d7e9c92239
Author: Jiangjie (Becket) Qin <ji...@alibaba-inc.com>
AuthorDate: Sun Oct 25 20:02:35 2020 +0800
[hotfix] Add a waitUntil() method to the CommonTestUtils.
---
.../flink/core/testutils/CommonTestUtils.java | 29 ++++++++++++++++++++++
1 file changed, 29 insertions(+)
diff --git a/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/CommonTestUtils.java b/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/CommonTestUtils.java
index 2eb4506..6738412 100644
--- a/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/CommonTestUtils.java
+++ b/flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/core/testutils/CommonTestUtils.java
@@ -29,8 +29,11 @@ import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
+import java.time.Duration;
import java.util.Map;
import java.util.concurrent.Callable;
+import java.util.concurrent.TimeoutException;
+import java.util.function.Supplier;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
@@ -181,4 +184,30 @@ public class CommonTestUtils {
assertThat(e.getMessage(), containsString(msg));
}
}
+
+ /**
+ * Wait util the given condition is met or timeout.
+ *
+ * @param condition the condition to wait for.
+ * @param timeout the maximum time to wait for the condition to become true.
+ * @param errorMsg the error message to include in the <code>TimeoutException</code>
+ * if the condition was not met before timeout.
+ * @throws TimeoutException if the condition is not met before timeout.
+ * @throws InterruptedException if the thread is interrupted.
+ */
+ @SuppressWarnings("BusyWait")
+ public static void waitUtil(Supplier<Boolean> condition, Duration timeout, String errorMsg)
+ throws TimeoutException, InterruptedException {
+ long timeoutMs = timeout.toMillis();
+ if (timeoutMs <= 0) {
+ throw new IllegalArgumentException("The timeout must be positive.");
+ }
+ long startingTime = System.currentTimeMillis();
+ while (!condition.get() && System.currentTimeMillis() - startingTime < timeoutMs) {
+ Thread.sleep(1);
+ }
+ if (!condition.get()) {
+ throw new TimeoutException(errorMsg);
+ }
+ }
}
[flink] 03/21: [backport] Relevant test mock changes from
"[FLINK-18907][task] Add test coverage for watermarks with chained sources"
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit f79a3a78b77dfe75063d58a49ea460a752c64b0d
Author: Piotr Nowojski <pi...@gmail.com>
AuthorDate: Mon Sep 21 15:18:25 2020 +0200
[backport] Relevant test mock changes from "[FLINK-18907][task] Add test coverage for watermarks with chained sources"
---
.../flink/api/connector/source/mocks/MockSource.java | 10 ++++++++--
.../flink/api/connector/source/mocks/MockSourceReader.java | 14 +++++++++++++-
2 files changed, 21 insertions(+), 3 deletions(-)
diff --git a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSource.java b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSource.java
index c48b380..1c29147 100644
--- a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSource.java
+++ b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSource.java
@@ -40,12 +40,18 @@ public class MockSource implements Source<Integer, MockSourceSplit, Set<MockSour
private final Boundedness boundedness;
private final int numSplits;
- private List<MockSourceReader> createdReaders;
+ private final boolean readerWaitingForMoreSplits;
+ protected List<MockSourceReader> createdReaders;
public MockSource(Boundedness boundedness, int numSplits) {
+ this(boundedness, numSplits, false);
+ }
+
+ public MockSource(Boundedness boundedness, int numSplits, boolean readerWaitingForMoreSplits) {
this.boundedness = boundedness;
this.numSplits = numSplits;
this.createdReaders = new ArrayList<>();
+ this.readerWaitingForMoreSplits = readerWaitingForMoreSplits;
}
@Override
@@ -55,7 +61,7 @@ public class MockSource implements Source<Integer, MockSourceSplit, Set<MockSour
@Override
public SourceReader<Integer, MockSourceSplit> createReader(SourceReaderContext readerContext) {
- MockSourceReader mockSourceReader = new MockSourceReader();
+ MockSourceReader mockSourceReader = new MockSourceReader(readerWaitingForMoreSplits);
createdReaders.add(mockSourceReader);
return mockSourceReader;
}
diff --git a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
index d474e1f..58ae951 100644
--- a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
+++ b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
@@ -39,14 +39,19 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
private int currentSplitIndex = 0;
private boolean started;
private boolean closed;
+ private boolean waitingForMoreSplits;
@GuardedBy("this")
private CompletableFuture<Void> availableFuture;
public MockSourceReader() {
+ this(false);
+ }
+ public MockSourceReader(boolean waitingForMoreSplits) {
this.started = false;
this.closed = false;
this.availableFuture = CompletableFuture.completedFuture(null);
+ this.waitingForMoreSplits = waitingForMoreSplits;
}
@Override
@@ -56,7 +61,7 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
@Override
public InputStatus pollNext(ReaderOutput<Integer> sourceOutput) throws Exception {
- boolean finished = true;
+ boolean finished = !waitingForMoreSplits;
currentSplitIndex = 0;
// Find first splits with available records.
while (currentSplitIndex < assignedSplits.size()
@@ -96,6 +101,10 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
@Override
public void handleSourceEvents(SourceEvent sourceEvent) {
+ if (sourceEvent instanceof MockNoMoreSplitsEvent) {
+ waitingForMoreSplits = false;
+ markAvailable();
+ }
receivedSourceEvents.add(sourceEvent);
}
@@ -139,4 +148,7 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
public List<SourceEvent> getReceivedSourceEvents() {
return receivedSourceEvents;
}
+
+ public static class MockNoMoreSplitsEvent implements SourceEvent {
+ }
}
[flink] 07/21: [FLINK-19457][core] Add a number sequence generating
source for the FLIP-27 source API.
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 09ea814090eca8f0084b3a07add6cb3595705e47
Author: Stephan Ewen <se...@apache.org>
AuthorDate: Wed Sep 23 18:10:34 2020 +0200
[FLINK-19457][core] Add a number sequence generating source for the FLIP-27 source API.
This closes #13512
---
.../connector/source/lib/NumberSequenceSource.java | 253 +++++++++++++++++++++
.../source/lib/util/IteratorSourceEnumerator.java | 88 +++++++
.../source/lib/util/IteratorSourceReader.java | 146 ++++++++++++
.../source/lib/util/IteratorSourceSplit.java | 43 ++++
.../source/lib/util/NoSplitAvailableEvent.java | 31 +++
.../source/lib/util/SplitRequestEvent.java | 31 +++
.../source/lib/NumberSequenceSourceTest.java | 91 ++++++++
.../source/lib/IteratorSourcesITCase.java | 90 ++++++++
8 files changed, 773 insertions(+)
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/NumberSequenceSource.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/NumberSequenceSource.java
new file mode 100644
index 0000000..154ac7f
--- /dev/null
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/NumberSequenceSource.java
@@ -0,0 +1,253 @@
+/*
+ * 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.api.connector.source.lib;
+
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.connector.source.Boundedness;
+import org.apache.flink.api.connector.source.Source;
+import org.apache.flink.api.connector.source.SourceReader;
+import org.apache.flink.api.connector.source.SourceReaderContext;
+import org.apache.flink.api.connector.source.SplitEnumerator;
+import org.apache.flink.api.connector.source.SplitEnumeratorContext;
+import org.apache.flink.api.connector.source.lib.util.IteratorSourceEnumerator;
+import org.apache.flink.api.connector.source.lib.util.IteratorSourceReader;
+import org.apache.flink.api.connector.source.lib.util.IteratorSourceSplit;
+import org.apache.flink.api.java.typeutils.ResultTypeQueryable;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+import org.apache.flink.core.memory.DataInputDeserializer;
+import org.apache.flink.core.memory.DataInputView;
+import org.apache.flink.core.memory.DataOutputSerializer;
+import org.apache.flink.core.memory.DataOutputView;
+import org.apache.flink.util.NumberSequenceIterator;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+/**
+ * A data source that produces a sequence of numbers (longs).
+ * This source is useful for testing and for cases that just need a stream of N events of any kind.
+ *
+ * <p>The source splits the sequence into as many parallel sub-sequences as there are parallel
+ * source readers. Each sub-sequence will be produced in order.
+ * Consequently, if the parallelism is limited to one, this will produce one sequence in order.
+ *
+ * <p>This source is always bounded. For very long sequences (for example over the entire domain
+ * of long integer values), user may want to consider executing the application in a streaming manner,
+ * because, despite the fact that the produced stream is bounded, the end bound is pretty far away.
+ */
+public class NumberSequenceSource implements
+ Source<Long, NumberSequenceSource.NumberSequenceSplit, Collection<NumberSequenceSource.NumberSequenceSplit>>,
+ ResultTypeQueryable<Long> {
+
+ private static final long serialVersionUID = 1L;
+
+ /** The starting number in the sequence, inclusive. */
+ private final long from;
+
+ /** The end number in the sequence, inclusive. */
+ private final long to;
+
+ /**
+ * Creates a new {@code NumberSequenceSource} that produces parallel sequences covering the range
+ * {@code from} to {@code to} (both boundaries are inclusive).
+ */
+ public NumberSequenceSource(long from, long to) {
+ checkArgument(from <= to, "'from' must be <= 'to'");
+ this.from = from;
+ this.to = to;
+ }
+
+ @Override
+ public TypeInformation<Long> getProducedType() {
+ return Types.LONG;
+ }
+
+ @Override
+ public Boundedness getBoundedness() {
+ return Boundedness.BOUNDED;
+ }
+
+ @Override
+ public SourceReader<Long, NumberSequenceSplit> createReader(SourceReaderContext readerContext) {
+ return new IteratorSourceReader<>(readerContext);
+ }
+
+ @Override
+ public SplitEnumerator<NumberSequenceSplit, Collection<NumberSequenceSplit>> createEnumerator(
+ final SplitEnumeratorContext<NumberSequenceSplit> enumContext) {
+
+ final NumberSequenceIterator[] subSequences =
+ new NumberSequenceIterator(from, to).split(enumContext.currentParallelism());
+ final ArrayList<NumberSequenceSplit> splits = new ArrayList<>(subSequences.length);
+
+ int splitId = 1;
+ for (NumberSequenceIterator seq : subSequences) {
+ splits.add(new NumberSequenceSplit(String.valueOf(splitId++), seq.getCurrent(), seq.getTo()));
+ }
+
+ return new IteratorSourceEnumerator<>(enumContext, splits);
+ }
+
+ @Override
+ public SplitEnumerator<NumberSequenceSplit, Collection<NumberSequenceSplit>> restoreEnumerator(
+ final SplitEnumeratorContext<NumberSequenceSplit> enumContext, Collection<NumberSequenceSplit> checkpoint) {
+ return new IteratorSourceEnumerator<>(enumContext, checkpoint);
+ }
+
+ @Override
+ public SimpleVersionedSerializer<NumberSequenceSplit> getSplitSerializer() {
+ return new SplitSerializer();
+ }
+
+ @Override
+ public SimpleVersionedSerializer<Collection<NumberSequenceSplit>> getEnumeratorCheckpointSerializer() {
+ return new CheckpointSerializer();
+ }
+
+ // ------------------------------------------------------------------------
+ // splits & checkpoint
+ // ------------------------------------------------------------------------
+
+ /**
+ * A split of the source, representing a number sub-sequence.
+ */
+ public static class NumberSequenceSplit implements IteratorSourceSplit<Long, NumberSequenceIterator> {
+
+ private final String splitId;
+ private final long from;
+ private final long to;
+
+ public NumberSequenceSplit(String splitId, long from, long to) {
+ checkArgument(from <= to, "'from' must be <= 'to'");
+ this.splitId = checkNotNull(splitId);
+ this.from = from;
+ this.to = to;
+ }
+
+ @Override
+ public String splitId() {
+ return splitId;
+ }
+
+ public long from() {
+ return from;
+ }
+
+ public long to() {
+ return to;
+ }
+
+ @Override
+ public NumberSequenceIterator getIterator() {
+ return new NumberSequenceIterator(from, to);
+ }
+
+ @Override
+ public IteratorSourceSplit<Long, NumberSequenceIterator> getUpdatedSplitForIterator(
+ final NumberSequenceIterator iterator) {
+ return new NumberSequenceSplit(splitId, iterator.getCurrent(), iterator.getTo());
+ }
+
+ @Override
+ public String toString() {
+ return String.format("NumberSequenceSplit [%d, %d] (%s)", from, to, splitId);
+ }
+ }
+
+ private static final class SplitSerializer implements SimpleVersionedSerializer<NumberSequenceSplit> {
+
+ private static final int CURRENT_VERSION = 1;
+
+ @Override
+ public int getVersion() {
+ return CURRENT_VERSION;
+ }
+
+ @Override
+ public byte[] serialize(NumberSequenceSplit split) throws IOException {
+ checkArgument(split.getClass() == NumberSequenceSplit.class, "cannot serialize subclasses");
+
+ // We will serialize 2 longs (16 bytes) plus the UFT representation of the string (2 + length)
+ final DataOutputSerializer out = new DataOutputSerializer(split.splitId().length() + 18);
+ serializeV1(out, split);
+ return out.getCopyOfBuffer();
+ }
+
+ @Override
+ public NumberSequenceSplit deserialize(int version, byte[] serialized) throws IOException {
+ if (version != CURRENT_VERSION) {
+ throw new IOException("Unrecognized version: " + version);
+ }
+ final DataInputDeserializer in = new DataInputDeserializer(serialized);
+ return deserializeV1(in);
+ }
+
+ static void serializeV1(DataOutputView out, NumberSequenceSplit split) throws IOException {
+ out.writeUTF(split.splitId());
+ out.writeLong(split.from());
+ out.writeLong(split.to());
+ }
+
+ static NumberSequenceSplit deserializeV1(DataInputView in) throws IOException {
+ return new NumberSequenceSplit(in.readUTF(), in.readLong(), in.readLong());
+ }
+ }
+
+ private static final class CheckpointSerializer implements SimpleVersionedSerializer<Collection<NumberSequenceSplit>> {
+
+ private static final int CURRENT_VERSION = 1;
+
+ @Override
+ public int getVersion() {
+ return CURRENT_VERSION;
+ }
+
+ @Override
+ public byte[] serialize(Collection<NumberSequenceSplit> checkpoint) throws IOException {
+ // Each split needs 2 longs (16 bytes) plus the UFT representation of the string (2 + length)
+ // Assuming at most 4 digit split IDs, 22 bytes per split avoids any intermediate array resizing.
+ // plus four bytes for the length field
+ final DataOutputSerializer out = new DataOutputSerializer(checkpoint.size() * 22 + 4);
+ out.writeInt(checkpoint.size());
+ for (NumberSequenceSplit split : checkpoint) {
+ SplitSerializer.serializeV1(out, split);
+ }
+ return out.getCopyOfBuffer();
+ }
+
+ @Override
+ public Collection<NumberSequenceSplit> deserialize(int version, byte[] serialized) throws IOException {
+ if (version != CURRENT_VERSION) {
+ throw new IOException("Unrecognized version: " + version);
+ }
+ final DataInputDeserializer in = new DataInputDeserializer(serialized);
+ final int num = in.readInt();
+ final ArrayList<NumberSequenceSplit> result = new ArrayList<>(num);
+ for (int remaining = num; remaining > 0; remaining--) {
+ result.add(SplitSerializer.deserializeV1(in));
+ }
+ return result;
+ }
+ }
+}
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceEnumerator.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceEnumerator.java
new file mode 100644
index 0000000..3ee2597
--- /dev/null
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceEnumerator.java
@@ -0,0 +1,88 @@
+/*
+ * 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.api.connector.source.lib.util;
+
+import org.apache.flink.api.connector.source.SourceEvent;
+import org.apache.flink.api.connector.source.SplitEnumerator;
+import org.apache.flink.api.connector.source.SplitEnumeratorContext;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import java.util.ArrayDeque;
+import java.util.Collection;
+import java.util.List;
+import java.util.Queue;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+/**
+ * A {@link SplitEnumerator} for iterator sources. Simply takes the pre-split set of splits and assigns
+ * it first-come-first-serve.
+ *
+ * @param <SplitT> The type of the splits used by the source.
+ */
+public class IteratorSourceEnumerator<SplitT extends IteratorSourceSplit<?, ?>> implements SplitEnumerator<SplitT, Collection<SplitT>> {
+
+ private final SplitEnumeratorContext<SplitT> context;
+ private final Queue<SplitT> remainingSplits;
+
+ public IteratorSourceEnumerator(SplitEnumeratorContext<SplitT> context, Collection<SplitT> splits) {
+ this.context = checkNotNull(context);
+ this.remainingSplits = new ArrayDeque<>(splits);
+ }
+
+ // ------------------------------------------------------------------------
+
+ @Override
+ public void start() {}
+
+ @Override
+ public void close() {}
+
+ @Override
+ public void handleSourceEvent(int subtaskId, SourceEvent sourceEvent) {
+ if (!(sourceEvent instanceof SplitRequestEvent)) {
+ throw new FlinkRuntimeException("Unrecognized event: " + sourceEvent);
+ }
+
+ final SplitT nextSplit = remainingSplits.poll();
+ if (nextSplit != null) {
+ context.assignSplit(nextSplit, subtaskId);
+ } else {
+ context.sendEventToSourceReader(subtaskId, new NoSplitAvailableEvent());
+ }
+ }
+
+ @Override
+ public void addSplitsBack(List<SplitT> splits, int subtaskId) {
+ remainingSplits.addAll(splits);
+ }
+
+ @Override
+ public Collection<SplitT> snapshotState() throws Exception {
+ return remainingSplits;
+ }
+
+ @Override
+ public void addReader(int subtaskId) {
+ // we don't assign any splits here, because this registration happens after fist startup
+ // and after each reader restart/recovery
+ // we only want to assign splits once, initially, which we get by reacting to the readers explicit
+ // split request
+ }
+}
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceReader.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceReader.java
new file mode 100644
index 0000000..f9d7461
--- /dev/null
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceReader.java
@@ -0,0 +1,146 @@
+/*
+ * 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.api.connector.source.lib.util;
+
+import org.apache.flink.api.connector.source.ReaderOutput;
+import org.apache.flink.api.connector.source.SourceEvent;
+import org.apache.flink.api.connector.source.SourceReader;
+import org.apache.flink.api.connector.source.SourceReaderContext;
+import org.apache.flink.core.io.InputStatus;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import javax.annotation.Nullable;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.CompletableFuture;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * A {@link SourceReader} that returns the values of an iterator, supplied via an
+ * {@link IteratorSourceSplit}.
+ *
+ * <p>The {@code IteratorSourceSplit} is also responsible for taking the current iterator and turning
+ * it back into a split for checkpointing.
+ *
+ * @param <E> The type of events returned by the reader.
+ * @param <IterT> The type of the iterator that produces the events. This type exists to make the
+ * conversion between iterator and {@code IteratorSourceSplit} type safe.
+ * @param <SplitT> The concrete type of the {@code IteratorSourceSplit} that creates and converts the
+ * iterator that produces this reader's elements.
+ */
+public class IteratorSourceReader<E, IterT extends Iterator<E>, SplitT extends IteratorSourceSplit<E, IterT>>
+ implements SourceReader<E, SplitT> {
+
+ /** The context for this reader, to communicate with the enumerator. */
+ private final SourceReaderContext context;
+
+ /** The availability future. This reader is available as soon as a split is assigned. */
+ private final CompletableFuture<Void> availability;
+
+ /** The iterator producing data. Non-null after a split has been assigned.
+ * This field is null or non-null always together with the {@link #currentSplit} field. */
+ @Nullable
+ private IterT iterator;
+
+ /** The split whose data we return. Non-null after a split has been assigned.
+ * This field is null or non-null always together with the {@link #iterator} field. */
+ @Nullable
+ private SplitT currentSplit;
+
+ /** The remaining splits. Null means no splits have yet been assigned. */
+ @Nullable
+ private Queue<SplitT> remainingSplits;
+
+ public IteratorSourceReader(SourceReaderContext context) {
+ this.context = checkNotNull(context);
+ this.availability = new CompletableFuture<>();
+ }
+
+ // ------------------------------------------------------------------------
+
+ @Override
+ public void start() {
+ // request a split only if we did not get one during restore
+ if (iterator == null) {
+ context.sendSourceEventToCoordinator(new SplitRequestEvent());
+ }
+ }
+
+ @Override
+ public InputStatus pollNext(ReaderOutput<E> output) {
+ if (iterator != null && iterator.hasNext()) {
+ output.collect(iterator.next());
+ return InputStatus.MORE_AVAILABLE;
+ } else if (remainingSplits == null) {
+ // nothing assigned yet, need to wait and come back when splits have been assigned
+ return InputStatus.NOTHING_AVAILABLE;
+ } else {
+ currentSplit = remainingSplits.poll();
+ if (currentSplit != null) {
+ iterator = currentSplit.getIterator();
+ return pollNext(output);
+ } else {
+ return InputStatus.END_OF_INPUT;
+ }
+ }
+ }
+
+ @Override
+ public CompletableFuture<Void> isAvailable() {
+ return availability;
+ }
+
+ @Override
+ public void addSplits(List<SplitT> splits) {
+ checkState(remainingSplits == null, "Cannot accept more than one split assignment");
+ remainingSplits = new ArrayDeque<>(splits);
+ availability.complete(null); // from now on we are always available
+ }
+
+ @Override
+ public List<SplitT> snapshotState() {
+ final ArrayList<SplitT> allSplits = new ArrayList<>(1 + remainingSplits.size());
+ if (iterator != null) {
+ @SuppressWarnings("unchecked")
+ final SplitT inProgressSplit = (SplitT) currentSplit.getUpdatedSplitForIterator(iterator);
+ allSplits.add(inProgressSplit);
+ }
+ allSplits.addAll(remainingSplits);
+ return allSplits;
+ }
+
+ @Override
+ public void handleSourceEvents(SourceEvent sourceEvent) {
+ if (sourceEvent instanceof NoSplitAvailableEvent) {
+ // non-null queue signals splits were assigned, in this case no splits
+ remainingSplits = new ArrayDeque<>();
+ } else {
+ throw new FlinkRuntimeException("Unexpected event: " + sourceEvent);
+ }
+ }
+
+ @Override
+ public void close() throws Exception {}
+}
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceSplit.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceSplit.java
new file mode 100644
index 0000000..60caf4f
--- /dev/null
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceSplit.java
@@ -0,0 +1,43 @@
+/*
+ * 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.api.connector.source.lib.util;
+
+import org.apache.flink.api.connector.source.SourceSplit;
+
+import java.util.Iterator;
+
+/**
+ * A {@link SourceSplit} that represents a sequence of elements captured in an iterator.
+ * The split produces the iterator and converts the iterator back to a new split during
+ * checkpointing.
+ *
+ * @param <E> The type of the elements returned by the iterator.
+ */
+public interface IteratorSourceSplit<E, IterT extends Iterator<E>> extends SourceSplit {
+
+ /**
+ * Gets the iterator over the elements of this split.
+ */
+ IterT getIterator();
+
+ /**
+ * Converts an iterator (that may have returned some elements already) back into a source split.
+ */
+ IteratorSourceSplit<E, IterT> getUpdatedSplitForIterator(IterT iterator);
+}
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/NoSplitAvailableEvent.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/NoSplitAvailableEvent.java
new file mode 100644
index 0000000..5a28565
--- /dev/null
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/NoSplitAvailableEvent.java
@@ -0,0 +1,31 @@
+/*
+ * 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.api.connector.source.lib.util;
+
+import org.apache.flink.api.connector.source.SourceEvent;
+import org.apache.flink.api.connector.source.SourceReader;
+import org.apache.flink.api.connector.source.SplitEnumerator;
+
+/**
+ * A simple {@link SourceEvent} indicating that there is no split available for the reader (any more).
+ * This event is typically sent from the {@link SplitEnumerator} to the {@link SourceReader}.
+ */
+public final class NoSplitAvailableEvent implements SourceEvent {
+ private static final long serialVersionUID = 1L;
+}
diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/SplitRequestEvent.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/SplitRequestEvent.java
new file mode 100644
index 0000000..3e561b7
--- /dev/null
+++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/SplitRequestEvent.java
@@ -0,0 +1,31 @@
+/*
+ * 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.api.connector.source.lib.util;
+
+import org.apache.flink.api.connector.source.SourceEvent;
+import org.apache.flink.api.connector.source.SourceReader;
+import org.apache.flink.api.connector.source.SplitEnumerator;
+
+/**
+ * A {@link SourceEvent} representing the request for a split, typically sent from the
+ * {@link SourceReader} to the {@link SplitEnumerator}.
+ */
+public final class SplitRequestEvent implements SourceEvent {
+ private static final long serialVersionUID = 1L;
+}
diff --git a/flink-core/src/test/java/org/apache/flink/api/connector/source/lib/NumberSequenceSourceTest.java b/flink-core/src/test/java/org/apache/flink/api/connector/source/lib/NumberSequenceSourceTest.java
new file mode 100644
index 0000000..450983e
--- /dev/null
+++ b/flink-core/src/test/java/org/apache/flink/api/connector/source/lib/NumberSequenceSourceTest.java
@@ -0,0 +1,91 @@
+/*
+ * 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.api.connector.source.lib;
+
+import org.apache.flink.api.connector.source.SourceReader;
+import org.apache.flink.api.connector.source.mocks.TestingReaderContext;
+import org.apache.flink.api.connector.source.mocks.TestingReaderOutput;
+import org.apache.flink.core.io.InputStatus;
+
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.Assert.fail;
+
+/**
+ * Tests for the {@link NumberSequenceSource}.
+ */
+public class NumberSequenceSourceTest {
+
+ @Test
+ public void testReaderCheckpoints() throws Exception {
+ final long from = 177;
+ final long mid = 333;
+ final long to = 563;
+ final long elementsPerCycle = (to - from) / 3;
+
+ final TestingReaderOutput<Long> out = new TestingReaderOutput<>();
+
+ SourceReader<Long, NumberSequenceSource.NumberSequenceSplit> reader = createReader();
+ reader.addSplits(Arrays.asList(
+ new NumberSequenceSource.NumberSequenceSplit("split-1", from, mid),
+ new NumberSequenceSource.NumberSequenceSplit("split-2", mid + 1, to)));
+
+ long remainingInCycle = elementsPerCycle;
+ while (reader.pollNext(out) != InputStatus.END_OF_INPUT) {
+ if (--remainingInCycle <= 0) {
+ remainingInCycle = elementsPerCycle;
+ // checkpoint
+ List<NumberSequenceSource.NumberSequenceSplit> splits = reader.snapshotState();
+
+ // re-create and restore
+ reader = createReader();
+ reader.addSplits(splits);
+ }
+ }
+
+ final List<Long> result = out.getEmittedRecords();
+ validateSequence(result, from, to);
+ }
+
+ private static void validateSequence(final List<Long> sequence, final long from, final long to) {
+ if (sequence.size() != to - from + 1) {
+ failSequence(sequence, from, to);
+ }
+
+ long nextExpected = from;
+ for (Long next : sequence) {
+ if (next != nextExpected++) {
+ failSequence(sequence, from, to);
+ }
+ }
+ }
+
+ private static void failSequence(final List<Long> sequence, final long from, final long to) {
+ fail(String.format("Expected: A sequence [%d, %d], but found: sequence (size %d) : %s",
+ from, to, sequence.size(), sequence));
+ }
+
+ private static SourceReader<Long, NumberSequenceSource.NumberSequenceSplit> createReader() {
+ // the arguments passed in the source constructor matter only to the enumerator
+ return new NumberSequenceSource(0L, 0L).createReader(new TestingReaderContext());
+ }
+}
diff --git a/flink-tests/src/test/java/org/apache/flink/api/connector/source/lib/IteratorSourcesITCase.java b/flink-tests/src/test/java/org/apache/flink/api/connector/source/lib/IteratorSourcesITCase.java
new file mode 100644
index 0000000..00909ce
--- /dev/null
+++ b/flink-tests/src/test/java/org/apache/flink/api/connector/source/lib/IteratorSourcesITCase.java
@@ -0,0 +1,90 @@
+/*
+ * 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.api.connector.source.lib;
+
+import org.apache.flink.api.common.eventtime.WatermarkStrategy;
+import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.datastream.DataStreamUtils;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.test.util.MiniClusterWithClientResource;
+import org.apache.flink.util.TestLogger;
+
+import org.junit.ClassRule;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.fail;
+
+/**
+ * An integration test for the sources based on iterators.
+ *
+ * <p>This test uses the {@link NumberSequenceSource} as a concrete iterator source implementation,
+ * but covers all runtime-related aspects for all the iterator-based sources together.
+ */
+public class IteratorSourcesITCase extends TestLogger {
+
+ private static final int PARALLELISM = 4;
+
+ @ClassRule
+ public static final MiniClusterWithClientResource MINI_CLUSTER = new MiniClusterWithClientResource(
+ new MiniClusterResourceConfiguration.Builder()
+ .setNumberTaskManagers(1)
+ .setNumberSlotsPerTaskManager(PARALLELISM)
+ .build());
+
+ // ------------------------------------------------------------------------
+
+ @Test
+ public void testParallelSourceExecution() throws Exception {
+ final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
+ env.setParallelism(PARALLELISM);
+
+ final DataStream<Long> stream = env.fromSource(
+ new NumberSequenceSource(1L, 1_000L),
+ WatermarkStrategy.noWatermarks(),
+ "iterator source");
+
+ final List<Long> result = DataStreamUtils.collectBoundedStream(stream, "Iterator Source Test");
+
+ verifySequence(result, 1L, 1_000L);
+ }
+
+ // ------------------------------------------------------------------------
+ // test utils
+ // ------------------------------------------------------------------------
+
+ private static void verifySequence(final List<Long> sequence, final long from, final long to) {
+ if (sequence.size() != to - from + 1) {
+ fail(String.format("Expected: Sequence [%d, %d]. Found: %s", from, to, sequence));
+ }
+
+ final ArrayList<Long> list = new ArrayList<>(sequence); // copy to be safe against immutable lists, etc.
+ list.sort(Long::compareTo);
+
+ int pos = 0;
+ for (long value = from; value <= to; value++, pos++) {
+ if (value != list.get(pos)) {
+ fail(String.format("Expected: Sequence [%d, %d]. Found: %s", from, to, list));
+ }
+ }
+ }
+}
[flink] 05/21: [backport] Relevant test mock changes from
"[FLINK-18907][test] Add stream status forwarding test for chained sources"
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 242ced99de92b07cf433b5408acd08985e5d7499
Author: Piotr Nowojski <pi...@gmail.com>
AuthorDate: Tue Sep 22 14:14:52 2020 +0200
[backport] Relevant test mock changes from "[FLINK-18907][test] Add stream status forwarding test for chained sources"
---
.../org/apache/flink/api/connector/source/mocks/MockSource.java | 8 +++++---
.../flink/api/connector/source/mocks/MockSourceReader.java | 9 +++++++--
2 files changed, 12 insertions(+), 5 deletions(-)
diff --git a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSource.java b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSource.java
index 1c29147..b860f27 100644
--- a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSource.java
+++ b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSource.java
@@ -41,17 +41,19 @@ public class MockSource implements Source<Integer, MockSourceSplit, Set<MockSour
private final Boundedness boundedness;
private final int numSplits;
private final boolean readerWaitingForMoreSplits;
+ private final boolean readerMarkIdleOnNoSplits;
protected List<MockSourceReader> createdReaders;
public MockSource(Boundedness boundedness, int numSplits) {
- this(boundedness, numSplits, false);
+ this(boundedness, numSplits, false, false);
}
- public MockSource(Boundedness boundedness, int numSplits, boolean readerWaitingForMoreSplits) {
+ public MockSource(Boundedness boundedness, int numSplits, boolean readerWaitingForMoreSplits, boolean readerMarkIdleOnNoSplits) {
this.boundedness = boundedness;
this.numSplits = numSplits;
this.createdReaders = new ArrayList<>();
this.readerWaitingForMoreSplits = readerWaitingForMoreSplits;
+ this.readerMarkIdleOnNoSplits = readerMarkIdleOnNoSplits;
}
@Override
@@ -61,7 +63,7 @@ public class MockSource implements Source<Integer, MockSourceSplit, Set<MockSour
@Override
public SourceReader<Integer, MockSourceSplit> createReader(SourceReaderContext readerContext) {
- MockSourceReader mockSourceReader = new MockSourceReader(readerWaitingForMoreSplits);
+ MockSourceReader mockSourceReader = new MockSourceReader(readerWaitingForMoreSplits, readerMarkIdleOnNoSplits);
createdReaders.add(mockSourceReader);
return mockSourceReader;
}
diff --git a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
index 4910f74..e48f827 100644
--- a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
+++ b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
@@ -35,6 +35,7 @@ import java.util.concurrent.CompletableFuture;
public class MockSourceReader implements SourceReader<Integer, MockSourceSplit> {
private final List<MockSourceSplit> assignedSplits = new ArrayList<>();
private final List<SourceEvent> receivedSourceEvents = new ArrayList<>();
+ private final boolean markIdleOnNoSplits;
private int currentSplitIndex = 0;
private boolean started;
@@ -45,14 +46,15 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
private CompletableFuture<Void> availableFuture;
public MockSourceReader() {
- this(false);
+ this(false, false);
}
- public MockSourceReader(boolean waitingForMoreSplits) {
+ public MockSourceReader(boolean waitingForMoreSplits, boolean markIdleOnNoSplits) {
this.started = false;
this.closed = false;
this.availableFuture = CompletableFuture.completedFuture(null);
this.waitingForMoreSplits = waitingForMoreSplits;
+ this.markIdleOnNoSplits = markIdleOnNoSplits;
}
@Override
@@ -79,6 +81,9 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
return InputStatus.END_OF_INPUT;
}
else {
+ if (markIdleOnNoSplits) {
+ sourceOutput.markIdle();
+ }
markUnavailable();
return InputStatus.NOTHING_AVAILABLE;
}
[flink] 09/21: [FLINK-19448][connector base] Explicitly check for
un-expected condition that would leave an inconsistent state
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit cdc0721f6f4da04e5d08dd0f63a9c503b34410a7
Author: Stephan Ewen <se...@apache.org>
AuthorDate: Mon Oct 12 17:38:30 2020 +0200
[FLINK-19448][connector base] Explicitly check for un-expected condition that would leave an inconsistent state
This condition should never happen, but if it ever happened, it would leave the source in an idle state waiting for
more input data, rather than shutting down.
---
.../flink/connector/base/source/reader/SourceReaderBase.java | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderBase.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderBase.java
index 1182cae..e1da654 100644
--- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderBase.java
+++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderBase.java
@@ -262,10 +262,13 @@ public abstract class SourceReaderBase<E, T, SplitT extends SourceSplit, SplitSt
private InputStatus finishedOrAvailableLater() {
final boolean allFetchersHaveShutdown = splitFetcherManager.maybeShutdownFinishedFetchers();
- if (noMoreSplitsAssignment && allFetchersHaveShutdown && elementsQueue.isEmpty()) {
+ if (!(noMoreSplitsAssignment && allFetchersHaveShutdown)) {
+ return InputStatus.NOTHING_AVAILABLE;
+ }
+ if (elementsQueue.isEmpty()) {
return InputStatus.END_OF_INPUT;
} else {
- return InputStatus.NOTHING_AVAILABLE;
+ throw new IllegalStateException("Called 'finishedOrAvailableLater()' with shut-down fetchers but non-empty queue");
}
}
[flink] 04/21: [backport] Relevant test mock changes from
"[FLINK-18907][task] Fix and add test coverage for watermarks gauges with
chained sources"
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit cd3ffa5365cfe9461533e7b047d458caf7040a08
Author: Piotr Nowojski <pi...@gmail.com>
AuthorDate: Mon Sep 21 18:17:20 2020 +0200
[backport] Relevant test mock changes from "[FLINK-18907][task] Fix and add test coverage for watermarks gauges with chained sources"
---
.../org/apache/flink/api/connector/source/mocks/MockSourceReader.java | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
index 58ae951..4910f74 100644
--- a/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
+++ b/flink-core/src/test/java/org/apache/flink/api/connector/source/mocks/MockSourceReader.java
@@ -47,6 +47,7 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
public MockSourceReader() {
this(false);
}
+
public MockSourceReader(boolean waitingForMoreSplits) {
this.started = false;
this.closed = false;
@@ -149,6 +150,9 @@ public class MockSourceReader implements SourceReader<Integer, MockSourceSplit>
return receivedSourceEvents;
}
+ /**
+ * Simple event allowing {@link MockSourceReader} to finish when requested.
+ */
public static class MockNoMoreSplitsEvent implements SourceEvent {
}
}
[flink] 12/21: [hotfix][runtime] Remove commented-out annotation in
SourceOperator
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch release-1.11
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 1f823bd9facfe84f0ec079530b375ddbdaa0575a
Author: Stephan Ewen <se...@apache.org>
AuthorDate: Mon Sep 21 18:09:43 2020 +0200
[hotfix][runtime] Remove commented-out annotation in SourceOperator
---
.../java/org/apache/flink/streaming/api/operators/SourceOperator.java | 1 -
1 file changed, 1 deletion(-)
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
index d925b23..742d7ce 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java
@@ -66,7 +66,6 @@ import static org.apache.flink.util.Preconditions.checkNotNull;
* @param <OUT> The output type of the operator.
*/
@Internal
-//@SuppressWarnings("serial")
public class SourceOperator<OUT, SplitT extends SourceSplit>
extends AbstractStreamOperator<OUT>
implements OperatorEventHandler, PushingAsyncDataInput<OUT> {