diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/event/NoMoreSplitsEvent.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/event/NoMoreSplitsEvent.java index ed3663b4..e2ca2e49 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/event/NoMoreSplitsEvent.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/event/NoMoreSplitsEvent.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.event; diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/RecordEmitter.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/RecordEmitter.java index 6a26aa57..9dbd23af 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/RecordEmitter.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/RecordEmitter.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader; diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/RecordsBySplits.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/RecordsBySplits.java index bdd16fff..77cb5942 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/RecordsBySplits.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/RecordsBySplits.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader; diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/RecordsWithSplitIds.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/RecordsWithSplitIds.java index 813c6a50..f616125e 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/RecordsWithSplitIds.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/RecordsWithSplitIds.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader; 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 0e22ef0c..546e20a3 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 @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader; 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 b5781dee..e01180e7 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 @@ -1,23 +1,24 @@ /* - 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. + * 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.connector.base.source.reader; +import org.apache.flink.api.connector.source.ReaderOutput; import org.apache.flink.api.connector.source.SourceEvent; import org.apache.flink.api.connector.source.SourceOutput; import org.apache.flink.api.connector.source.SourceReader; @@ -63,7 +64,7 @@ public abstract class SourceReaderBase> elementsQueue; /** The state of the splits. */ - private final Map splitStates; + private final Map> splitStates; /** The record emitter to handle the records read by the SplitReaders. */ protected final RecordEmitter recordEmitter; @@ -111,7 +112,7 @@ public abstract class SourceReaderBase sourceOutput) throws Exception { + public InputStatus pollNext(ReaderOutput output) throws Exception { splitFetcherManager.checkErrors(); // poll from the queue if the last element was successfully handled. Otherwise // just pass the last element again. @@ -133,14 +134,19 @@ public abstract class SourceReaderBase splitContext = splitStates.get(splitIter.currentSplitId()); + final SourceOutput splitOutput = splitContext.getOrCreateSplitOutput(output); + recordEmitter.emitRecord(record, splitOutput, splitContext.state); LOG.trace("Emitted record: {}", record); } // Do some cleanup if the all the records in the current splitIter have been processed. if (!splitIter.hasNext()) { // First remove the state of the split. - splitIter.finishedSplitIds().forEach(splitStates::remove); + splitIter.finishedSplitIds().forEach((id) -> { + splitStates.remove(id); + output.releaseOutputForSplit(id); + }); // Handle the finished splits. onSplitFinished(splitIter.finishedSplitIds()); // Prepare the return status based on the availability of the next element. @@ -173,7 +179,7 @@ public abstract class SourceReaderBase snapshotState() { List splits = new ArrayList<>(); - splitStates.forEach((id, state) -> splits.add(toSplitType(id, state))); + splitStates.forEach((id, context) -> splits.add(toSplitType(id, context.state))); return splits; } @@ -181,7 +187,7 @@ public abstract class SourceReaderBase splits) { LOG.trace("Adding splits {}", splits); // Initialize the state for each split. - splits.forEach(s -> splitStates.put(s.splitId(), initializedState(s))); + splits.forEach(s -> splitStates.put(s.splitId(), new SplitContext<>(s.splitId(), initializedState(s)))); // Hand over the splits to the split fetcher to start fetch. splitFetcherManager.addSplits(splits); } @@ -201,6 +207,8 @@ public abstract class SourceReaderBase { + + final String splitId; + final SplitStateT state; + SourceOutput sourceOutput; + + private SplitContext(String splitId, SplitStateT state) { + this.state = state; + this.splitId = splitId; + } + + SourceOutput getOrCreateSplitOutput(ReaderOutput mainOutput) { + if (sourceOutput == null) { + sourceOutput = mainOutput.createOutputForSplit(splitId); + } + return sourceOutput; + } + } } diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderOptions.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderOptions.java index 10eb58bd..508b347b 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderOptions.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SourceReaderOptions.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader; diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SplitsRecordIterator.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SplitsRecordIterator.java index 47dfd877..d7b7b766 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SplitsRecordIterator.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SplitsRecordIterator.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader; diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/AddSplitsTask.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/AddSplitsTask.java index 8f9fdc57..19b15b5b 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/AddSplitsTask.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/AddSplitsTask.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader.fetcher; diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/FetchTask.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/FetchTask.java index 7db615f5..aff21fdb 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/FetchTask.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/FetchTask.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader.fetcher; diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SingleThreadFetcherManager.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SingleThreadFetcherManager.java index 2745a369..bd5879f0 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SingleThreadFetcherManager.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SingleThreadFetcherManager.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader.fetcher; 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 703945db..d006bb07 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 @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader.fetcher; diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherManager.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherManager.java index 3b04bac5..61bada12 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherManager.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherManager.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader.fetcher; diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherTask.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherTask.java index 997cb65f..716d2e2b 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherTask.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherTask.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader.fetcher; 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 e8c1987f..89cf81b4 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 @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader.splitreader; diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/splitreader/SplitsAddition.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/splitreader/SplitsAddition.java index a6b6b4ec..ebd2330c 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/splitreader/SplitsAddition.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/splitreader/SplitsAddition.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader.splitreader; diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/splitreader/SplitsChange.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/splitreader/SplitsChange.java index 1af330bd..eae7ad05 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/splitreader/SplitsChange.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/splitreader/SplitsChange.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader.splitreader; diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/synchronization/FutureCompletingBlockingQueue.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/synchronization/FutureCompletingBlockingQueue.java index 407f3050..6a6dfacf 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/synchronization/FutureCompletingBlockingQueue.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/synchronization/FutureCompletingBlockingQueue.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader.synchronization; diff --git a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/synchronization/FutureNotifier.java b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/synchronization/FutureNotifier.java index 53e60f31..9330407a 100644 --- a/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/synchronization/FutureNotifier.java +++ b/flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/synchronization/FutureNotifier.java @@ -1,19 +1,19 @@ /* - 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. + * 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.connector.base.source.reader.synchronization; diff --git a/flink-core/src/main/java/org/apache/flink/api/common/eventtime/NoWatermarksGenerator.java b/flink-core/src/main/java/org/apache/flink/api/common/eventtime/NoWatermarksGenerator.java new file mode 100644 index 00000000..b20a13fe --- /dev/null +++ b/flink-core/src/main/java/org/apache/flink/api/common/eventtime/NoWatermarksGenerator.java @@ -0,0 +1,34 @@ +/* + * 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.common.eventtime; + +import org.apache.flink.annotation.Public; + +/** + * An implementation of a {@link WatermarkGenerator} that generates no Watermarks. + */ +@Public +public final class NoWatermarksGenerator implements WatermarkGenerator { + + @Override + public void onEvent(E event, long eventTimestamp, WatermarkOutput output) {} + + @Override + public void onPeriodicEmit(WatermarkOutput output) {} +} diff --git a/flink-core/src/main/java/org/apache/flink/api/common/eventtime/TimestampAssigner.java b/flink-core/src/main/java/org/apache/flink/api/common/eventtime/TimestampAssigner.java index c5bc828f..7265cea8 100644 --- a/flink-core/src/main/java/org/apache/flink/api/common/eventtime/TimestampAssigner.java +++ b/flink-core/src/main/java/org/apache/flink/api/common/eventtime/TimestampAssigner.java @@ -35,13 +35,20 @@ import org.apache.flink.annotation.Public; @FunctionalInterface public interface TimestampAssigner { + /** + * The value that is passed to {@link #extractTimestamp} when there is no previous timestamp + * attached to the record. + */ + long NO_TIMESTAMP = Long.MIN_VALUE; + /** * Assigns a timestamp to an element, in milliseconds since the Epoch. This is independent of * any particular time zone or calendar. * *

The method is passed the previously assigned timestamp of the element. * That previous timestamp may have been assigned from a previous assigner. If the element did - * not carry a timestamp before, this value is {@code Long.MIN_VALUE}. + * not carry a timestamp before, this value is {@link #NO_TIMESTAMP} (= {@code Long.MIN_VALUE}: + * {@value Long#MIN_VALUE}). * * @param element The element that the timestamp will be assigned to. * @param recordTimestamp The current internal timestamp of the element, diff --git a/flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkOutputMultiplexer.java b/flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkOutputMultiplexer.java index 83976e35..545f78a2 100644 --- a/flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkOutputMultiplexer.java +++ b/flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkOutputMultiplexer.java @@ -40,8 +40,8 @@ import static org.apache.flink.util.Preconditions.checkState; * #onPeriodicEmit()} is called will the deferred updates be combined and forwarded to the * underlying output. * - *

For registering a new multiplexed output, you must first call {@link #registerNewOutput()} - * and then call {@link #getImmediateOutput(int)} or {@link #getDeferredOutput(int)} with the output + *

For registering a new multiplexed output, you must first call {@link #registerNewOutput(String)} + * and then call {@link #getImmediateOutput(String)} or {@link #getDeferredOutput(String)} with the output * ID you get from that. You can get both an immediate and deferred output for a given output ID, * you can also call the getters multiple times. * @@ -57,16 +57,13 @@ public class WatermarkOutputMultiplexer { */ private final WatermarkOutput underlyingOutput; - /** The id to use for the next registered output. */ - private int nextOutputId = 0; - /** The combined watermark over the per-output watermarks. */ private long combinedWatermark = Long.MIN_VALUE; /** * Map view, to allow finding them when requesting the {@link WatermarkOutput} for a given id. */ - private final Map watermarkPerOutputId; + private final Map watermarkPerOutputId; /** * List of all watermark outputs, for efficient access. @@ -88,13 +85,23 @@ public class WatermarkOutputMultiplexer { * an output ID that can be used to get a deferred or immediate {@link WatermarkOutput} for that * output. */ - public int registerNewOutput() { - int newOutputId = nextOutputId; - nextOutputId++; - OutputState outputState = new OutputState(); - watermarkPerOutputId.put(newOutputId, outputState); + public void registerNewOutput(String id) { + final OutputState outputState = new OutputState(); + + final OutputState previouslyRegistered = watermarkPerOutputId.putIfAbsent(id, outputState); + checkState(previouslyRegistered == null, "Already contains an output for ID %s", id); + watermarkOutputs.add(outputState); - return newOutputId; + } + + public boolean unregisterOutput(String id) { + final OutputState output = watermarkPerOutputId.remove(id); + if (output != null) { + watermarkOutputs.remove(output); + return true; + } else { + return false; + } } /** @@ -103,12 +110,9 @@ public class WatermarkOutputMultiplexer { *

>See {@link WatermarkOutputMultiplexer} for a description of immediate and deferred * outputs. */ - public WatermarkOutput getImmediateOutput(int outputId) { - Preconditions.checkArgument( - watermarkPerOutputId.containsKey(outputId), - "no output registered under id " + outputId); - - OutputState outputState = watermarkPerOutputId.get(outputId); + public WatermarkOutput getImmediateOutput(String outputId) { + final OutputState outputState = watermarkPerOutputId.get(outputId); + Preconditions.checkArgument(outputState != null, "no output registered under id %s", outputId); return new ImmediateOutput(outputState); } @@ -118,12 +122,9 @@ public class WatermarkOutputMultiplexer { *

>See {@link WatermarkOutputMultiplexer} for a description of immediate and deferred * outputs. */ - public WatermarkOutput getDeferredOutput(int outputId) { - Preconditions.checkArgument( - watermarkPerOutputId.containsKey(outputId), - "no output registered under id " + outputId); - - OutputState outputState = watermarkPerOutputId.get(outputId); + public WatermarkOutput getDeferredOutput(String outputId) { + final OutputState outputState = watermarkPerOutputId.get(outputId); + Preconditions.checkArgument(outputState != null, "no output registered under id %s", outputId); return new DeferredOutput(outputState); } @@ -171,8 +172,8 @@ public class WatermarkOutputMultiplexer { * Per-output watermark state. */ private static class OutputState { - private volatile long watermark = Long.MIN_VALUE; - private volatile boolean idle = false; + private long watermark = Long.MIN_VALUE; + private boolean idle = false; /** * Returns the current watermark timestamp. This will throw {@link IllegalStateException} if @@ -191,12 +192,9 @@ public class WatermarkOutputMultiplexer { */ public boolean setWatermark(long watermark) { this.idle = false; - if (watermark > this.watermark) { - this.watermark = watermark; - return true; - } else { - return false; - } + final boolean updated = watermark > this.watermark; + this.watermark = Math.max(watermark, this.watermark); + return updated; } public boolean isIdle() { diff --git a/flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkStrategies.java b/flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkStrategies.java index 44b54747..880edc74 100644 --- a/flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkStrategies.java +++ b/flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkStrategies.java @@ -175,6 +175,14 @@ public final class WatermarkStrategies { return new WatermarkStrategies<>(new FromWatermarkGeneratorSupplier<>(generatorSupplier)); } + /** + * Starts building a watermark strategy that generates no watermarks at all. + * This may be useful in scenarios that do pure processing-time based stream processing. + */ + public static WatermarkStrategies noWatermarks() { + return new WatermarkStrategies<>((ctx) -> new NoWatermarksGenerator<>()); + } + // ------------------------------------------------------------------------ private static final class FromWatermarkGeneratorSupplier implements WatermarkStrategy { diff --git a/flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkStrategy.java b/flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkStrategy.java index 80277974..254afc16 100644 --- a/flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkStrategy.java +++ b/flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkStrategy.java @@ -31,7 +31,7 @@ import java.io.Serializable; * to workers during distributed execution. */ @Public -public interface WatermarkStrategy extends TimestampAssignerSupplier, WatermarkGeneratorSupplier{ +public interface WatermarkStrategy extends TimestampAssignerSupplier, WatermarkGeneratorSupplier { /** * Instantiates a {@link TimestampAssigner} for assigning timestamps according to this diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/Boundedness.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/Boundedness.java index 5b5c4a66..89e07c5d 100644 --- a/flink-core/src/main/java/org/apache/flink/api/connector/source/Boundedness.java +++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/Boundedness.java @@ -1,30 +1,30 @@ /* - 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. + * 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; -import org.apache.flink.annotation.Public; +import org.apache.flink.annotation.PublicEvolving; /** * The boundedness of a stream. A stream could either be "bounded" (a stream with finite records) or * "unbounded" (a stream with infinite records). */ -@Public +@PublicEvolving public enum Boundedness { /** * A BOUNDED stream is a stream with finite records. diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/ReaderInfo.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/ReaderInfo.java index f4a8f8d4..7e7e3f04 100644 --- a/flink-core/src/main/java/org/apache/flink/api/connector/source/ReaderInfo.java +++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/ReaderInfo.java @@ -1,24 +1,24 @@ /* - 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. + * 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; -import org.apache.flink.annotation.Public; +import org.apache.flink.annotation.PublicEvolving; import java.io.Serializable; import java.util.Objects; @@ -26,7 +26,7 @@ import java.util.Objects; /** * A container class hosting the information of a {@link SourceReader}. */ -@Public +@PublicEvolving public final class ReaderInfo implements Serializable { private static final long serialVersionUID = 1L; diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/ReaderOutput.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/ReaderOutput.java new file mode 100644 index 00000000..6a45d034 --- /dev/null +++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/ReaderOutput.java @@ -0,0 +1,117 @@ +/* + * 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; + +import org.apache.flink.annotation.PublicEvolving; +import org.apache.flink.api.common.eventtime.TimestampAssigner; +import org.apache.flink.api.common.eventtime.Watermark; + +/** + * The interface provided by the Flink runtime to the {@link SourceReader} to emit records, and + * optionally watermarks, to downstream operators for message processing. + * + *

The {@code ReaderOutput} is a {@link SourceOutput} and can be used directly to emit the stream + * of events from the source. This is recommended for source where the SourceReader processes only a + * single split, or where NO split-specific characteristics are required (like per-split watermarks + * and idleness, split-specific event-time skew handling, etc.). + * As a special case, this is true for sources that are purely supporting bounded/batch data processing. + * + *

For most streaming sources, the {@code SourceReader} should use split-specific outputs, to allow + * the processing logic to run per-split watermark generators, idleness detection, etc. + * To create a split-specific {@code SourceOutput} use the {@link ReaderOutput#createOutputForSplit(String)} + * method, using the Source Split's ID. Make sure to release the output again once the source has finished + * processing that split. + */ +@PublicEvolving +public interface ReaderOutput extends SourceOutput { + + /** + * Emit a record without a timestamp. + * + *

Use this method if the source system does not have a notion of records with timestamps. + * + *

The events later pass through a {@link TimestampAssigner}, which attaches a timestamp + * to the event based on the event's contents. For example a file source with JSON records would not + * have a generic timestamp from the file reading and JSON parsing process, and thus use this + * method to produce initially a record without a timestamp. The {@code TimestampAssigner} in + * the next step would be used to extract timestamp from a field of the JSON object. + * + * @param record the record to emit. + */ + @Override + void collect(T record); + + /** + * Emit a record with a timestamp. + * + *

Use this method if the source system has timestamps attached to records. Typical examples + * would be Logs, PubSubs, or Message Queues, like Kafka or Kinesis, which store a timestamp with + * each event. + * + *

The events typically still pass through a {@link TimestampAssigner}, which may decide to + * either use this source-provided timestamp, or replace it with a timestamp stored within the + * event (for example if the event was a JSON object one could configure aTimestampAssigner that + * extracts one of the object's fields and uses that as a timestamp). + * + * @param record the record to emit. + * @param timestamp the timestamp of the record. + */ + @Override + void collect(T record, long timestamp); + + /** + * Emits the given watermark. + * + *

Emitting a watermark also implicitly marks the stream as active, ending + * previously marked idleness. + */ + @Override + void emitWatermark(Watermark watermark); + + /** + * Marks this output as idle, meaning that downstream operations do not + * wait for watermarks from this output. + * + *

An output becomes active again as soon as the next watermark is emitted. + */ + @Override + void markIdle(); + + /** + * Creates a {@code SourceOutput} for a specific Source Split. Use these outputs if you want to + * run split-local logic, like watermark generation. + * + *

If a split-local output was already created for this split-ID, the method will return that instance, + * so that only one split-local output exists per split-ID. + * + *

IMPORTANT: After the split has been finished, it is crucial to release the created + * output again. Otherwise it will continue to contribute to the watermark generation like a + * perpetually stalling source split, and may hold back the watermark indefinitely. + * + * @see #releaseOutputForSplit(String) + */ + SourceOutput createOutputForSplit(String splitId); + + /** + * Releases the {@code SourceOutput} created for the split with the given ID. + * + * @see #createOutputForSplit(String) + */ + void releaseOutputForSplit(String splitId); +} 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 1b8a1ca1..fe81db86 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 @@ -1,24 +1,24 @@ /* - 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. + * 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; -import org.apache.flink.annotation.Public; +import org.apache.flink.annotation.PublicEvolving; import org.apache.flink.core.io.SimpleVersionedSerializer; import java.io.IOException; @@ -33,7 +33,7 @@ import java.io.Serializable; * @param The type of splits handled by the source. * @param The type of the enumerator checkpoints. */ -@Public +@PublicEvolving public interface Source extends Serializable { /** diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceEvent.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceEvent.java index 2377bb76..d07c660c 100644 --- a/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceEvent.java +++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceEvent.java @@ -1,31 +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. + * 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; -import org.apache.flink.annotation.Public; +import org.apache.flink.annotation.PublicEvolving; import java.io.Serializable; /** * An base class for the events passed between the SourceReaders and Enumerators. */ -@Public +@PublicEvolving public interface SourceEvent extends Serializable { } diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceOutput.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceOutput.java index 4d9f065e..02d41f5a 100644 --- a/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceOutput.java +++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceOutput.java @@ -1,45 +1,67 @@ /* - 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. + * 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; -import org.apache.flink.annotation.Public; +import org.apache.flink.annotation.PublicEvolving; +import org.apache.flink.api.common.eventtime.TimestampAssigner; import org.apache.flink.api.common.eventtime.WatermarkOutput; /** - * The interface provided by Flink task to the {@link SourceReader} to emit records - * to downstream operators for message processing. + * The {@code SourceOutput} is the gateway for a {@link SourceReader}) to emit the produced + * records and watermarks. + * + *

A {@code SourceReader} may have multiple SourceOutputs, scoped to individual Source Splits. That + * way, streams of events from different splits can be identified and treated separately, for example + * for watermark generation, or event-time skew handling. */ -@Public +@PublicEvolving public interface SourceOutput extends WatermarkOutput { /** - * Emit a record without a timestamp. Equivalent to {@link #collect(Object, long) collect(timestamp, null)}; + * Emit a record without a timestamp. + * + *

Use this method if the source system does not have a notion of records with timestamps. + * + *

The events later pass through a {@link TimestampAssigner}, which attaches a timestamp + * to the event based on the event's contents. For example a file source with JSON records would not + * have a generic timestamp from the file reading and JSON parsing process, and thus use this + * method to produce initially a record without a timestamp. The {@code TimestampAssigner} in + * the next step would be used to extract timestamp from a field of the JSON object. * * @param record the record to emit. */ - void collect(T record) throws Exception; + void collect(T record); /** - * Emit a record with timestamp. + * Emit a record with a timestamp. + * + *

Use this method if the source system has timestamps attached to records. Typical examples + * would be Logs, PubSubs, or Message Queues, like Kafka or Kinesis, which store a timestamp with + * each event. + * + *

The events typically still pass through a {@link TimestampAssigner}, which may decide to + * either use this source-provided timestamp, or replace it with a timestamp stored within the + * event (for example if the event was a JSON object one could configure aTimestampAssigner that + * extracts one of the object's fields and uses that as a timestamp). * * @param record the record to emit. * @param timestamp the timestamp of the record. */ - void collect(T record, long timestamp) throws Exception; + void collect(T record, long timestamp); } 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 66a12297..3e623dd7 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 @@ -1,24 +1,24 @@ /* - 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. + * 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; -import org.apache.flink.annotation.Public; +import org.apache.flink.annotation.PublicEvolving; import org.apache.flink.core.io.InputStatus; import java.util.List; @@ -31,7 +31,7 @@ import java.util.concurrent.CompletableFuture; * @param The type of the record emitted by this source reader. * @param The type of the the source splits. */ -@Public +@PublicEvolving public interface SourceReader extends AutoCloseable { /** @@ -51,7 +51,7 @@ public interface SourceReader extends AutoCloseab * * @return The InputStatus of the SourceReader after the method invocation. */ - InputStatus pollNext(SourceOutput sourceOutput) throws Exception; + InputStatus pollNext(ReaderOutput output) throws Exception; /** * Checkpoint on the state of the source. 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 2936649e..658034b7 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 @@ -1,30 +1,30 @@ /* - 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. + * 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; -import org.apache.flink.annotation.Public; +import org.apache.flink.annotation.PublicEvolving; import org.apache.flink.metrics.MetricGroup; /** * The class that expose some context from runtime to the {@link SourceReader}. */ -@Public +@PublicEvolving public interface SourceReaderContext { /** diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceSplit.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceSplit.java index d317f0ec..95a5f8dc 100644 --- a/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceSplit.java +++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/SourceSplit.java @@ -1,29 +1,29 @@ /* - 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. + * 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; -import org.apache.flink.annotation.Public; +import org.apache.flink.annotation.PublicEvolving; /** * An interface for all the Split types to extend. */ -@Public +@PublicEvolving public interface SourceSplit { /** 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 16b39389..1e429bb2 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 @@ -1,24 +1,24 @@ /* - 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. + * 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; -import org.apache.flink.annotation.Public; +import org.apache.flink.annotation.PublicEvolving; import java.io.IOException; import java.util.List; @@ -28,7 +28,7 @@ import java.util.List; * 1. discover the splits for the {@link SourceReader} to read. * 2. assign the splits to the source reader. */ -@Public +@PublicEvolving public interface SplitEnumerator extends AutoCloseable { /** diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/SplitEnumeratorContext.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/SplitEnumeratorContext.java index db6ccad2..5aee6dd7 100644 --- a/flink-core/src/main/java/org/apache/flink/api/connector/source/SplitEnumeratorContext.java +++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/SplitEnumeratorContext.java @@ -1,24 +1,24 @@ /* - 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. + * 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; -import org.apache.flink.annotation.Public; +import org.apache.flink.annotation.PublicEvolving; import org.apache.flink.metrics.MetricGroup; import java.util.Map; @@ -34,7 +34,7 @@ import java.util.function.BiConsumer; * * @param the type of the splits. */ -@Public +@PublicEvolving public interface SplitEnumeratorContext { MetricGroup metricGroup(); diff --git a/flink-core/src/main/java/org/apache/flink/api/connector/source/SplitsAssignment.java b/flink-core/src/main/java/org/apache/flink/api/connector/source/SplitsAssignment.java index aad3577d..63317881 100644 --- a/flink-core/src/main/java/org/apache/flink/api/connector/source/SplitsAssignment.java +++ b/flink-core/src/main/java/org/apache/flink/api/connector/source/SplitsAssignment.java @@ -1,24 +1,24 @@ /* - 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. + * 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; -import org.apache.flink.annotation.Public; +import org.apache.flink.annotation.PublicEvolving; import java.util.List; import java.util.Map; @@ -29,7 +29,7 @@ import java.util.Map; *

The assignment is always incremental. In another word, splits in the assignment are simply * added to the existing assignment. */ -@Public +@PublicEvolving public final class SplitsAssignment { private final Map> assignment; diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStreamSource.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStreamSource.java index 4e0d6266..9fb2c26c 100644 --- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStreamSource.java +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStreamSource.java @@ -18,6 +18,7 @@ package org.apache.flink.streaming.api.datastream; import org.apache.flink.annotation.Public; +import org.apache.flink.api.common.eventtime.WatermarkStrategy; import org.apache.flink.api.common.operators.util.OperatorValidationUtils; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.connector.source.Source; @@ -37,9 +38,15 @@ public class DataStreamSource extends SingleOutputStreamOperator { boolean isParallel; - public DataStreamSource(StreamExecutionEnvironment environment, - TypeInformation outTypeInfo, StreamSource operator, - boolean isParallel, String sourceName) { + /** + * The constructor used to create legacy sources. + */ + public DataStreamSource( + StreamExecutionEnvironment environment, + TypeInformation outTypeInfo, + StreamSource operator, + boolean isParallel, + String sourceName) { super(environment, new LegacySourceTransformation<>(sourceName, operator, outTypeInfo, environment.getParallelism())); this.isParallel = isParallel; @@ -48,20 +55,27 @@ public class DataStreamSource extends SingleOutputStreamOperator { } } + /** + * Constructor for "deep" sources that manually set up (one or more) custom configured complex operators. + */ public DataStreamSource(SingleOutputStreamOperator operator) { super(operator.environment, operator.getTransformation()); this.isParallel = true; } + /** + * Constructor for new Sources (FLIP-27). + */ public DataStreamSource( StreamExecutionEnvironment environment, Source source, + WatermarkStrategy timestampsAndWatermarks, TypeInformation outTypeInfo, String sourceName) { super(environment, new SourceTransformation<>( sourceName, - new SourceOperatorFactory<>(source), + new SourceOperatorFactory<>(source, timestampsAndWatermarks), outTypeInfo, environment.getParallelism())); } diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/SingleOutputStreamOperator.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/SingleOutputStreamOperator.java index 669fa9e7..6a70803f 100644 --- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/SingleOutputStreamOperator.java +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/SingleOutputStreamOperator.java @@ -55,7 +55,7 @@ public class SingleOutputStreamOperator extends DataStream { * we can catch the case when a side output with a matching id is requested for a different * type because this would lead to problems at runtime. */ - private Map, TypeInformation> requestedSideOutputs = new HashMap<>(); + private Map, TypeInformation> requestedSideOutputs = new HashMap<>(); private boolean wasSplitApplied = false; diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java index 680e285d..a47eaede 100644 --- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java @@ -17,6 +17,7 @@ package org.apache.flink.streaming.api.environment; +import org.apache.flink.annotation.Experimental; import org.apache.flink.annotation.Internal; import org.apache.flink.annotation.Public; import org.apache.flink.annotation.PublicEvolving; @@ -24,6 +25,7 @@ import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.InvalidProgramException; import org.apache.flink.api.common.JobExecutionResult; import org.apache.flink.api.common.cache.DistributedCache; +import org.apache.flink.api.common.eventtime.WatermarkStrategy; import org.apache.flink.api.common.functions.InvalidTypesException; import org.apache.flink.api.common.io.FileInputFormat; import org.apache.flink.api.common.io.FilePathFilter; @@ -1589,7 +1591,6 @@ public class StreamExecutionEnvironment { * the user defined type information for the stream * @return the data stream constructed */ - @SuppressWarnings("unchecked") public DataStreamSource addSource(SourceFunction function, String sourceName, TypeInformation typeInfo) { TypeInformation resolvedTypeInfo = getTypeInfo(function, sourceName, SourceFunction.class, typeInfo); @@ -1613,9 +1614,12 @@ public class StreamExecutionEnvironment { * type of the returned stream * @return the data stream constructed */ - @PublicEvolving - public DataStreamSource continuousSource(Source source, String sourceName) { - return continuousSource(source, sourceName, null); + @Experimental + public DataStreamSource continuousSource( + Source source, + WatermarkStrategy timestampsAndWatermarks, + String sourceName) { + return continuousSource(source, timestampsAndWatermarks, sourceName, null); } /** @@ -1631,13 +1635,21 @@ public class StreamExecutionEnvironment { * the user defined type information for the stream * @return the data stream constructed */ - @PublicEvolving + @Experimental public DataStreamSource continuousSource( Source source, + WatermarkStrategy timestampsAndWatermarks, String sourceName, TypeInformation typeInfo) { - TypeInformation resolvedTypeInfo = getTypeInfo(source, sourceName, Source.class, typeInfo); - return new DataStreamSource<>(this, source, resolvedTypeInfo, sourceName); + + final TypeInformation resolvedTypeInfo = getTypeInfo(source, sourceName, Source.class, typeInfo); + + return new DataStreamSource<>( + this, + checkNotNull(source, "source"), + checkNotNull(timestampsAndWatermarks, "timestampsAndWatermarks"), + checkNotNull(resolvedTypeInfo), + checkNotNull(sourceName)); } /** 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 5d4b2d62..9ac80d3c 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 @@ -19,11 +19,12 @@ package org.apache.flink.streaming.api.operators; import org.apache.flink.annotation.Internal; import org.apache.flink.annotation.VisibleForTesting; +import org.apache.flink.api.common.eventtime.WatermarkStrategy; import org.apache.flink.api.common.state.ListState; import org.apache.flink.api.common.state.ListStateDescriptor; import org.apache.flink.api.common.typeutils.base.array.BytePrimitiveArraySerializer; +import org.apache.flink.api.connector.source.ReaderOutput; import org.apache.flink.api.connector.source.SourceEvent; -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; @@ -38,8 +39,10 @@ import org.apache.flink.runtime.source.event.ReaderRegistrationEvent; import org.apache.flink.runtime.source.event.SourceEventWrapper; 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.runtime.io.PushingAsyncDataInput; +import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService; import org.apache.flink.util.CollectionUtil; import java.util.List; @@ -81,30 +84,47 @@ public class SourceOperator /** The event gateway through which this operator talks to its coordinator. */ private final OperatorEventGateway operatorEventGateway; - // ---- lazily initialized fields ---- + /** The factory for timestamps and watermark generators. */ + private final WatermarkStrategy watermarkStrategy; + + // ---- lazily initialized fields (these fields are the "hot" fields) ---- /** The source reader that does most of the work. */ private SourceReader sourceReader; + private ReaderOutput currentMainOutput; + + private DataOutput lastInvokedOutput; + /** The state that holds the currently assigned splits. */ private ListState readerState; + /** The event time and watermarking logic. Ideally this would be eagerly passed into this operator, + * but we currently need to instantiate this lazily, because the metric groups exist only later. */ + private TimestampsAndWatermarks eventTimeLogic; + public SourceOperator( Function> readerFactory, OperatorEventGateway operatorEventGateway, - SimpleVersionedSerializer splitSerializer) { + SimpleVersionedSerializer splitSerializer, + WatermarkStrategy watermarkStrategy, + ProcessingTimeService timeService) { this.readerFactory = checkNotNull(readerFactory); this.operatorEventGateway = checkNotNull(operatorEventGateway); this.splitSerializer = checkNotNull(splitSerializer); + this.watermarkStrategy = checkNotNull(watermarkStrategy); + this.processingTimeService = timeService; } @Override public void open() throws Exception { + final MetricGroup metricGroup = getMetricGroup(); + final SourceReaderContext context = new SourceReaderContext() { @Override public MetricGroup metricGroup() { - return getRuntimeContext().getMetricGroup(); + return metricGroup; } @Override @@ -113,6 +133,15 @@ public class SourceOperator } }; + // in the future when we support both batch and streaming modes for the source operator, + // and when this one is migrated to the "eager initialization" operator (StreamOperatorV2), + // then we should evaluate this during operator construction. + eventTimeLogic = TimestampsAndWatermarks.createStreamingEventTimeLogic( + watermarkStrategy, + metricGroup, + getProcessingTimeService(), + getExecutionConfig().getAutoWatermarkInterval()); + sourceReader = readerFactory.apply(context); // restore the state if necessary. @@ -125,12 +154,31 @@ public class SourceOperator sourceReader.start(); // Register the reader to the coordinator. registerReader(); + + eventTimeLogic.startPeriodicWatermarkEmits(); + } + + @Override + public void close() throws Exception { + eventTimeLogic.stopPeriodicWatermarkEmits(); + super.close(); } @Override - @SuppressWarnings("unchecked") public InputStatus emitNext(DataOutput output) throws Exception { - return sourceReader.pollNext((SourceOutput) output); + // guarding an assumptions we currently make due to the fact that certain classes + // assume a constant output + assert lastInvokedOutput == output || lastInvokedOutput == null; + + // short circuit the common case (every invocation except the first) + if (currentMainOutput != null) { + return sourceReader.pollNext(currentMainOutput); + } + + // this creates a batch or streaming output based on the runtime mode + currentMainOutput = eventTimeLogic.createMainOutput(output); + lastInvokedOutput = output; + return sourceReader.pollNext(currentMainOutput); } @Override 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 c30a0a74..d1636cdc 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 @@ -18,6 +18,7 @@ package org.apache.flink.streaming.api.operators; +import org.apache.flink.api.common.eventtime.WatermarkStrategy; import org.apache.flink.api.connector.source.Source; import org.apache.flink.api.connector.source.SourceReader; import org.apache.flink.api.connector.source.SourceReaderContext; @@ -27,29 +28,40 @@ import org.apache.flink.runtime.jobgraph.OperatorID; import org.apache.flink.runtime.operators.coordination.OperatorCoordinator; 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 static org.apache.flink.util.Preconditions.checkNotNull; + /** * The Factory class for {@link SourceOperator}. */ public class SourceOperatorFactory extends AbstractStreamOperatorFactory - implements CoordinatedOperatorFactory { + implements CoordinatedOperatorFactory, ProcessingTimeServiceAware { private static final long serialVersionUID = 1L; /** The {@link Source} to create the {@link SourceOperator}. */ private final Source source; + /** The event time setup (timestamp assigners, watermark generators, etc.). */ + private final WatermarkStrategy watermarkStrategy; + /** The number of worker thread for the source coordinator. */ private final int numCoordinatorWorkerThread; - public SourceOperatorFactory(Source source) { - this(source, 1); + public SourceOperatorFactory(Source source, WatermarkStrategy watermarkStrategy) { + this(source, watermarkStrategy, 1); } - public SourceOperatorFactory(Source source, int numCoordinatorWorkerThread) { - this.source = source; + public SourceOperatorFactory( + Source source, + WatermarkStrategy watermarkStrategy, + int numCoordinatorWorkerThread) { + this.source = checkNotNull(source); + this.watermarkStrategy = checkNotNull(watermarkStrategy); this.numCoordinatorWorkerThread = numCoordinatorWorkerThread; } @@ -61,7 +73,9 @@ public class SourceOperatorFactory extends AbstractStreamOperatorFactory sourceOperator = instantiateSourceOperator( source::createReader, gateway, - source.getSplitSerializer()); + source.getSplitSerializer(), + watermarkStrategy, + parameters.getProcessingTimeService()); sourceOperator.setup(parameters.getContainingTask(), parameters.getStreamConfig(), parameters.getOutput()); parameters.getOperatorEventDispatcher().registerEventHandler(operatorId, sourceOperator); @@ -99,7 +113,9 @@ public class SourceOperatorFactory extends AbstractStreamOperatorFactory SourceOperator instantiateSourceOperator( Function> readerFactory, OperatorEventGateway eventGateway, - SimpleVersionedSerializer splitSerializer) { + SimpleVersionedSerializer splitSerializer, + WatermarkStrategy watermarkStrategy, + ProcessingTimeService timeService) { // jumping through generics hoops: cast the generics away to then cast them back more strictly typed final Function> typedReaderFactory = @@ -110,6 +126,8 @@ public class SourceOperatorFactory extends AbstractStreamOperatorFactory( typedReaderFactory, eventGateway, - typedSplitSerializer); + typedSplitSerializer, + watermarkStrategy, + timeService); } } diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/StreamOperatorFactoryUtil.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/StreamOperatorFactoryUtil.java index fb0917f9..8adb1c1d 100644 --- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/StreamOperatorFactoryUtil.java +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/StreamOperatorFactoryUtil.java @@ -26,6 +26,7 @@ import org.apache.flink.streaming.runtime.tasks.ProcessingTimeServiceAware; import org.apache.flink.streaming.runtime.tasks.StreamTask; import java.util.Optional; +import java.util.function.Supplier; /** * A utility to instantiate new operators with a given factory. @@ -51,13 +52,18 @@ public class StreamOperatorFactoryUtil { MailboxExecutor mailboxExecutor = containingTask.getMailboxExecutorFactory().createExecutor(configuration.getChainIndex()); if (operatorFactory instanceof YieldingOperatorFactory) { - ((YieldingOperatorFactory) operatorFactory).setMailboxExecutor(mailboxExecutor); + ((YieldingOperatorFactory) operatorFactory).setMailboxExecutor(mailboxExecutor); } - ProcessingTimeService processingTimeService = null; + final Supplier processingTimeServiceFactory = + () -> containingTask.getProcessingTimeServiceFactory().createProcessingTimeService(mailboxExecutor); + + final ProcessingTimeService processingTimeService; if (operatorFactory instanceof ProcessingTimeServiceAware) { - processingTimeService = containingTask.getProcessingTimeServiceFactory().createProcessingTimeService(mailboxExecutor); + processingTimeService = processingTimeServiceFactory.get(); ((ProcessingTimeServiceAware) operatorFactory).setProcessingTimeService(processingTimeService); + } else { + processingTimeService = null; } // TODO: what to do with ProcessingTimeServiceAware? @@ -66,7 +72,7 @@ public class StreamOperatorFactoryUtil { containingTask, configuration, output, - processingTimeService, + processingTimeService != null ? () -> processingTimeService : processingTimeServiceFactory, operatorEventDispatcher)); return new Tuple2<>(op, Optional.ofNullable(processingTimeService)); } diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/StreamOperatorParameters.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/StreamOperatorParameters.java index 70df0e4b..3213e8ac 100644 --- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/StreamOperatorParameters.java +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/StreamOperatorParameters.java @@ -25,6 +25,10 @@ import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService; import org.apache.flink.streaming.runtime.tasks.StreamTask; +import javax.annotation.Nullable; + +import java.util.function.Supplier; + /** * Helper class to construct {@link AbstractStreamOperatorV2}. Wraps couple of internal parameters * to simplify for users construction of classes extending {@link AbstractStreamOperatorV2} and to @@ -37,19 +41,23 @@ public class StreamOperatorParameters { private final StreamTask containingTask; private final StreamConfig config; private final Output> output; - private final ProcessingTimeService processingTimeService; + private final Supplier processingTimeServiceFactory; private final OperatorEventDispatcher operatorEventDispatcher; + /** The ProcessingTimeService, lazily created, but cached so that we don't create more than one. */ + @Nullable + private ProcessingTimeService processingTimeService; + public StreamOperatorParameters( StreamTask containingTask, StreamConfig config, Output> output, - ProcessingTimeService processingTimeService, + Supplier processingTimeServiceFactory, OperatorEventDispatcher operatorEventDispatcher) { this.containingTask = containingTask; this.config = config; this.output = output; - this.processingTimeService = processingTimeService; + this.processingTimeServiceFactory = processingTimeServiceFactory; this.operatorEventDispatcher = operatorEventDispatcher; } @@ -66,6 +74,9 @@ public class StreamOperatorParameters { } public ProcessingTimeService getProcessingTimeService() { + if (processingTimeService == null) { + processingTimeService = processingTimeServiceFactory.get(); + } return processingTimeService; } diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/BatchTimestampsAndWatermarks.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/BatchTimestampsAndWatermarks.java new file mode 100644 index 00000000..135cad92 --- /dev/null +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/BatchTimestampsAndWatermarks.java @@ -0,0 +1,126 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.streaming.api.operators.source; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.api.common.eventtime.TimestampAssigner; +import org.apache.flink.api.common.eventtime.Watermark; +import org.apache.flink.api.connector.source.ReaderOutput; +import org.apache.flink.api.connector.source.SourceOutput; +import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.streaming.runtime.tasks.ExceptionInChainedOperatorException; + +import static org.apache.flink.util.Preconditions.checkNotNull; + +/** + * An implementation of {@link TimestampsAndWatermarks} to be used during batch execution of a + * program. Batch execution has no watermarks, so all watermark related operations in this + * implementation are no-ops. + * + * @param The type of the emitted records. + */ +@Internal +public class BatchTimestampsAndWatermarks implements TimestampsAndWatermarks { + + private final TimestampAssigner timestamps; + + /** + * Creates a new BatchTimestampsAndWatermarks with the given TimestampAssigner. + */ + public BatchTimestampsAndWatermarks(TimestampAssigner timestamps) { + this.timestamps = checkNotNull(timestamps); + } + + @Override + public ReaderOutput createMainOutput(PushingAsyncDataInput.DataOutput output) { + checkNotNull(output); + return new TimestampsOnlyOutput<>(output, timestamps); + } + + @Override + public void startPeriodicWatermarkEmits() { + // no periodic watermarks in batch processing + } + + @Override + public void stopPeriodicWatermarkEmits() { + // no periodic watermarks in batch processing + } + + // ------------------------------------------------------------------------ + + /** + * A simple implementation of {@link SourceOutput} and {@link ReaderOutput} that extracts + * timestamps but has no watermarking logic. Because only watermarking logic has state per + * Source Split, the same instance gets shared across all Source Splits. + * + * @param The type of the emitted records. + */ + private static final class TimestampsOnlyOutput implements ReaderOutput { + + private final PushingAsyncDataInput.DataOutput output; + private final TimestampAssigner timestampAssigner; + + private TimestampsOnlyOutput( + PushingAsyncDataInput.DataOutput output, + TimestampAssigner timestampAssigner) { + + this.output = output; + this.timestampAssigner = timestampAssigner; + } + + @Override + public void collect(T record) { + collect(record, TimestampAssigner.NO_TIMESTAMP); + } + + @Override + public void collect(T record, long timestamp) { + try { + output.emitRecord(new StreamRecord<>(record, timestampAssigner.extractTimestamp(record, timestamp))); + } catch (ExceptionInChainedOperatorException e) { + throw e; + } catch (Exception e) { + throw new ExceptionInChainedOperatorException(e); + } + } + + @Override + public void emitWatermark(Watermark watermark) { + // do nothing, this does not forward any watermarks manually emitted by the source directly + } + + @Override + public void markIdle() { + // do nothing, because without watermarks there is no idleness + } + + @Override + public SourceOutput createOutputForSplit(String splitId) { + // we don't need per-partition instances, because we do not generate watermarks + return this; + } + + @Override + public void releaseOutputForSplit(String splitId) { + // nothing to release, because we do not create per-partition instances + } + } +} diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/SourceOutputWithWatermarks.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/SourceOutputWithWatermarks.java new file mode 100644 index 00000000..3a8396e3 --- /dev/null +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/SourceOutputWithWatermarks.java @@ -0,0 +1,179 @@ +/* + * 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.streaming.api.operators.source; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.api.common.eventtime.TimestampAssigner; +import org.apache.flink.api.common.eventtime.Watermark; +import org.apache.flink.api.common.eventtime.WatermarkGenerator; +import org.apache.flink.api.common.eventtime.WatermarkOutput; +import org.apache.flink.api.connector.source.SourceOutput; +import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput; +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.streaming.runtime.tasks.ExceptionInChainedOperatorException; + +import static org.apache.flink.util.Preconditions.checkNotNull; + +/** + * Implementation of the SourceOutput. The records emitted to this output are pushed into a given + * {@link PushingAsyncDataInput.DataOutput}. The watermarks are pushed into the same output, or + * into a separate {@link WatermarkOutput}, if one is provided. + * + *

Periodic Watermarks

+ * + *

This output does not implement automatic periodic watermark emission. The + * method {@link SourceOutputWithWatermarks#emitPeriodicWatermark()} needs to be called periodically. + * + *

Note on Performance Considerations

+ * + *

The methods {@link SourceOutput#collect(Object)} and {@link SourceOutput#collect(Object, long)} + * are highly performance-critical (part of the hot loop). To make the code as JIT friendly as possible, + * we want to have only a single implementation of these two methods, across all classes. + * That way, the JIT compiler can de-virtualize (and inline) them better. + * + *

Currently, we have one implementation of these methods in the batch case (see class + * {@link BatchTimestampsAndWatermarks}) and one for the streaming case (this class). When the JVM + * is dedicated to a single job (or type of job) only one of these classes will be loaded. In mixed + * job setups, we still have a bimorphic method (rather than a poly/-/mega-morphic method). + * + * @param The type of emitted records. + */ +@Internal +public class SourceOutputWithWatermarks implements SourceOutput { + + private final PushingAsyncDataInput.DataOutput recordsOutput; + + private final TimestampAssigner timestampAssigner; + + private final WatermarkGenerator watermarkGenerator; + + private final WatermarkOutput onEventWatermarkOutput; + + private final WatermarkOutput periodicWatermarkOutput; + + /** + * Creates a new SourceOutputWithWatermarks that emits records to the given DataOutput + * and watermarks to the (possibly different) WatermarkOutput. + */ + protected SourceOutputWithWatermarks( + PushingAsyncDataInput.DataOutput recordsOutput, + WatermarkOutput onEventWatermarkOutput, + WatermarkOutput periodicWatermarkOutput, + TimestampAssigner timestampAssigner, + WatermarkGenerator watermarkGenerator) { + + this.recordsOutput = checkNotNull(recordsOutput); + this.onEventWatermarkOutput = checkNotNull(onEventWatermarkOutput); + this.periodicWatermarkOutput = checkNotNull(periodicWatermarkOutput); + this.timestampAssigner = checkNotNull(timestampAssigner); + this.watermarkGenerator = checkNotNull(watermarkGenerator); + } + + // ------------------------------------------------------------------------ + // SourceOutput Methods + // + // Note that the two methods below are final, as a partial enforcement + // of the performance design goal mentioned in the class-level comment. + // ------------------------------------------------------------------------ + + @Override + public final void collect(T record) { + collect(record, TimestampAssigner.NO_TIMESTAMP); + } + + @Override + public final void collect(T record, long timestamp) { + try { + final long assignedTimestamp = timestampAssigner.extractTimestamp(record, timestamp); + + // IMPORTANT: The event must be emitted before the watermark generator is called. + recordsOutput.emitRecord(new StreamRecord<>(record, assignedTimestamp)); + watermarkGenerator.onEvent(record, assignedTimestamp, onEventWatermarkOutput); + } catch (ExceptionInChainedOperatorException e) { + throw e; + } catch (Exception e) { + throw new ExceptionInChainedOperatorException(e); + } + } + + // ------------------------------------------------------------------------ + // WatermarkOutput Methods + // + // These two methods are final as well, to enforce the contract that the + // watermarks from emitWatermark(Watermark) go to the same output as the + // watermarks from the watermarkGenerator.onEvent(...) calls in the collect(...) + // methods. + // ------------------------------------------------------------------------ + + @Override + public final void emitWatermark(Watermark watermark) { + onEventWatermarkOutput.emitWatermark(watermark); + } + + @Override + public final void markIdle() { + onEventWatermarkOutput.markIdle(); + } + + public final void emitPeriodicWatermark() { + watermarkGenerator.onPeriodicEmit(periodicWatermarkOutput); + } + + // ------------------------------------------------------------------------ + // Factories + // ------------------------------------------------------------------------ + + /** + * Creates a new SourceOutputWithWatermarks that emits records to the given DataOutput + * and watermarks to the (possibly different) WatermarkOutput. + */ + public static SourceOutputWithWatermarks createWithSameOutputs( + PushingAsyncDataInput.DataOutput recordsAndWatermarksOutput, + TimestampAssigner timestampAssigner, + WatermarkGenerator watermarkGenerator) { + + final WatermarkOutput watermarkOutput = new WatermarkToDataOutput(recordsAndWatermarksOutput); + + return new SourceOutputWithWatermarks<>( + recordsAndWatermarksOutput, + watermarkOutput, + watermarkOutput, + timestampAssigner, + watermarkGenerator); + } + + /** + * Creates a new SourceOutputWithWatermarks that emits records to the given DataOutput + * and watermarks to the different WatermarkOutputs. + */ + public static SourceOutputWithWatermarks createWithSeparateOutputs( + PushingAsyncDataInput.DataOutput recordsOutput, + WatermarkOutput onEventWatermarkOutput, + WatermarkOutput periodicWatermarkOutput, + TimestampAssigner timestampAssigner, + WatermarkGenerator watermarkGenerator) { + + return new SourceOutputWithWatermarks<>( + recordsOutput, + onEventWatermarkOutput, + periodicWatermarkOutput, + timestampAssigner, + watermarkGenerator); + } +} diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/StreamingTimestampsAndWatermarks.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/StreamingTimestampsAndWatermarks.java new file mode 100644 index 00000000..af51f414 --- /dev/null +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/StreamingTimestampsAndWatermarks.java @@ -0,0 +1,247 @@ +/* + * 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.streaming.api.operators.source; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.api.common.eventtime.TimestampAssigner; +import org.apache.flink.api.common.eventtime.WatermarkGenerator; +import org.apache.flink.api.common.eventtime.WatermarkGeneratorSupplier; +import org.apache.flink.api.common.eventtime.WatermarkOutput; +import org.apache.flink.api.common.eventtime.WatermarkOutputMultiplexer; +import org.apache.flink.api.connector.source.ReaderOutput; +import org.apache.flink.api.connector.source.SourceOutput; +import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput; +import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService; + +import javax.annotation.Nullable; + +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.ScheduledFuture; + +import static org.apache.flink.util.Preconditions.checkState; + +/** + * An implementation of timestamp extraction and watermark generation logic for streaming sources. + * + * @param The type of the emitted records. + */ +@Internal +public class StreamingTimestampsAndWatermarks implements TimestampsAndWatermarks { + + private final TimestampAssigner timestampAssigner; + + private final WatermarkGeneratorSupplier watermarksFactory; + + private final WatermarkGeneratorSupplier.Context watermarksContext; + + private final ProcessingTimeService timeService; + + private final long periodicWatermarkInterval; + + @Nullable + private SplitLocalOutputs currentPerSplitOutputs; + + @Nullable + private StreamingReaderOutput currentMainOutput; + + @Nullable + private ScheduledFuture periodicEmitHandle; + + public StreamingTimestampsAndWatermarks( + TimestampAssigner timestampAssigner, + WatermarkGeneratorSupplier watermarksFactory, + WatermarkGeneratorSupplier.Context watermarksContext, + ProcessingTimeService timeService, + Duration periodicWatermarkInterval) { + + this.timestampAssigner = timestampAssigner; + this.watermarksFactory = watermarksFactory; + this.watermarksContext = watermarksContext; + this.timeService = timeService; + + long periodicWatermarkIntervalMillis; + try { + periodicWatermarkIntervalMillis = periodicWatermarkInterval.toMillis(); + } catch (ArithmeticException ignored) { + // long integer overflow + periodicWatermarkIntervalMillis = Long.MAX_VALUE; + } + this.periodicWatermarkInterval = periodicWatermarkIntervalMillis; + } + + // ------------------------------------------------------------------------ + + @Override + public ReaderOutput createMainOutput(PushingAsyncDataInput.DataOutput output) { + // At the moment, we assume only one output is ever created! + // This assumption is strict, currently, because many of the classes in this implementation do not + // support re-assigning the underlying output + checkState(currentMainOutput == null && currentPerSplitOutputs == null, "already created a main output"); + + final WatermarkOutput watermarkOutput = new WatermarkToDataOutput(output); + final WatermarkGenerator watermarkGenerator = watermarksFactory.createWatermarkGenerator(watermarksContext); + + currentPerSplitOutputs = new SplitLocalOutputs<>( + output, + watermarkOutput, + timestampAssigner, + watermarksFactory, + watermarksContext); + + currentMainOutput = new StreamingReaderOutput<>( + output, + watermarkOutput, + timestampAssigner, + watermarkGenerator, + currentPerSplitOutputs); + + return currentMainOutput; + } + + @Override + public void startPeriodicWatermarkEmits() { + checkState(periodicEmitHandle == null, "periodic emitter already started"); + + if (periodicWatermarkInterval == 0) { + // a value of zero means not activated + return; + } + + periodicEmitHandle = timeService.scheduleWithFixedDelay( + this::triggerPeriodicEmit, + periodicWatermarkInterval, + periodicWatermarkInterval); + } + + @Override + public void stopPeriodicWatermarkEmits() { + if (periodicEmitHandle != null) { + periodicEmitHandle.cancel(false); + periodicEmitHandle = null; + } + } + + void triggerPeriodicEmit(@SuppressWarnings("unused") long wallClockTimestamp) { + if (currentPerSplitOutputs != null) { + currentPerSplitOutputs.emitPeriodicWatermark(); + } + if (currentMainOutput != null) { + currentMainOutput.emitPeriodicWatermark(); + } + } + + // ------------------------------------------------------------------------ + + private static final class StreamingReaderOutput extends SourceOutputWithWatermarks implements ReaderOutput { + + private final SplitLocalOutputs splitLocalOutputs; + + StreamingReaderOutput( + PushingAsyncDataInput.DataOutput output, + WatermarkOutput watermarkOutput, + TimestampAssigner timestampAssigner, + WatermarkGenerator watermarkGenerator, + SplitLocalOutputs splitLocalOutputs) { + + super(output, watermarkOutput, watermarkOutput, timestampAssigner, watermarkGenerator); + this.splitLocalOutputs = splitLocalOutputs; + } + + @Override + public SourceOutput createOutputForSplit(String splitId) { + return splitLocalOutputs.createOutputForSplit(splitId); + } + + @Override + public void releaseOutputForSplit(String splitId) { + splitLocalOutputs.releaseOutputForSplit(splitId); + } + } + + // ------------------------------------------------------------------------ + + /** + * A holder and factory for split-local {@link SourceOutput}s. The split-local outputs maintain + * local watermark generators with their own state, to facilitate per-split watermarking logic. + * + * @param The type of the emitted records. + */ + private static final class SplitLocalOutputs { + + private final WatermarkOutputMultiplexer watermarkMultiplexer; + private final Map> localOutputs; + private final PushingAsyncDataInput.DataOutput recordOutput; + private final TimestampAssigner timestampAssigner; + private final WatermarkGeneratorSupplier watermarksFactory; + private final WatermarkGeneratorSupplier.Context watermarkContext; + + private SplitLocalOutputs( + PushingAsyncDataInput.DataOutput recordOutput, + WatermarkOutput watermarkOutput, + TimestampAssigner timestampAssigner, + WatermarkGeneratorSupplier watermarksFactory, + WatermarkGeneratorSupplier.Context watermarkContext) { + + this.recordOutput = recordOutput; + this.timestampAssigner = timestampAssigner; + this.watermarksFactory = watermarksFactory; + this.watermarkContext = watermarkContext; + + this.watermarkMultiplexer = new WatermarkOutputMultiplexer(watermarkOutput); + this.localOutputs = new LinkedHashMap<>(); // we use a LinkedHashMap because it iterates faster + } + + SourceOutput createOutputForSplit(String splitId) { + final SourceOutputWithWatermarks previous = localOutputs.get(splitId); + if (previous != null) { + return previous; + } + + watermarkMultiplexer.registerNewOutput(splitId); + final WatermarkOutput onEventOutput = watermarkMultiplexer.getImmediateOutput(splitId); + final WatermarkOutput periodicOutput = watermarkMultiplexer.getDeferredOutput(splitId); + + final WatermarkGenerator watermarks = watermarksFactory.createWatermarkGenerator(watermarkContext); + + final SourceOutputWithWatermarks localOutput = SourceOutputWithWatermarks.createWithSeparateOutputs( + recordOutput, onEventOutput, periodicOutput, timestampAssigner, watermarks); + + localOutputs.put(splitId, localOutput); + return localOutput; + } + + void releaseOutputForSplit(String splitId) { + localOutputs.remove(splitId); + watermarkMultiplexer.unregisterOutput(splitId); + } + + void emitPeriodicWatermark() { + // The call in the loop only records the next watermark candidate for each local output. + // The call to 'watermarkMultiplexer.onPeriodicEmit()' actually merges the watermarks. + // That way, we save inefficient repeated merging of (partially outdated) watermarks before + // all local generators have emitted their candidates. + for (SourceOutputWithWatermarks output : localOutputs.values()) { + output.emitPeriodicWatermark(); + } + watermarkMultiplexer.onPeriodicEmit(); + } + } +} diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/TimestampsAndWatermarks.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/TimestampsAndWatermarks.java new file mode 100644 index 00000000..f95ec551 --- /dev/null +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/TimestampsAndWatermarks.java @@ -0,0 +1,92 @@ +/* + * 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.streaming.api.operators.source; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.api.common.eventtime.TimestampAssigner; +import org.apache.flink.api.common.eventtime.WatermarkOutput; +import org.apache.flink.api.common.eventtime.WatermarkStrategy; +import org.apache.flink.api.connector.source.ReaderOutput; +import org.apache.flink.metrics.MetricGroup; +import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput; +import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService; + +import java.time.Duration; + +/** + * Basic interface for the timestamp extraction and watermark generation logic for the + * {@link org.apache.flink.api.connector.source.SourceReader}. + * + *

Implementations of this class may or may not actually perform certain tasks, like watermark + * generation. For example, the batch-oriented implementation typically skips all watermark generation + * logic. + * + * @param The type of the emitted records. + */ +@Internal +public interface TimestampsAndWatermarks { + + /** + * Creates the ReaderOutput for the source reader, than internally runs the timestamp extraction and + * watermark generation. + */ + ReaderOutput createMainOutput(PushingAsyncDataInput.DataOutput output); + + /** + * Starts emitting periodic watermarks, if this implementation produces watermarks, and if + * periodic watermarks are configured. + * + *

Periodic watermarks are produced by periodically calling the + * {@link org.apache.flink.api.common.eventtime.WatermarkGenerator#onPeriodicEmit(WatermarkOutput)} method + * of the underlying Watermark Generators. + */ + void startPeriodicWatermarkEmits(); + + /** + * Stops emitting periodic watermarks. + */ + void stopPeriodicWatermarkEmits(); + + // ------------------------------------------------------------------------ + // factories + // ------------------------------------------------------------------------ + + static TimestampsAndWatermarks createStreamingEventTimeLogic( + WatermarkStrategy watermarkStrategy, + MetricGroup metrics, + ProcessingTimeService timeService, + long periodicWatermarkIntervalMillis) { + + final TimestampsAndWatermarksContext context = new TimestampsAndWatermarksContext(metrics); + final TimestampAssigner timestampAssigner = watermarkStrategy.createTimestampAssigner(context); + + return new StreamingTimestampsAndWatermarks<>( + timestampAssigner, watermarkStrategy, context, timeService, Duration.ofMillis(periodicWatermarkIntervalMillis)); + } + + static TimestampsAndWatermarks createBatchEventTimeLogic( + WatermarkStrategy watermarkStrategy, + MetricGroup metrics) { + + final TimestampsAndWatermarksContext context = new TimestampsAndWatermarksContext(metrics); + final TimestampAssigner timestampAssigner = watermarkStrategy.createTimestampAssigner(context); + + return new BatchTimestampsAndWatermarks<>(timestampAssigner); + } +} diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/TimestampsAndWatermarksContext.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/TimestampsAndWatermarksContext.java new file mode 100644 index 00000000..201b9017 --- /dev/null +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/TimestampsAndWatermarksContext.java @@ -0,0 +1,46 @@ +/* + * 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.streaming.api.operators.source; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier; +import org.apache.flink.api.common.eventtime.WatermarkGeneratorSupplier; +import org.apache.flink.metrics.MetricGroup; + +import static org.apache.flink.util.Preconditions.checkNotNull; + +/** + * A simple implementation of a context that is both {@link TimestampAssignerSupplier.Context} + * and {@link WatermarkGeneratorSupplier.Context}. + */ +@Internal +public final class TimestampsAndWatermarksContext + implements TimestampAssignerSupplier.Context, WatermarkGeneratorSupplier.Context { + + private final MetricGroup metricGroup; + + public TimestampsAndWatermarksContext(MetricGroup metricGroup) { + this.metricGroup = checkNotNull(metricGroup); + } + + @Override + public MetricGroup getMetricGroup() { + return metricGroup; + } +} diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/WatermarkToDataOutput.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/WatermarkToDataOutput.java new file mode 100644 index 00000000..3e3b255a --- /dev/null +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/WatermarkToDataOutput.java @@ -0,0 +1,86 @@ +/* + * 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.streaming.api.operators.source; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.api.common.eventtime.Watermark; +import org.apache.flink.api.common.eventtime.WatermarkOutput; +import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput; +import org.apache.flink.streaming.runtime.streamstatus.StreamStatus; +import org.apache.flink.streaming.runtime.tasks.ExceptionInChainedOperatorException; + +import static org.apache.flink.util.Preconditions.checkNotNull; + +/** + * An adapter that exposes a {@link WatermarkOutput} based on a {@link PushingAsyncDataInput.DataOutput}. + */ +@Internal +public final class WatermarkToDataOutput implements WatermarkOutput { + + private final PushingAsyncDataInput.DataOutput output; + private long maxWatermarkSoFar; + private boolean isIdle; + + /** + * Creates a new WatermarkOutput against the given DataOutput. + */ + public WatermarkToDataOutput(PushingAsyncDataInput.DataOutput output) { + this.output = checkNotNull(output); + this.maxWatermarkSoFar = Long.MIN_VALUE; + } + + @Override + public void emitWatermark(Watermark watermark) { + final long newWatermark = watermark.getTimestamp(); + if (newWatermark <= maxWatermarkSoFar) { + return; + } + + maxWatermarkSoFar = newWatermark; + + try { + if (isIdle) { + output.emitStreamStatus(StreamStatus.ACTIVE); + isIdle = false; + } + + output.emitWatermark(new org.apache.flink.streaming.api.watermark.Watermark(newWatermark)); + } catch (ExceptionInChainedOperatorException e) { + throw e; + } catch (Exception e) { + throw new ExceptionInChainedOperatorException(e); + } + } + + @Override + public void markIdle() { + if (isIdle) { + return; + } + + try { + output.emitStreamStatus(StreamStatus.IDLE); + isIdle = true; + } catch (ExceptionInChainedOperatorException e) { + throw e; + } catch (Exception e) { + throw new ExceptionInChainedOperatorException(e); + } + } +} diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/ProcessingTimeCallback.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/ProcessingTimeCallback.java index 9bccae09..4604380b 100644 --- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/ProcessingTimeCallback.java +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/ProcessingTimeCallback.java @@ -25,6 +25,7 @@ import org.apache.flink.annotation.Internal; * {@link ProcessingTimeService}. */ @Internal +@FunctionalInterface public interface ProcessingTimeCallback { /** diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/ProcessingTimeService.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/ProcessingTimeService.java index 3f37ff50..9ce97f63 100644 --- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/ProcessingTimeService.java +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/ProcessingTimeService.java @@ -19,6 +19,7 @@ package org.apache.flink.streaming.runtime.tasks; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; /** * Defines the current processing time and handles all related actions, @@ -48,6 +49,9 @@ public interface ProcessingTimeService { /** * Registers a task to be executed repeatedly at a fixed rate. * + *

This call behaves similar to + * {@link org.apache.flink.runtime.concurrent.ScheduledExecutor#scheduleAtFixedRate(Runnable, long, long, TimeUnit)}. + * * @param callback to be executed after the initial delay and then after each period * @param initialDelay initial delay to start executing callback * @param period after the initial delay after which the callback is executed @@ -55,6 +59,19 @@ public interface ProcessingTimeService { */ ScheduledFuture scheduleAtFixedRate(ProcessingTimeCallback callback, long initialDelay, long period); + /** + * Registers a task to be executed repeatedly with a fixed delay. + * + *

This call behaves similar to + * {@link org.apache.flink.runtime.concurrent.ScheduledExecutor#scheduleWithFixedDelay(Runnable, long, long, TimeUnit)}. + * + * @param callback to be executed after the initial delay and then after each period + * @param initialDelay initial delay to start executing callback + * @param period after the initial delay after which the callback is executed + * @return Scheduled future representing the task to be executed repeatedly + */ + ScheduledFuture scheduleWithFixedDelay(ProcessingTimeCallback callback, long initialDelay, long period); + /** * This method puts the service into a state where it does not register new timers, but * returns for each call to {@link #registerTimer} or {@link #scheduleAtFixedRate} a "mock" diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/ProcessingTimeServiceImpl.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/ProcessingTimeServiceImpl.java index 61ae9f26..456d0a7d 100644 --- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/ProcessingTimeServiceImpl.java +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/ProcessingTimeServiceImpl.java @@ -76,6 +76,16 @@ class ProcessingTimeServiceImpl implements ProcessingTimeService { addQuiesceProcessingToCallback(processingTimeCallbackWrapper.apply(callback)), initialDelay, period); } + @Override + public ScheduledFuture scheduleWithFixedDelay(ProcessingTimeCallback callback, long initialDelay, long period) { + if (isQuiesced()) { + return new NeverCompleteFuture(initialDelay); + } + + return timerService.scheduleWithFixedDelay( + addQuiesceProcessingToCallback(processingTimeCallbackWrapper.apply(callback)), initialDelay, period); + } + @Override public CompletableFuture quiesce() { if (!quiesced) { 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 5898aa92..47a1d733 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 @@ -19,7 +19,6 @@ package org.apache.flink.streaming.runtime.tasks; import org.apache.flink.annotation.Internal; -import org.apache.flink.api.connector.source.SourceOutput; import org.apache.flink.runtime.execution.Environment; import org.apache.flink.streaming.api.operators.Output; import org.apache.flink.streaming.api.operators.SourceOperator; @@ -31,7 +30,6 @@ import org.apache.flink.streaming.runtime.io.StreamTaskInput; import org.apache.flink.streaming.runtime.io.StreamTaskSourceInput; import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; -import org.apache.flink.streaming.runtime.streamstatus.StreamStatus; import org.apache.flink.streaming.runtime.streamstatus.StreamStatusMaintainer; import static org.apache.flink.util.Preconditions.checkNotNull; @@ -49,7 +47,7 @@ public class SourceOperatorStreamTask extends StreamTask input = new StreamTaskSourceInput<>(headOperator); - DataOutput output = new StreamTaskSourceOutput<>( + DataOutput output = new AsyncDataOutputToOutput<>( operatorChain.getChainEntryPoint(), getStreamStatusMaintainer()); @@ -60,14 +58,13 @@ public class SourceOperatorStreamTask extends StreamTask extends AbstractDataOutput implements SourceOutput { + private static class AsyncDataOutputToOutput extends AbstractDataOutput { private final Output> output; - StreamTaskSourceOutput( + AsyncDataOutputToOutput( Output> output, StreamStatusMaintainer streamStatusMaintainer) { super(streamStatusMaintainer); @@ -89,27 +86,5 @@ public class SourceOperatorStreamTask extends StreamTask(record)); - } - - @Override - public void collect(T record, long timestamp) throws Exception { - output.collect(new StreamRecord<>(record, timestamp)); - } - - @Override - public void emitWatermark(org.apache.flink.api.common.eventtime.Watermark watermark) { - output.emitWatermark(new Watermark(watermark.getTimestamp())); - } - - @Override - public void markIdle() { - emitStreamStatus(StreamStatus.IDLE); - } } } diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/SystemProcessingTimeService.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/SystemProcessingTimeService.java index c0ecd85f..fc538709 100644 --- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/SystemProcessingTimeService.java +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/SystemProcessingTimeService.java @@ -126,16 +126,24 @@ public class SystemProcessingTimeService implements TimerService { @Override public ScheduledFuture scheduleAtFixedRate(ProcessingTimeCallback callback, long initialDelay, long period) { - long nextTimestamp = getCurrentProcessingTime() + initialDelay; + return scheduleRepeatedly(callback, initialDelay, period, false); + } + + @Override + public ScheduledFuture scheduleWithFixedDelay(ProcessingTimeCallback callback, long initialDelay, long period) { + return scheduleRepeatedly(callback, initialDelay, period, true); + } + + private ScheduledFuture scheduleRepeatedly(ProcessingTimeCallback callback, long initialDelay, long period, boolean fixedDelay) { + final long nextTimestamp = getCurrentProcessingTime() + initialDelay; + final Runnable task = wrapOnTimerCallback(callback, nextTimestamp, period); // we directly try to register the timer and only react to the status on exception // that way we save unnecessary volatile accesses for each timer try { - return timerService.scheduleAtFixedRate( - wrapOnTimerCallback(callback, nextTimestamp, period), - initialDelay, - period, - TimeUnit.MILLISECONDS); + return fixedDelay + ? timerService.scheduleWithFixedDelay(task, initialDelay, period, TimeUnit.MILLISECONDS) + : timerService.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { final int status = this.status.get(); if (status == STATUS_QUIESCED) { diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/TestProcessingTimeService.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/TestProcessingTimeService.java index 67a0ef7d..7c5742c4 100644 --- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/TestProcessingTimeService.java +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/TestProcessingTimeService.java @@ -112,6 +112,12 @@ public class TestProcessingTimeService implements TimerService { return periodicCallbackTask; } + @Override + public ScheduledFuture scheduleWithFixedDelay(ProcessingTimeCallback callback, long initialDelay, long period) { + // for all testing purposed, there is no difference between the fixed rate and fixed delay + return scheduleAtFixedRate(callback, initialDelay, period); + } + @Override public boolean isTerminated() { return isTerminated;