diff --git a/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/BoolWatermark.java b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/BoolWatermark.java new file mode 100644 --- /dev/null +++ b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/BoolWatermark.java @@ -0,0 +1,73 @@ +/* + * 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.watermark; + +import org.apache.flink.annotation.Experimental; + +import java.util.Objects; + +/** + * The {@link BoolWatermark} represents a watermark with a boolean value and an associated + * identifier. + */ +@Experimental +public class BoolWatermark implements Watermark { + + private static final long serialVersionUID = 1L; + + private final boolean value; + + private final String identifier; + + public BoolWatermark(boolean value, String identifier) { + this.value = value; + this.identifier = identifier; + } + + public boolean getValue() { + return value; + } + + @Override + public String getIdentifier() { + return identifier; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BoolWatermark that = (BoolWatermark) o; + return value == that.value && Objects.equals(identifier, that.identifier); + } + + @Override + public int hashCode() { + return Objects.hash(value, identifier); + } + + @Override + public String toString() { + return "BoolWatermark{" + "value=" + value + ", identifier='" + identifier + '\'' + '}'; + } +} diff --git a/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/BoolWatermarkDeclaration.java b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/BoolWatermarkDeclaration.java new file mode 100644 --- /dev/null +++ b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/BoolWatermarkDeclaration.java @@ -0,0 +1,97 @@ +/* + * 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.watermark; + +import org.apache.flink.annotation.Experimental; + +import java.util.Objects; + +/** + * The {@link BoolWatermarkDeclaration} class implements the {@link WatermarkDeclaration} interface + * and provides additional functionality specific to boolean-type watermarks. It includes methods + * for obtaining combination semantics and creating new bool watermarks. + */ +@Experimental +public class BoolWatermarkDeclaration implements WatermarkDeclaration { + + private final String identifier; + + private final WatermarkCombinationPolicy combinationPolicy; + + private final WatermarkHandlingStrategy defaultHandlingStrategy; + + public BoolWatermarkDeclaration( + String identifier, + WatermarkCombinationPolicy combinationPolicy, + WatermarkHandlingStrategy defaultHandlingStrategy) { + this.identifier = identifier; + this.combinationPolicy = combinationPolicy; + this.defaultHandlingStrategy = defaultHandlingStrategy; + } + + @Override + public String getIdentifier() { + return identifier; + } + + /** Creates a new {@link BoolWatermark} with the specified boolean value. */ + public BoolWatermark newWatermark(boolean val) { + return new BoolWatermark(val, identifier); + } + + public WatermarkCombinationPolicy getCombinationPolicy() { + return combinationPolicy; + } + + public WatermarkHandlingStrategy getDefaultHandlingStrategy() { + return defaultHandlingStrategy; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BoolWatermarkDeclaration that = (BoolWatermarkDeclaration) o; + return Objects.equals(identifier, that.identifier) + && Objects.equals(combinationPolicy, that.combinationPolicy) + && defaultHandlingStrategy == that.defaultHandlingStrategy; + } + + @Override + public int hashCode() { + return Objects.hash(identifier, combinationPolicy, defaultHandlingStrategy); + } + + @Override + public String toString() { + return "BoolWatermarkDeclaration{" + + "identifier='" + + identifier + + '\'' + + ", combinationPolicy=" + + combinationPolicy + + ", defaultHandlingStrategy=" + + defaultHandlingStrategy + + '}'; + } +} diff --git a/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/LongWatermark.java b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/LongWatermark.java new file mode 100644 --- /dev/null +++ b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/LongWatermark.java @@ -0,0 +1,72 @@ +/* + * 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.watermark; + +import org.apache.flink.annotation.Experimental; + +import java.util.Objects; + +/** + * The {@link LongWatermark} represents a watermark with a long value and an associated identifier. + */ +@Experimental +public class LongWatermark implements Watermark { + + private static final long serialVersionUID = 1L; + + private final long value; + + private final String identifier; + + public LongWatermark(long value, String identifier) { + this.value = value; + this.identifier = identifier; + } + + public long getValue() { + return value; + } + + @Override + public String getIdentifier() { + return identifier; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LongWatermark that = (LongWatermark) o; + return value == that.value && Objects.equals(identifier, that.identifier); + } + + @Override + public int hashCode() { + return Objects.hash(value, identifier); + } + + @Override + public String toString() { + return "LongWatermark{" + "value=" + value + ", identifier='" + identifier + '\'' + '}'; + } +} diff --git a/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/LongWatermarkDeclaration.java b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/LongWatermarkDeclaration.java new file mode 100644 --- /dev/null +++ b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/LongWatermarkDeclaration.java @@ -0,0 +1,99 @@ +/* + * 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.watermark; + +import org.apache.flink.annotation.Experimental; + +import java.util.Objects; + +/** + * The {@link LongWatermarkDeclaration} class implements the {@link WatermarkDeclaration} interface + * and provides additional functionality specific to long-type watermarks. It includes methods for + * obtaining combination semantics and creating new long watermarks. + */ +@Experimental +public class LongWatermarkDeclaration implements WatermarkDeclaration { + + protected static final long serialVersionUID = 1L; + + protected final String identifier; + + protected final WatermarkCombinationPolicy combinationPolicy; + + protected final WatermarkHandlingStrategy defaultHandlingStrategy; + + public LongWatermarkDeclaration( + String identifier, + WatermarkCombinationPolicy combinationPolicy, + WatermarkHandlingStrategy defaultHandlingStrategy) { + this.identifier = identifier; + this.combinationPolicy = combinationPolicy; + this.defaultHandlingStrategy = defaultHandlingStrategy; + } + + @Override + public String getIdentifier() { + return identifier; + } + + /** Creates a new {@link LongWatermark} with the specified long value. */ + public LongWatermark newWatermark(long val) { + return new LongWatermark(val, identifier); + } + + public WatermarkCombinationPolicy getCombinationPolicy() { + return combinationPolicy; + } + + public WatermarkHandlingStrategy getDefaultHandlingStrategy() { + return defaultHandlingStrategy; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LongWatermarkDeclaration that = (LongWatermarkDeclaration) o; + return Objects.equals(identifier, that.identifier) + && Objects.equals(combinationPolicy, that.combinationPolicy) + && defaultHandlingStrategy == that.defaultHandlingStrategy; + } + + @Override + public int hashCode() { + return Objects.hash(identifier, combinationPolicy, defaultHandlingStrategy); + } + + @Override + public String toString() { + return "LongWatermarkDeclaration{" + + "identifier='" + + identifier + + '\'' + + ", combinationPolicy=" + + combinationPolicy + + ", defaultHandlingStrategy=" + + defaultHandlingStrategy + + '}'; + } +} diff --git a/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/Watermark.java b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/Watermark.java new file mode 100644 --- /dev/null +++ b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/Watermark.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.watermark; + +import org.apache.flink.annotation.Experimental; + +import java.io.Serializable; + +/* * This interface represents a watermark. It will provide a unified triggering and + * combination mechanism for user-defined event-like things. + */ +@Experimental +public interface Watermark extends Serializable { + /** + * Returns the unique identifier for this watermark. + * + * @return a {@code String} representing the unique identifier of the watermark + */ + String getIdentifier(); +} diff --git a/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkCombinationFunction.java b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkCombinationFunction.java new file mode 100644 --- /dev/null +++ b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkCombinationFunction.java @@ -0,0 +1,55 @@ +/* + * 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.watermark; + +import org.apache.flink.annotation.Experimental; +import org.apache.flink.api.common.functions.Function; + +/** + * The {@link WatermarkCombinationFunction} defines the watermark's comparison/combination semantics + * among multiple input channels. + */ +@Experimental +public interface WatermarkCombinationFunction extends Function { + /** + * The {@link BoolWatermarkCombinationFunction} enum defines the combination semantics for + * boolean watermarks. It includes logical operations such as {@code OR} and {@code AND}. + */ + @Experimental + enum BoolWatermarkCombinationFunction implements WatermarkCombinationFunction { + /** Logical OR combination for boolean watermarks. */ + OR, + + /** Logical AND combination for boolean watermarks. */ + AND + } + + /** + * The {@link NumericWatermarkCombinationFunction} enum defines the combination semantics for + * numeric watermarks. It includes operations such as {@code MIN} and {@code MAX}. + */ + @Experimental + enum NumericWatermarkCombinationFunction implements WatermarkCombinationFunction { + /** Minimum value combination for numeric watermarks. */ + MIN, + + /** Maximum value combination for numeric watermarks. */ + MAX + } +} diff --git a/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkCombinationPolicy.java b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkCombinationPolicy.java new file mode 100644 --- /dev/null +++ b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkCombinationPolicy.java @@ -0,0 +1,79 @@ +/* + * 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.watermark; + +import org.apache.flink.annotation.Experimental; + +import java.io.Serializable; +import java.util.Objects; + +/** + * The {@link WatermarkCombinationPolicy} defines when and how to the combine {@link Watermark}s. + * + *

The watermark combination process will first check the setting of {@link + * #combineWaitForAllChannels}. If it is set to true, the ProcessFunction must receive watermarks + * from all input channels before it can proceed with the combination. + * + *

The actual combination of watermarks will then be executed using the specified {@link + * #watermarkCombinationFunction}. + */ +@Experimental +public class WatermarkCombinationPolicy implements Serializable { + + private static final long serialVersionUID = 1L; + + private final WatermarkCombinationFunction watermarkCombinationFunction; + + // Whether the combine process should be executed after the process function receives watermarks + // from both upstream channels. + private final boolean combineWaitForAllChannels; + + public WatermarkCombinationPolicy( + WatermarkCombinationFunction watermarkCombinationFunction, + boolean combineWaitForAllChannels) { + this.watermarkCombinationFunction = watermarkCombinationFunction; + this.combineWaitForAllChannels = combineWaitForAllChannels; + } + + public WatermarkCombinationFunction getWatermarkCombinationFunction() { + return watermarkCombinationFunction; + } + + public boolean isCombineWaitForAllChannels() { + return combineWaitForAllChannels; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WatermarkCombinationPolicy that = (WatermarkCombinationPolicy) o; + return combineWaitForAllChannels == that.combineWaitForAllChannels + && Objects.equals(watermarkCombinationFunction, that.watermarkCombinationFunction); + } + + @Override + public int hashCode() { + return Objects.hash(watermarkCombinationFunction, combineWaitForAllChannels); + } +} diff --git a/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkDeclaration.java b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkDeclaration.java new file mode 100644 --- /dev/null +++ b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkDeclaration.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.watermark; + +import org.apache.flink.annotation.Experimental; + +import java.io.Serializable; + +/** This class represents the watermark creation and handling policy defined by the user. */ +@Experimental +public interface WatermarkDeclaration extends Serializable { + /** + * Returns the unique identifier for this watermark. + * + * @return a {@code String} representing the unique identifier of the watermark + */ + String getIdentifier(); +} diff --git a/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkDeclarations.java b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkDeclarations.java new file mode 100644 --- /dev/null +++ b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkDeclarations.java @@ -0,0 +1,185 @@ +/* + * 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.watermark; + +import org.apache.flink.annotation.Experimental; +import org.apache.flink.api.common.watermark.WatermarkCombinationFunction.BoolWatermarkCombinationFunction; +import org.apache.flink.api.common.watermark.WatermarkCombinationFunction.NumericWatermarkCombinationFunction; + +/** The Utils class is used to create {@link WatermarkDeclaration}. */ +@Experimental +public class WatermarkDeclarations { + + public static WatermarkDeclarationBuilder newBuilder(String identifier) { + return new WatermarkDeclarationBuilder(identifier); + } + + /** Builder class for {@link WatermarkDeclaration}s. */ + @Experimental + public static class WatermarkDeclarationBuilder { + + protected final String identifier; + + WatermarkDeclarationBuilder(String identifier) { + this.identifier = identifier; + } + + public LongWatermarkDeclarationBuilder typeLong() { + return new LongWatermarkDeclarationBuilder(identifier); + } + + public BoolWatermarkDeclarationBuilder typeBool() { + return new BoolWatermarkDeclarationBuilder(identifier); + } + + @Experimental + public static class LongWatermarkDeclarationBuilder { + private final String identifier; + private boolean combineWaitForAllChannels = false; + private WatermarkCombinationFunction combinationFunction = + NumericWatermarkCombinationFunction.MIN; + private WatermarkHandlingStrategy defaultHandlingStrategy = + WatermarkHandlingStrategy.FORWARD; + + public LongWatermarkDeclarationBuilder(String identifier) { + this.identifier = identifier; + } + + /** Combine and propagate the maximum watermark to downstream. */ + public LongWatermarkDeclarationBuilder combineFunctionMax() { + this.combinationFunction = NumericWatermarkCombinationFunction.MAX; + return this; + } + + /** Combine and propagate the minimum watermark to downstream. */ + public LongWatermarkDeclarationBuilder combineFunctionMin() { + this.combinationFunction = NumericWatermarkCombinationFunction.MIN; + return this; + } + + /** + * Define whether the framework should send the {@link Watermark} to downstream tasks + * when the user-defined {@link Watermark} process method returns {@link + * WatermarkHandlingResult#PEEK}. If set to {@link WatermarkHandlingStrategy#FORWARD}, + * the framework will send the watermark to downstream tasks. If set to {@link + * WatermarkHandlingStrategy#IGNORE}, the framework will not take any action. + */ + public LongWatermarkDeclarationBuilder defaultHandlingStrategy( + WatermarkHandlingStrategy strategy) { + this.defaultHandlingStrategy = strategy; + return this; + } + + public LongWatermarkDeclarationBuilder defaultHandlingStrategyForward() { + this.defaultHandlingStrategy = WatermarkHandlingStrategy.FORWARD; + return this; + } + + public LongWatermarkDeclarationBuilder defaultHandlingStrategyIgnore() { + this.defaultHandlingStrategy = WatermarkHandlingStrategy.IGNORE; + return this; + } + + /** + * Whether the combine process should be executed after the process function receives + * watermarks from both upstream channels. + */ + public LongWatermarkDeclarationBuilder combineWaitForAllChannels( + boolean combineWaitForAllChannels) { + this.combineWaitForAllChannels = combineWaitForAllChannels; + return this; + } + + public LongWatermarkDeclaration build() { + return new LongWatermarkDeclaration( + identifier, + new WatermarkCombinationPolicy( + this.combinationFunction, this.combineWaitForAllChannels), + this.defaultHandlingStrategy); + } + } + + @Experimental + public static class BoolWatermarkDeclarationBuilder { + private final String identifier; + private boolean combineWaitForAllChannels = false; + private WatermarkCombinationFunction combinationFunction = + BoolWatermarkCombinationFunction.AND; + private WatermarkHandlingStrategy defaultHandlingStrategy = + WatermarkHandlingStrategy.FORWARD; + + public BoolWatermarkDeclarationBuilder(String identifier) { + this.identifier = identifier; + } + + /** Propagate the logical OR combination result of boolean watermarks downstream. */ + public BoolWatermarkDeclarationBuilder combineFunctionOR() { + this.combinationFunction = BoolWatermarkCombinationFunction.OR; + return this; + } + + /** Propagate the logical AND combination result of boolean watermarks downstream. */ + public BoolWatermarkDeclarationBuilder combineFunctionAND() { + this.combinationFunction = BoolWatermarkCombinationFunction.AND; + return this; + } + + /** + * Define whether the framework should send the {@link Watermark} to downstream tasks + * when the user-defined {@link Watermark} process method returns {@link + * WatermarkHandlingResult#PEEK}. If set to {@link WatermarkHandlingStrategy#FORWARD}, + * the framework will send the watermark to downstream tasks. If set to {@link + * WatermarkHandlingStrategy#IGNORE}, the framework will not take any action. + */ + public BoolWatermarkDeclarationBuilder defaultHandlingStrategy( + WatermarkHandlingStrategy strategy) { + this.defaultHandlingStrategy = strategy; + return this; + } + + public BoolWatermarkDeclarationBuilder defaultHandlingStrategyForward() { + this.defaultHandlingStrategy = WatermarkHandlingStrategy.FORWARD; + return this; + } + + public BoolWatermarkDeclarationBuilder defaultHandlingStrategyIgnore() { + this.defaultHandlingStrategy = WatermarkHandlingStrategy.IGNORE; + return this; + } + + /** + * Whether the combine process should be executed after the process function receives + * watermarks from both upstream channels. + */ + public BoolWatermarkDeclarationBuilder combineWaitForAllChannels( + boolean combineWaitForAllChannels) { + this.combineWaitForAllChannels = combineWaitForAllChannels; + return this; + } + + public BoolWatermarkDeclaration build() { + return new BoolWatermarkDeclaration( + identifier, + new WatermarkCombinationPolicy( + this.combinationFunction, this.combineWaitForAllChannels), + this.defaultHandlingStrategy); + } + } + } +} diff --git a/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkHandlingResult.java b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkHandlingResult.java new file mode 100644 --- /dev/null +++ b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkHandlingResult.java @@ -0,0 +1,37 @@ +/* + * 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.watermark; + +import org.apache.flink.annotation.Experimental; + +/** This class defines watermark handling result for user-defined process function. */ +@Experimental +public enum WatermarkHandlingResult { + /** + * Process function only peek the watermark, and it's framework's responsibility to handle this + * watermark. + */ + PEEK, + + /** + * This watermark should be sent to downstream by process function itself. The framework does no + * additional processing. + */ + POLL, +} diff --git a/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkHandlingStrategy.java b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkHandlingStrategy.java new file mode 100644 --- /dev/null +++ b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkHandlingStrategy.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.watermark; + +import org.apache.flink.annotation.Experimental; + +/** + * This class defines the framework's behavior when the user-defined {@link Watermark} process + * method returns {@link WatermarkHandlingResult#PEEK}. + */ +@Experimental +public enum WatermarkHandlingStrategy { + /** The framework shouldn't take any action. */ + IGNORE, + + /** The framework should send the watermark to downstream. */ + FORWARD, +} diff --git a/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkManager.java b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkManager.java new file mode 100644 --- /dev/null +++ b/flink-core-api/src/main/java/org/apache/flink/api/common/watermark/WatermarkManager.java @@ -0,0 +1,36 @@ +/* + * 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.watermark; + +import org.apache.flink.annotation.Experimental; + +/** + * The {@link WatermarkManager} interface provides a mechanism to emit watermarks from a process + * function. + */ +@Experimental +public interface WatermarkManager { + + /** + * Emits a watermark from the process function. + * + * @param watermark the {@link Watermark} to emit. + */ + void emitWatermark(Watermark watermark); +} 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 --- 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 @@ -19,8 +19,12 @@ package org.apache.flink.api.connector.source; import org.apache.flink.annotation.Public; +import org.apache.flink.api.common.watermark.WatermarkDeclaration; import org.apache.flink.core.io.SimpleVersionedSerializer; +import java.util.Collections; +import java.util.Set; + /** * The interface for Source. It acts like a factory class that helps construct the {@link * SplitEnumerator} and {@link SourceReader} and corresponding serializers. @@ -83,4 +87,14 @@ SplitEnumerator restoreEnumerator( * @return The serializer for the SplitEnumerator checkpoint. */ SimpleVersionedSerializer getEnumeratorCheckpointSerializer(); + + /** + * Explicitly declare watermarks upfront. Each specific watermark must be declared in this + * method before it can be used. + * + * @return all watermark declarations used by this application. + */ + default Set declareWatermarks() { + return Collections.emptySet(); + } } 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 --- 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 @@ -19,6 +19,7 @@ package org.apache.flink.api.connector.source; import org.apache.flink.annotation.Public; +import org.apache.flink.api.common.watermark.Watermark; import org.apache.flink.configuration.Configuration; import org.apache.flink.metrics.groups.SourceReaderMetricGroup; import org.apache.flink.util.UserCodeClassLoader; @@ -76,4 +77,13 @@ public interface SourceReaderContext { default int currentParallelism() { throw new UnsupportedOperationException(); } + + /** + * Send the watermark to source output. + * + *

This should only be used for datastream v2. + */ + default void emitWatermark(Watermark watermark) { + throw new UnsupportedOperationException(); + } } diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/BasePartitionedContext.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/BasePartitionedContext.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/BasePartitionedContext.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.datastream.api.context; + +import org.apache.flink.annotation.Experimental; + +/** + * On the base of {@link RuntimeContext}, {@link BasePartitionedContext} also contains all + * partition-wise execution information, such as getting state, registering timer, etc. + */ +@Experimental +public interface BasePartitionedContext extends RuntimeContext { + /** Get the {@link StateManager} of this process function. */ + StateManager getStateManager(); + + /** Get the {@link ProcessingTimeManager} of this process function. */ + ProcessingTimeManager getProcessingTimeManager(); +} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/NonPartitionedContext.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/NonPartitionedContext.java --- a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/NonPartitionedContext.java +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/NonPartitionedContext.java @@ -19,6 +19,8 @@ package org.apache.flink.datastream.api.context; import org.apache.flink.annotation.Experimental; +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.api.common.watermark.WatermarkManager; import org.apache.flink.datastream.api.function.ApplyPartitionFunction; /** @@ -32,4 +34,10 @@ public interface NonPartitionedContext extends RuntimeContext { * non-keyed stream, it will apply to single partition. */ void applyToAllPartitions(ApplyPartitionFunction applyPartitionFunction) throws Exception; + + /** + * Get {@link WatermarkManager} instance, which allow emitting a {@link Watermark} from the + * process function. + */ + WatermarkManager getWatermarkManager(); } diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/PartitionedContext.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/PartitionedContext.java --- a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/PartitionedContext.java +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/PartitionedContext.java @@ -20,15 +20,9 @@ import org.apache.flink.annotation.Experimental; -/** - * On the base of {@link RuntimeContext}, {@link PartitionedContext} also contains all - * partition-wise execution information, such as getting state, registering timer, etc. - */ +/** A {@link BasePartitionedContext} used in one output process functions. */ @Experimental -public interface PartitionedContext extends RuntimeContext { - /** Get the {@link StateManager} of this process function. */ - StateManager getStateManager(); - - /** Get the {@link ProcessingTimeManager} of this process function. */ - ProcessingTimeManager getProcessingTimeManager(); +public interface PartitionedContext extends BasePartitionedContext { + /** Get the non-partitioned context of this process function. */ + NonPartitionedContext getNonPartitionedContext(); } diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/TwoOutputNonPartitionedContext.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/TwoOutputNonPartitionedContext.java --- a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/TwoOutputNonPartitionedContext.java +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/TwoOutputNonPartitionedContext.java @@ -19,6 +19,8 @@ package org.apache.flink.datastream.api.context; import org.apache.flink.annotation.Experimental; +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.api.common.watermark.WatermarkManager; import org.apache.flink.datastream.api.function.TwoOutputApplyPartitionFunction; /** @@ -33,4 +35,10 @@ public interface TwoOutputNonPartitionedContext extends RuntimeConte */ void applyToAllPartitions(TwoOutputApplyPartitionFunction applyPartitionFunction) throws Exception; + + /** + * Get {@link WatermarkManager} instance, which allow emitting a {@link Watermark} from the + * process function. + */ + WatermarkManager getWatermarkManager(); } diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/TwoOutputPartitionedContext.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/TwoOutputPartitionedContext.java new file mode 100644 --- /dev/null +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/context/TwoOutputPartitionedContext.java @@ -0,0 +1,27 @@ +/* + * 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.datastream.api.context; + +import org.apache.flink.annotation.Experimental; + +/** A special {@link BasePartitionedContext} used in two output process functions. */ +@Experimental +public interface TwoOutputPartitionedContext extends BasePartitionedContext { + TwoOutputNonPartitionedContext getNonPartitionedContext(); +} diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/OneInputStreamProcessFunction.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/OneInputStreamProcessFunction.java --- a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/OneInputStreamProcessFunction.java +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/OneInputStreamProcessFunction.java @@ -19,6 +19,8 @@ package org.apache.flink.datastream.api.function; import org.apache.flink.annotation.Experimental; +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.api.common.watermark.WatermarkHandlingResult; import org.apache.flink.datastream.api.common.Collector; import org.apache.flink.datastream.api.context.NonPartitionedContext; import org.apache.flink.datastream.api.context.PartitionedContext; @@ -63,4 +65,10 @@ default void endInput(NonPartitionedContext ctx) {} * @param ctx runtime context in which this function is executed. */ default void onProcessingTimer(long timestamp, Collector output, PartitionedContext ctx) {} + + /** Callback function when receive watermark. */ + default WatermarkHandlingResult onWatermark( + Watermark watermark, Collector output, NonPartitionedContext ctx) { + return WatermarkHandlingResult.PEEK; + } } diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/ProcessFunction.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/ProcessFunction.java --- a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/ProcessFunction.java +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/ProcessFunction.java @@ -21,6 +21,7 @@ import org.apache.flink.annotation.Experimental; import org.apache.flink.api.common.functions.Function; import org.apache.flink.api.common.state.StateDeclaration; +import org.apache.flink.api.common.watermark.WatermarkDeclaration; import java.util.Collections; import java.util.Set; @@ -38,6 +39,16 @@ default Set usesStates() { return Collections.emptySet(); } + /** + * Explicitly declare watermarks upfront. Each specific watermark must be declared in this + * method before it can be used. + * + * @return all watermark declarations used by this application. + */ + default Set declareWatermarks() { + return Collections.emptySet(); + } + /** * Tear-down method for the user code. It is called after the last call to the main working * methods (e.g. processRecord). diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoInputBroadcastStreamProcessFunction.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoInputBroadcastStreamProcessFunction.java --- a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoInputBroadcastStreamProcessFunction.java +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoInputBroadcastStreamProcessFunction.java @@ -19,6 +19,8 @@ package org.apache.flink.datastream.api.function; import org.apache.flink.annotation.Experimental; +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.api.common.watermark.WatermarkHandlingResult; import org.apache.flink.datastream.api.common.Collector; import org.apache.flink.datastream.api.context.NonPartitionedContext; import org.apache.flink.datastream.api.context.PartitionedContext; @@ -86,4 +88,28 @@ default void endBroadcastInput(NonPartitionedContext ctx) {} * @param ctx runtime context in which this function is executed. */ default void onProcessingTimer(long timestamp, Collector output, PartitionedContext ctx) {} + + /** + * Callback function when receive the watermark from broadcast input. + * + * @param watermark to process. + * @param output to emit record. + * @param ctx runtime context in which this function is executed. + */ + default WatermarkHandlingResult onWatermarkFromBroadcastInput( + Watermark watermark, Collector output, NonPartitionedContext ctx) { + return WatermarkHandlingResult.PEEK; + } + + /** + * Callback function when receive the watermark from non-broadcast input. + * + * @param watermark to process. + * @param output to emit record. + * @param ctx runtime context in which this function is executed. + */ + default WatermarkHandlingResult onWatermarkFromNonBroadcastInput( + Watermark watermark, Collector output, NonPartitionedContext ctx) { + return WatermarkHandlingResult.PEEK; + } } diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoInputNonBroadcastStreamProcessFunction.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoInputNonBroadcastStreamProcessFunction.java --- a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoInputNonBroadcastStreamProcessFunction.java +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoInputNonBroadcastStreamProcessFunction.java @@ -19,6 +19,8 @@ package org.apache.flink.datastream.api.function; import org.apache.flink.annotation.Experimental; +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.api.common.watermark.WatermarkHandlingResult; import org.apache.flink.datastream.api.common.Collector; import org.apache.flink.datastream.api.context.NonPartitionedContext; import org.apache.flink.datastream.api.context.PartitionedContext; @@ -82,4 +84,28 @@ default void endSecondInput(NonPartitionedContext ctx) {} * @param ctx runtime context in which this function is executed. */ default void onProcessingTimer(long timestamp, Collector output, PartitionedContext ctx) {} + + /** + * Callback function when receive the watermark from the first input. + * + * @param watermark to process. + * @param output to emit record. + * @param ctx runtime context in which this function is executed. + */ + default WatermarkHandlingResult onWatermarkFromFirstInput( + Watermark watermark, Collector output, NonPartitionedContext ctx) { + return WatermarkHandlingResult.PEEK; + } + + /** + * Callback function when receive the watermark from the second input. + * + * @param watermark to process. + * @param output to emit record. + * @param ctx runtime context in which this function is executed. + */ + default WatermarkHandlingResult onWatermarkFromSecondInput( + Watermark watermark, Collector output, NonPartitionedContext ctx) { + return WatermarkHandlingResult.PEEK; + } } diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoOutputApplyPartitionFunction.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoOutputApplyPartitionFunction.java --- a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoOutputApplyPartitionFunction.java +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoOutputApplyPartitionFunction.java @@ -21,7 +21,7 @@ import org.apache.flink.annotation.Experimental; import org.apache.flink.api.common.functions.Function; import org.apache.flink.datastream.api.common.Collector; -import org.apache.flink.datastream.api.context.PartitionedContext; +import org.apache.flink.datastream.api.context.TwoOutputPartitionedContext; /** A function to be applied to all partitions with two outputs. */ @FunctionalInterface @@ -34,6 +34,9 @@ public interface TwoOutputApplyPartitionFunction extends Function { * @param secondOutput to emit record to second output. * @param ctx runtime context in which this function is executed. */ - void apply(Collector firstOutput, Collector secondOutput, PartitionedContext ctx) + void apply( + Collector firstOutput, + Collector secondOutput, + TwoOutputPartitionedContext ctx) throws Exception; } diff --git a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoOutputStreamProcessFunction.java b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoOutputStreamProcessFunction.java --- a/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoOutputStreamProcessFunction.java +++ b/flink-datastream-api/src/main/java/org/apache/flink/datastream/api/function/TwoOutputStreamProcessFunction.java @@ -19,9 +19,11 @@ package org.apache.flink.datastream.api.function; import org.apache.flink.annotation.Experimental; +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.api.common.watermark.WatermarkHandlingResult; import org.apache.flink.datastream.api.common.Collector; -import org.apache.flink.datastream.api.context.PartitionedContext; import org.apache.flink.datastream.api.context.TwoOutputNonPartitionedContext; +import org.apache.flink.datastream.api.context.TwoOutputPartitionedContext; /** This contains all logical related to process and emit records to two output streams. */ @Experimental @@ -47,7 +49,10 @@ default void open(TwoOutputNonPartitionedContext ctx) throws Excepti * @param ctx runtime context in which this function is executed. */ void processRecord( - IN record, Collector output1, Collector output2, PartitionedContext ctx) + IN record, + Collector output1, + Collector output2, + TwoOutputPartitionedContext ctx) throws Exception; /** @@ -70,5 +75,21 @@ default void onProcessingTimer( long timestamp, Collector output1, Collector output2, - PartitionedContext ctx) {} + TwoOutputPartitionedContext ctx) {} + + /** + * Callback function when receive the watermark from the input. + * + * @param watermark to process. + * @param output1 to emit data to the first output. + * @param output2 to emit data to the second output. + * @param ctx runtime context in which this function is executed. + */ + default WatermarkHandlingResult onWatermark( + Watermark watermark, + Collector output1, + Collector output2, + TwoOutputNonPartitionedContext ctx) { + return WatermarkHandlingResult.PEEK; + } } diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/ExecutionEnvironmentImpl.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/ExecutionEnvironmentImpl.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/ExecutionEnvironmentImpl.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/ExecutionEnvironmentImpl.java @@ -193,7 +193,7 @@ public ProcessConfigurableAndNonKeyedPartitionStream fromSource( return fromSource(new WrappedSource<>(generatorSource), "Collection Source"); } else { throw new UnsupportedOperationException( - "Unsupported type of sink, you could use DataStreamV2SourceUtils to wrap a FLIP-27 based source."); + "Unsupported type of source, you could use DataStreamV2SourceUtils to wrap a FLIP-27 based source."); } } diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/AbstractPartitionedContext.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/AbstractPartitionedContext.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/AbstractPartitionedContext.java @@ -0,0 +1,79 @@ +/* + * 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.datastream.impl.context; + +import org.apache.flink.datastream.api.context.BasePartitionedContext; +import org.apache.flink.datastream.api.context.JobInfo; +import org.apache.flink.datastream.api.context.ProcessingTimeManager; +import org.apache.flink.datastream.api.context.RuntimeContext; +import org.apache.flink.datastream.api.context.TaskInfo; +import org.apache.flink.metrics.MetricGroup; +import org.apache.flink.runtime.state.v2.OperatorStateStore; +import org.apache.flink.streaming.api.operators.StreamingRuntimeContext; + +import java.util.function.BiConsumer; +import java.util.function.Supplier; + +/** Abstract implementation class of {@link BasePartitionedContext}. */ +public abstract class AbstractPartitionedContext implements BasePartitionedContext { + protected final RuntimeContext context; + + protected final DefaultStateManager stateManager; + + protected final ProcessingTimeManager processingTimeManager; + + public AbstractPartitionedContext( + RuntimeContext context, + Supplier currentKeySupplier, + BiConsumer processorWithKey, + ProcessingTimeManager processingTimeManager, + StreamingRuntimeContext operatorContext, + OperatorStateStore operatorStateStore) { + this.context = context; + this.stateManager = + new DefaultStateManager( + currentKeySupplier, processorWithKey, operatorContext, operatorStateStore); + this.processingTimeManager = processingTimeManager; + } + + @Override + public JobInfo getJobInfo() { + return context.getJobInfo(); + } + + @Override + public TaskInfo getTaskInfo() { + return context.getTaskInfo(); + } + + @Override + public DefaultStateManager getStateManager() { + return stateManager; + } + + @Override + public ProcessingTimeManager getProcessingTimeManager() { + return processingTimeManager; + } + + @Override + public MetricGroup getMetricGroup() { + return context.getMetricGroup(); + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultNonPartitionedContext.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultNonPartitionedContext.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultNonPartitionedContext.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultNonPartitionedContext.java @@ -18,38 +18,49 @@ package org.apache.flink.datastream.impl.context; +import org.apache.flink.api.common.watermark.WatermarkManager; import org.apache.flink.datastream.api.common.Collector; import org.apache.flink.datastream.api.context.JobInfo; import org.apache.flink.datastream.api.context.NonPartitionedContext; import org.apache.flink.datastream.api.context.TaskInfo; import org.apache.flink.datastream.api.function.ApplyPartitionFunction; +import org.apache.flink.datastream.impl.watermark.DefaultWatermarkManager; import org.apache.flink.metrics.MetricGroup; +import org.apache.flink.streaming.api.operators.Output; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; +import java.util.Map; import java.util.Set; /** The default implementation of {@link NonPartitionedContext}. */ public class DefaultNonPartitionedContext implements NonPartitionedContext { private final DefaultRuntimeContext context; - private final DefaultPartitionedContext partitionedContext; + private final DefaultPartitionedContext partitionedContext; private final Collector collector; private final boolean isKeyed; private final Set keySet; + private final WatermarkManager watermarkManager; + public DefaultNonPartitionedContext( DefaultRuntimeContext context, - DefaultPartitionedContext partitionedContext, + DefaultPartitionedContext partitionedContext, Collector collector, boolean isKeyed, - Set keySet) { + Set keySet, + Output streamRecordOutput, + Map> watermarkDeclarationMap) { this.context = context; this.partitionedContext = partitionedContext; this.collector = collector; this.isKeyed = isKeyed; this.keySet = keySet; + this.watermarkManager = + new DefaultWatermarkManager(streamRecordOutput, watermarkDeclarationMap); } @Override @@ -75,6 +86,11 @@ public void applyToAllPartitions(ApplyPartitionFunction applyPartitionFunct } } + @Override + public WatermarkManager getWatermarkManager() { + return watermarkManager; + } + @Override public JobInfo getJobInfo() { return context.getJobInfo(); diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultPartitionedContext.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultPartitionedContext.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultPartitionedContext.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultPartitionedContext.java @@ -18,25 +18,28 @@ package org.apache.flink.datastream.impl.context; -import org.apache.flink.datastream.api.context.JobInfo; +import org.apache.flink.datastream.api.context.NonPartitionedContext; import org.apache.flink.datastream.api.context.PartitionedContext; import org.apache.flink.datastream.api.context.ProcessingTimeManager; import org.apache.flink.datastream.api.context.RuntimeContext; -import org.apache.flink.datastream.api.context.TaskInfo; -import org.apache.flink.metrics.MetricGroup; import org.apache.flink.runtime.state.v2.OperatorStateStore; import org.apache.flink.streaming.api.operators.StreamingRuntimeContext; import java.util.function.BiConsumer; import java.util.function.Supplier; /** The default implementation of {@link PartitionedContext}. */ -public class DefaultPartitionedContext implements PartitionedContext { - private final RuntimeContext context; +public class DefaultPartitionedContext extends AbstractPartitionedContext + implements PartitionedContext { - private final DefaultStateManager stateManager; - - private final ProcessingTimeManager processingTimeManager; + /** + * The {@link DefaultNonPartitionedContext} and {@link DefaultPartitionedContext} create a + * circular reference, so the {@code nonPartitionedContext} field of {@link + * DefaultPartitionedContext} should be set in a separate method, {@link + * DefaultPartitionedContext#setNonPartitionedContext(NonPartitionedContext)}, rather than in + * the constructor. + */ + private NonPartitionedContext nonPartitionedContext; public DefaultPartitionedContext( RuntimeContext context, @@ -45,35 +48,21 @@ public DefaultPartitionedContext( ProcessingTimeManager processingTimeManager, StreamingRuntimeContext operatorContext, OperatorStateStore operatorStateStore) { - this.context = context; - this.stateManager = - new DefaultStateManager( - currentKeySupplier, processorWithKey, operatorContext, operatorStateStore); - this.processingTimeManager = processingTimeManager; - } - - @Override - public JobInfo getJobInfo() { - return context.getJobInfo(); + super( + context, + currentKeySupplier, + processorWithKey, + processingTimeManager, + operatorContext, + operatorStateStore); } - @Override - public TaskInfo getTaskInfo() { - return context.getTaskInfo(); - } - - @Override - public DefaultStateManager getStateManager() { - return stateManager; - } - - @Override - public ProcessingTimeManager getProcessingTimeManager() { - return processingTimeManager; + public void setNonPartitionedContext(NonPartitionedContext nonPartitionedContext) { + this.nonPartitionedContext = nonPartitionedContext; } @Override - public MetricGroup getMetricGroup() { - return context.getMetricGroup(); + public NonPartitionedContext getNonPartitionedContext() { + return nonPartitionedContext; } } diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultTwoOutputNonPartitionedContext.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultTwoOutputNonPartitionedContext.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultTwoOutputNonPartitionedContext.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultTwoOutputNonPartitionedContext.java @@ -18,21 +18,26 @@ package org.apache.flink.datastream.impl.context; +import org.apache.flink.api.common.watermark.WatermarkManager; import org.apache.flink.datastream.api.common.Collector; import org.apache.flink.datastream.api.context.JobInfo; import org.apache.flink.datastream.api.context.TaskInfo; import org.apache.flink.datastream.api.context.TwoOutputNonPartitionedContext; import org.apache.flink.datastream.api.function.TwoOutputApplyPartitionFunction; +import org.apache.flink.datastream.impl.watermark.DefaultWatermarkManager; import org.apache.flink.metrics.MetricGroup; +import org.apache.flink.streaming.api.operators.Output; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; +import java.util.Map; import java.util.Set; /** The default implementation of {@link TwoOutputNonPartitionedContext}. */ public class DefaultTwoOutputNonPartitionedContext implements TwoOutputNonPartitionedContext { protected final DefaultRuntimeContext context; - private final DefaultPartitionedContext partitionedContext; + private final DefaultTwoOutputPartitionedContext partitionedContext; protected final Collector firstCollector; @@ -42,19 +47,25 @@ public class DefaultTwoOutputNonPartitionedContext private final Set keySet; + private final WatermarkManager watermarkManager; + public DefaultTwoOutputNonPartitionedContext( DefaultRuntimeContext context, - DefaultPartitionedContext partitionedContext, + DefaultTwoOutputPartitionedContext partitionedContext, Collector firstCollector, Collector secondCollector, boolean isKeyed, - Set keySet) { + Set keySet, + Output streamRecordOutput, + Map> watermarkDeclarationMap) { this.context = context; this.partitionedContext = partitionedContext; this.firstCollector = firstCollector; this.secondCollector = secondCollector; this.isKeyed = isKeyed; this.keySet = keySet; + this.watermarkManager = + new DefaultWatermarkManager(streamRecordOutput, watermarkDeclarationMap); } @Override @@ -83,6 +94,11 @@ public void applyToAllPartitions( } } + @Override + public WatermarkManager getWatermarkManager() { + return watermarkManager; + } + @Override public JobInfo getJobInfo() { return context.getJobInfo(); diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultTwoOutputPartitionedContext.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultTwoOutputPartitionedContext.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/DefaultTwoOutputPartitionedContext.java @@ -0,0 +1,69 @@ +/* + * 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.datastream.impl.context; + +import org.apache.flink.datastream.api.context.ProcessingTimeManager; +import org.apache.flink.datastream.api.context.RuntimeContext; +import org.apache.flink.datastream.api.context.TwoOutputNonPartitionedContext; +import org.apache.flink.datastream.api.context.TwoOutputPartitionedContext; +import org.apache.flink.runtime.state.v2.OperatorStateStore; +import org.apache.flink.streaming.api.operators.StreamingRuntimeContext; + +import java.util.function.BiConsumer; +import java.util.function.Supplier; + +/** The default implementation of {@link TwoOutputPartitionedContext}. */ +public class DefaultTwoOutputPartitionedContext extends AbstractPartitionedContext + implements TwoOutputPartitionedContext { + + /** + * The {@link DefaultTwoOutputNonPartitionedContext} and {@link + * DefaultTwoOutputPartitionedContext} create a circular reference, so the {@code + * nonPartitionedContext} field of {@link DefaultTwoOutputPartitionedContext} should be set in a + * separate method, {@link DefaultTwoOutputPartitionedContext#setNonPartitionedContext}, rather + * than in the constructor. + */ + protected TwoOutputNonPartitionedContext nonPartitionedContext; + + public DefaultTwoOutputPartitionedContext( + RuntimeContext context, + Supplier currentKeySupplier, + BiConsumer processorWithKey, + ProcessingTimeManager processingTimeManager, + StreamingRuntimeContext operatorContext, + OperatorStateStore operatorStateStore) { + super( + context, + currentKeySupplier, + processorWithKey, + processingTimeManager, + operatorContext, + operatorStateStore); + } + + public void setNonPartitionedContext( + TwoOutputNonPartitionedContext nonPartitionedContext) { + this.nonPartitionedContext = nonPartitionedContext; + } + + @Override + public TwoOutputNonPartitionedContext getNonPartitionedContext() { + return nonPartitionedContext; + } +} diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedProcessOperator.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedProcessOperator.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedProcessOperator.java @@ -101,7 +101,13 @@ protected ProcessingTimeManager getProcessingTimeManager() { @Override protected NonPartitionedContext getNonPartitionedContext() { return new DefaultNonPartitionedContext<>( - context, partitionedContext, outputCollector, true, keySet); + context, + partitionedContext, + outputCollector, + true, + keySet, + output, + watermarkDeclarationMap); } @Override diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoInputBroadcastProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoInputBroadcastProcessOperator.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoInputBroadcastProcessOperator.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoInputBroadcastProcessOperator.java @@ -102,7 +102,13 @@ public void onProcessingTime(InternalTimer timer) throws Exc @Override protected NonPartitionedContext getNonPartitionedContext() { return new DefaultNonPartitionedContext<>( - context, partitionedContext, collector, true, keySet); + context, + partitionedContext, + collector, + true, + keySet, + output, + watermarkDeclarationMap); } @Override diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoInputNonBroadcastProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoInputNonBroadcastProcessOperator.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoInputNonBroadcastProcessOperator.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoInputNonBroadcastProcessOperator.java @@ -104,7 +104,13 @@ public void onProcessingTime(InternalTimer timer) throws Exc @Override protected NonPartitionedContext getNonPartitionedContext() { return new DefaultNonPartitionedContext<>( - context, partitionedContext, collector, true, keySet); + context, + partitionedContext, + collector, + true, + keySet, + output, + watermarkDeclarationMap); } @Override diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoOutputProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoOutputProcessOperator.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoOutputProcessOperator.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/KeyedTwoOutputProcessOperator.java @@ -125,7 +125,14 @@ public void onProcessingTime(InternalTimer timer) throws Exc @Override protected TwoOutputNonPartitionedContext getNonPartitionedContext() { return new DefaultTwoOutputNonPartitionedContext<>( - context, partitionedContext, mainCollector, sideCollector, true, keySet); + context, + partitionedContext, + mainCollector, + sideCollector, + true, + keySet, + output, + watermarkDeclarationMap); } @Override diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/ProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/ProcessOperator.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/ProcessOperator.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/ProcessOperator.java @@ -19,6 +19,8 @@ package org.apache.flink.datastream.impl.operators; import org.apache.flink.api.common.TaskInfo; +import org.apache.flink.api.common.watermark.WatermarkHandlingResult; +import org.apache.flink.api.common.watermark.WatermarkHandlingStrategy; import org.apache.flink.datastream.api.context.NonPartitionedContext; import org.apache.flink.datastream.api.context.ProcessingTimeManager; import org.apache.flink.datastream.api.function.OneInputStreamProcessFunction; @@ -29,12 +31,17 @@ import org.apache.flink.datastream.impl.context.DefaultRuntimeContext; import org.apache.flink.datastream.impl.context.UnsupportedProcessingTimeManager; import org.apache.flink.runtime.asyncprocessing.operators.AbstractAsyncStateUdfStreamOperator; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.operators.BoundedOneInput; import org.apache.flink.streaming.api.operators.OneInputStreamOperator; import org.apache.flink.streaming.api.operators.StreamingRuntimeContext; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; +import java.util.Map; import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Collectors; /** Operator for {@link OneInputStreamProcessFunction}. */ public class ProcessOperator @@ -43,12 +50,15 @@ public class ProcessOperator protected transient DefaultRuntimeContext context; - protected transient DefaultPartitionedContext partitionedContext; + protected transient DefaultPartitionedContext partitionedContext; protected transient NonPartitionedContext nonPartitionedContext; protected transient TimestampCollector outputCollector; + protected transient Map> + watermarkDeclarationMap; + public ProcessOperator(OneInputStreamProcessFunction userFunction) { super(userFunction); } @@ -68,8 +78,17 @@ public void open() throws Exception { taskInfo.getIndexOfThisSubtask(), taskInfo.getAttemptNumber(), operatorContext.getMetricGroup()); + + outputCollector = getOutputCollector(); + watermarkDeclarationMap = + config.getWatermarkDeclarations(getUserCodeClassloader()).stream() + .collect( + Collectors.toMap( + AbstractInternalWatermarkDeclaration::getIdentifier, + Function.identity())); + partitionedContext = - new DefaultPartitionedContext( + new DefaultPartitionedContext<>( context, this::currentKey, getProcessorWithKey(), @@ -78,6 +97,7 @@ public void open() throws Exception { getOperatorStateBackend()); outputCollector = getOutputCollector(); nonPartitionedContext = getNonPartitionedContext(); + partitionedContext.setNonPartitionedContext(nonPartitionedContext); userFunction.open(nonPartitionedContext); } @@ -87,6 +107,20 @@ public void processElement(StreamRecord element) throws Exception { userFunction.processRecord(element.getValue(), outputCollector, partitionedContext); } + @Override + public void processWatermarkInternal(WatermarkEvent watermark) throws Exception { + WatermarkHandlingResult watermarkHandlingResultByUserFunction = + userFunction.onWatermark( + watermark.getWatermark(), outputCollector, nonPartitionedContext); + if (watermarkHandlingResultByUserFunction == WatermarkHandlingResult.PEEK + && watermarkDeclarationMap + .get(watermark.getWatermark().getIdentifier()) + .getDefaultHandlingStrategy() + == WatermarkHandlingStrategy.FORWARD) { + output.emitWatermark(watermark); + } + } + protected TimestampCollector getOutputCollector() { return new OutputCollector<>(output); } @@ -121,7 +155,13 @@ protected ProcessingTimeManager getProcessingTimeManager() { protected NonPartitionedContext getNonPartitionedContext() { return new DefaultNonPartitionedContext<>( - context, partitionedContext, outputCollector, false, null); + context, + partitionedContext, + outputCollector, + false, + null, + output, + watermarkDeclarationMap); } @Override diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/TwoInputBroadcastProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/TwoInputBroadcastProcessOperator.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/TwoInputBroadcastProcessOperator.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/TwoInputBroadcastProcessOperator.java @@ -19,6 +19,8 @@ package org.apache.flink.datastream.impl.operators; import org.apache.flink.api.common.TaskInfo; +import org.apache.flink.api.common.watermark.WatermarkHandlingResult; +import org.apache.flink.api.common.watermark.WatermarkHandlingStrategy; import org.apache.flink.datastream.api.context.NonPartitionedContext; import org.apache.flink.datastream.api.context.ProcessingTimeManager; import org.apache.flink.datastream.api.function.TwoInputBroadcastStreamProcessFunction; @@ -29,12 +31,17 @@ import org.apache.flink.datastream.impl.context.DefaultRuntimeContext; import org.apache.flink.datastream.impl.context.UnsupportedProcessingTimeManager; import org.apache.flink.runtime.asyncprocessing.operators.AbstractAsyncStateUdfStreamOperator; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.operators.BoundedMultiInput; import org.apache.flink.streaming.api.operators.StreamingRuntimeContext; import org.apache.flink.streaming.api.operators.TwoInputStreamOperator; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; +import java.util.Map; import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Collectors; import static org.apache.flink.util.Preconditions.checkState; @@ -48,10 +55,13 @@ public class TwoInputBroadcastProcessOperator protected transient DefaultRuntimeContext context; - protected transient DefaultPartitionedContext partitionedContext; + protected transient DefaultPartitionedContext partitionedContext; protected transient NonPartitionedContext nonPartitionedContext; + protected transient Map> + watermarkDeclarationMap; + public TwoInputBroadcastProcessOperator( TwoInputBroadcastStreamProcessFunction userFunction) { super(userFunction); @@ -73,15 +83,23 @@ public void open() throws Exception { taskInfo.getIndexOfThisSubtask(), taskInfo.getAttemptNumber(), operatorContext.getMetricGroup()); + + watermarkDeclarationMap = + config.getWatermarkDeclarations(getUserCodeClassloader()).stream() + .collect( + Collectors.toMap( + AbstractInternalWatermarkDeclaration::getIdentifier, + Function.identity())); this.partitionedContext = - new DefaultPartitionedContext( + new DefaultPartitionedContext<>( context, this::currentKey, getProcessorWithKey(), getProcessingTimeManager(), operatorContext, getOperatorStateBackend()); this.nonPartitionedContext = getNonPartitionedContext(); + this.partitionedContext.setNonPartitionedContext(this.nonPartitionedContext); this.userFunction.open(this.nonPartitionedContext); } @@ -98,13 +116,47 @@ public void processElement2(StreamRecord element) throws Exception { userFunction.processRecordFromBroadcastInput(element.getValue(), nonPartitionedContext); } + @Override + public void processWatermark1Internal(WatermarkEvent watermark) throws Exception { + WatermarkHandlingResult watermarkHandlingResultByUserFunction = + userFunction.onWatermarkFromNonBroadcastInput( + watermark.getWatermark(), collector, nonPartitionedContext); + if (watermarkHandlingResultByUserFunction == WatermarkHandlingResult.PEEK + && watermarkDeclarationMap + .get(watermark.getWatermark().getIdentifier()) + .getDefaultHandlingStrategy() + == WatermarkHandlingStrategy.FORWARD) { + output.emitWatermark(watermark); + } + } + + @Override + public void processWatermark2Internal(WatermarkEvent watermark) throws Exception { + WatermarkHandlingResult watermarkHandlingResultByUserFunction = + userFunction.onWatermarkFromBroadcastInput( + watermark.getWatermark(), collector, nonPartitionedContext); + if (watermarkHandlingResultByUserFunction == WatermarkHandlingResult.PEEK + && watermarkDeclarationMap + .get(watermark.getWatermark().getIdentifier()) + .getDefaultHandlingStrategy() + == WatermarkHandlingStrategy.FORWARD) { + output.emitWatermark(watermark); + } + } + protected TimestampCollector getOutputCollector() { return new OutputCollector<>(output); } protected NonPartitionedContext getNonPartitionedContext() { return new DefaultNonPartitionedContext<>( - context, partitionedContext, collector, false, null); + context, + partitionedContext, + collector, + false, + null, + output, + watermarkDeclarationMap); } @Override diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/TwoInputNonBroadcastProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/TwoInputNonBroadcastProcessOperator.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/TwoInputNonBroadcastProcessOperator.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/TwoInputNonBroadcastProcessOperator.java @@ -19,6 +19,8 @@ package org.apache.flink.datastream.impl.operators; import org.apache.flink.api.common.TaskInfo; +import org.apache.flink.api.common.watermark.WatermarkHandlingResult; +import org.apache.flink.api.common.watermark.WatermarkHandlingStrategy; import org.apache.flink.datastream.api.context.NonPartitionedContext; import org.apache.flink.datastream.api.context.ProcessingTimeManager; import org.apache.flink.datastream.api.function.TwoInputNonBroadcastStreamProcessFunction; @@ -29,13 +31,18 @@ import org.apache.flink.datastream.impl.context.DefaultRuntimeContext; import org.apache.flink.datastream.impl.context.UnsupportedProcessingTimeManager; import org.apache.flink.runtime.asyncprocessing.operators.AbstractAsyncStateUdfStreamOperator; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.state.OperatorStateBackend; import org.apache.flink.streaming.api.operators.BoundedMultiInput; import org.apache.flink.streaming.api.operators.StreamingRuntimeContext; import org.apache.flink.streaming.api.operators.TwoInputStreamOperator; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; +import java.util.Map; import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Collectors; import static org.apache.flink.util.Preconditions.checkState; @@ -49,10 +56,13 @@ public class TwoInputNonBroadcastProcessOperator protected transient DefaultRuntimeContext context; - protected transient DefaultPartitionedContext partitionedContext; + protected transient DefaultPartitionedContext partitionedContext; protected transient NonPartitionedContext nonPartitionedContext; + protected transient Map> + watermarkDeclarationMap; + public TwoInputNonBroadcastProcessOperator( TwoInputNonBroadcastStreamProcessFunction userFunction) { super(userFunction); @@ -76,15 +86,23 @@ public void open() throws Exception { taskInfo.getIndexOfThisSubtask(), taskInfo.getAttemptNumber(), operatorContext.getMetricGroup()); + + watermarkDeclarationMap = + config.getWatermarkDeclarations(getUserCodeClassloader()).stream() + .collect( + Collectors.toMap( + AbstractInternalWatermarkDeclaration::getIdentifier, + Function.identity())); this.partitionedContext = - new DefaultPartitionedContext( + new DefaultPartitionedContext<>( context, this::currentKey, getProcessorWithKey(), getProcessingTimeManager(), operatorContext, operatorStateBackend); this.nonPartitionedContext = getNonPartitionedContext(); + this.partitionedContext.setNonPartitionedContext(this.nonPartitionedContext); this.userFunction.open(this.nonPartitionedContext); } @@ -101,13 +119,47 @@ public void processElement2(StreamRecord element) throws Exception { element.getValue(), collector, partitionedContext); } + @Override + public void processWatermark1Internal(WatermarkEvent watermark) throws Exception { + WatermarkHandlingResult watermarkHandlingResultByUserFunction = + userFunction.onWatermarkFromFirstInput( + watermark.getWatermark(), collector, nonPartitionedContext); + if (watermarkHandlingResultByUserFunction == WatermarkHandlingResult.PEEK + && watermarkDeclarationMap + .get(watermark.getWatermark().getIdentifier()) + .getDefaultHandlingStrategy() + == WatermarkHandlingStrategy.FORWARD) { + output.emitWatermark(watermark); + } + } + + @Override + public void processWatermark2Internal(WatermarkEvent watermark) throws Exception { + WatermarkHandlingResult watermarkHandlingResultByUserFunction = + userFunction.onWatermarkFromSecondInput( + watermark.getWatermark(), collector, nonPartitionedContext); + if (watermarkHandlingResultByUserFunction == WatermarkHandlingResult.PEEK + && watermarkDeclarationMap + .get(watermark.getWatermark().getIdentifier()) + .getDefaultHandlingStrategy() + == WatermarkHandlingStrategy.FORWARD) { + output.emitWatermark(watermark); + } + } + protected TimestampCollector getOutputCollector() { return new OutputCollector<>(output); } protected NonPartitionedContext getNonPartitionedContext() { return new DefaultNonPartitionedContext<>( - context, partitionedContext, collector, false, null); + context, + partitionedContext, + collector, + false, + null, + output, + watermarkDeclarationMap); } @Override diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/TwoOutputProcessOperator.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/TwoOutputProcessOperator.java --- a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/TwoOutputProcessOperator.java +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/operators/TwoOutputProcessOperator.java @@ -19,25 +19,32 @@ package org.apache.flink.datastream.impl.operators; import org.apache.flink.api.common.TaskInfo; +import org.apache.flink.api.common.watermark.WatermarkHandlingResult; +import org.apache.flink.api.common.watermark.WatermarkHandlingStrategy; import org.apache.flink.datastream.api.context.ProcessingTimeManager; import org.apache.flink.datastream.api.context.TwoOutputNonPartitionedContext; import org.apache.flink.datastream.api.function.TwoOutputStreamProcessFunction; import org.apache.flink.datastream.impl.common.OutputCollector; import org.apache.flink.datastream.impl.common.TimestampCollector; -import org.apache.flink.datastream.impl.context.DefaultPartitionedContext; import org.apache.flink.datastream.impl.context.DefaultRuntimeContext; import org.apache.flink.datastream.impl.context.DefaultTwoOutputNonPartitionedContext; +import org.apache.flink.datastream.impl.context.DefaultTwoOutputPartitionedContext; import org.apache.flink.datastream.impl.context.UnsupportedProcessingTimeManager; import org.apache.flink.runtime.asyncprocessing.operators.AbstractAsyncStateUdfStreamOperator; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.state.v2.OperatorStateStore; import org.apache.flink.streaming.api.operators.BoundedOneInput; import org.apache.flink.streaming.api.operators.OneInputStreamOperator; import org.apache.flink.streaming.api.operators.Output; import org.apache.flink.streaming.api.operators.StreamingRuntimeContext; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; import org.apache.flink.util.OutputTag; +import java.util.Map; import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Collectors; /** * Operator for {@link TwoOutputStreamProcessFunction}. @@ -54,12 +61,15 @@ public class TwoOutputProcessOperator protected transient DefaultRuntimeContext context; - protected transient DefaultPartitionedContext partitionedContext; + protected transient DefaultTwoOutputPartitionedContext partitionedContext; protected transient TwoOutputNonPartitionedContext nonPartitionedContext; protected OutputTag outputTag; + protected transient Map> + watermarkDeclarationMap; + public TwoOutputProcessOperator( TwoOutputStreamProcessFunction userFunction, OutputTag outputTag) { @@ -85,15 +95,23 @@ public void open() throws Exception { taskInfo.getIndexOfThisSubtask(), taskInfo.getAttemptNumber(), operatorContext.getMetricGroup()); + + watermarkDeclarationMap = + config.getWatermarkDeclarations(getUserCodeClassloader()).stream() + .collect( + Collectors.toMap( + AbstractInternalWatermarkDeclaration::getIdentifier, + Function.identity())); this.partitionedContext = - new DefaultPartitionedContext( + new DefaultTwoOutputPartitionedContext<>( context, this::currentKey, getProcessorWithKey(), getProcessingTimeManager(), operatorContext, operatorStateStore); this.nonPartitionedContext = getNonPartitionedContext(); + this.partitionedContext.setNonPartitionedContext(nonPartitionedContext); this.userFunction.open(this.nonPartitionedContext); } @@ -105,6 +123,23 @@ public void processElement(StreamRecord element) throws Exception { element.getValue(), mainCollector, sideCollector, partitionedContext); } + @Override + public void processWatermarkInternal(WatermarkEvent watermark) throws Exception { + WatermarkHandlingResult watermarkHandlingResultByUserFunction = + userFunction.onWatermark( + watermark.getWatermark(), + mainCollector, + sideCollector, + nonPartitionedContext); + if (watermarkHandlingResultByUserFunction == WatermarkHandlingResult.PEEK + && watermarkDeclarationMap + .get(watermark.getWatermark().getIdentifier()) + .getDefaultHandlingStrategy() + == WatermarkHandlingStrategy.FORWARD) { + output.emitWatermark(watermark); + } + } + @Override public void endInput() throws Exception { userFunction.endInput(nonPartitionedContext); @@ -139,7 +174,14 @@ protected BiConsumer getProcessorWithKey() { protected TwoOutputNonPartitionedContext getNonPartitionedContext() { return new DefaultTwoOutputNonPartitionedContext<>( - context, partitionedContext, mainCollector, sideCollector, false, null); + context, + partitionedContext, + mainCollector, + sideCollector, + false, + null, + output, + watermarkDeclarationMap); } protected ProcessingTimeManager getProcessingTimeManager() { diff --git a/flink-datastream/src/main/java/org/apache/flink/datastream/impl/watermark/DefaultWatermarkManager.java b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/watermark/DefaultWatermarkManager.java new file mode 100644 --- /dev/null +++ b/flink-datastream/src/main/java/org/apache/flink/datastream/impl/watermark/DefaultWatermarkManager.java @@ -0,0 +1,57 @@ +/* + * 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.datastream.impl.watermark; + +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.api.common.watermark.WatermarkManager; +import org.apache.flink.runtime.event.WatermarkEvent; +import org.apache.flink.streaming.api.operators.Output; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; +import org.apache.flink.util.Preconditions; + +import java.util.Map; + +/** A default implementation of {@link WatermarkManager}. */ +public class DefaultWatermarkManager implements WatermarkManager { + + private final Output streamRecordOutput; + + private final Map> watermarkDeclarationMap; + + public DefaultWatermarkManager( + Output streamRecordOutput, + Map> watermarkDeclarationMap) { + this.streamRecordOutput = streamRecordOutput; + this.watermarkDeclarationMap = watermarkDeclarationMap; + } + + @Override + public void emitWatermark(Watermark watermark) { + Preconditions.checkState( + watermarkDeclarationMap.containsKey(watermark.getIdentifier()), + "Watermark identifier " + + watermark.getIdentifier() + + " does not exist, please declare it."); + + streamRecordOutput.emitWatermark( + new WatermarkEvent( + watermark, + watermarkDeclarationMap.get(watermark.getIdentifier()).isAligned())); + } +} diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/output/operators/StateBootstrapWrapperOperator.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/output/operators/StateBootstrapWrapperOperator.java --- a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/output/operators/StateBootstrapWrapperOperator.java +++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/output/operators/StateBootstrapWrapperOperator.java @@ -22,6 +22,7 @@ import org.apache.flink.core.fs.Path; import org.apache.flink.metrics.groups.OperatorMetricGroup; import org.apache.flink.runtime.checkpoint.CheckpointOptions; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.jobgraph.OperatorID; import org.apache.flink.runtime.state.CheckpointStreamFactory; import org.apache.flink.state.api.output.SnapshotUtils; @@ -206,6 +207,9 @@ public void emitLatencyMarker(LatencyMarker latencyMarker) {} @Override public void emitRecordAttributes(RecordAttributes recordAttributes) {} + @Override + public void emitWatermark(WatermarkEvent watermark) {} + @Override public void collect(T record) {} diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/output/operators/StateBootstrapWrapperOperatorFactory.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/output/operators/StateBootstrapWrapperOperatorFactory.java --- a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/output/operators/StateBootstrapWrapperOperatorFactory.java +++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/output/operators/StateBootstrapWrapperOperatorFactory.java @@ -19,6 +19,7 @@ package org.apache.flink.state.api.output.operators; import org.apache.flink.core.fs.Path; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.state.api.output.TaggedOperatorSubtaskState; import org.apache.flink.streaming.api.operators.AbstractStreamOperator; import org.apache.flink.streaming.api.operators.AbstractStreamOperatorFactory; @@ -96,6 +97,9 @@ public void emitLatencyMarker(LatencyMarker latencyMarker) {} @Override public void emitRecordAttributes(RecordAttributes recordAttributes) {} + @Override + public void emitWatermark(WatermarkEvent watermark) {} + @Override public void collect(T record) {} diff --git a/flink-runtime/pom.xml b/flink-runtime/pom.xml --- a/flink-runtime/pom.xml +++ b/flink-runtime/pom.xml @@ -56,6 +56,12 @@ under the License. + + org.apache.flink + flink-datastream-api + ${project.version} + + diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/AbstractAsyncStateStreamOperator.java b/flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/AbstractAsyncStateStreamOperator.java --- a/flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/AbstractAsyncStateStreamOperator.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/AbstractAsyncStateStreamOperator.java @@ -29,6 +29,7 @@ import org.apache.flink.runtime.asyncprocessing.AsyncStateException; import org.apache.flink.runtime.asyncprocessing.RecordContext; import org.apache.flink.runtime.asyncprocessing.declare.DeclarationManager; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.execution.Environment; import org.apache.flink.runtime.state.AsyncKeyedStateBackend; import org.apache.flink.runtime.state.v2.StateDescriptor; @@ -480,6 +481,48 @@ public void processRecordAttributes2(RecordAttributes recordAttributes) { null, () -> super.processRecordAttributes2(recordAttributes)); } + public void processWatermarkInternal(WatermarkEvent watermark) throws Exception { + super.processWatermark(watermark); + } + + public void processWatermark1Internal(WatermarkEvent watermark) throws Exception { + super.processWatermark1(watermark); + } + + public void processWatermark2Internal(WatermarkEvent watermark) throws Exception { + super.processWatermark2(watermark); + } + + @Override + public void processWatermark(WatermarkEvent watermark) throws Exception { + if (!isAsyncStateProcessingEnabled()) { + this.processWatermarkInternal(watermark); + return; + } + asyncExecutionController.processNonRecord( + null, () -> this.processWatermarkInternal(watermark)); + } + + @Override + public void processWatermark1(WatermarkEvent watermark) throws Exception { + if (!isAsyncStateProcessingEnabled()) { + this.processWatermark1Internal(watermark); + return; + } + asyncExecutionController.processNonRecord( + null, () -> this.processWatermark1Internal(watermark)); + } + + @Override + public void processWatermark2(WatermarkEvent watermark) throws Exception { + if (!isAsyncStateProcessingEnabled()) { + this.processWatermark2Internal(watermark); + return; + } + asyncExecutionController.processNonRecord( + null, () -> this.processWatermark2Internal(watermark)); + } + @VisibleForTesting AsyncExecutionController getAsyncExecutionController() { return asyncExecutionController; diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/TimestampedCollectorWithDeclaredVariable.java b/flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/TimestampedCollectorWithDeclaredVariable.java --- a/flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/TimestampedCollectorWithDeclaredVariable.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/TimestampedCollectorWithDeclaredVariable.java @@ -22,6 +22,7 @@ import org.apache.flink.api.common.typeutils.base.LongSerializer; import org.apache.flink.runtime.asyncprocessing.declare.DeclarationContext; import org.apache.flink.runtime.asyncprocessing.declare.DeclaredVariable; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.operators.Output; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker; @@ -126,4 +127,9 @@ public void emitLatencyMarker(LatencyMarker latencyMarker) { public void emitRecordAttributes(RecordAttributes recordAttributes) { output.emitRecordAttributes(recordAttributes); } + + @Override + public void emitWatermark(WatermarkEvent watermark) { + output.emitWatermark(watermark); + } } diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/event/WatermarkEvent.java b/flink-runtime/src/main/java/org/apache/flink/runtime/event/WatermarkEvent.java new file mode 100644 --- /dev/null +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/event/WatermarkEvent.java @@ -0,0 +1,127 @@ +/* + * 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.runtime.event; + +import org.apache.flink.annotation.Internal; +import org.apache.flink.api.common.watermark.BoolWatermark; +import org.apache.flink.api.common.watermark.LongWatermark; +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.core.memory.DataInputView; +import org.apache.flink.core.memory.DataOutputView; + +import java.io.IOException; +import java.util.Objects; + +/** + * This event wraps the {@link Watermark}, it is used in propagate {@link Watermark} between shuffle + * components, and should not be visible to operators and functions. + */ +@Internal +public class WatermarkEvent extends RuntimeEvent { + + private static final int TAG_LONG_GENERALIZED_WATERMARK = 0; + private static final int TAG_BOOL_GENERALIZED_WATERMARK = 1; + + private Watermark watermark; + private boolean isAligned = false; + + public WatermarkEvent() {} + + public WatermarkEvent(Watermark watermark, boolean isAligned) { + this.watermark = watermark; + this.isAligned = isAligned; + } + + @Override + public void write(DataOutputView out) throws IOException { + // write watermark identifier + out.writeUTF(watermark.getIdentifier()); + // write align flag + out.writeBoolean(isAligned); + // write watermark class tag + // write watermark value + if (watermark instanceof LongWatermark) { + out.writeInt(TAG_LONG_GENERALIZED_WATERMARK); + out.writeLong(((LongWatermark) watermark).getValue()); + } else if (watermark instanceof BoolWatermark) { + out.writeInt(TAG_BOOL_GENERALIZED_WATERMARK); + out.writeBoolean(((BoolWatermark) watermark).getValue()); + } else { + throw new IllegalArgumentException( + "Unsupported watermark type: " + watermark.getClass()); + } + } + + @Override + public void read(DataInputView in) throws IOException { + // read watermark identifier + String identifier = in.readUTF(); + // read align flag + this.isAligned = in.readBoolean(); + + // read watermark class tag + int watermarkTypeTag = in.readInt(); + + // read watermark value + if (watermarkTypeTag == TAG_LONG_GENERALIZED_WATERMARK) { + long value = in.readLong(); + this.watermark = new LongWatermark(value, identifier); + } else if (watermarkTypeTag == TAG_BOOL_GENERALIZED_WATERMARK) { + boolean value = in.readBoolean(); + this.watermark = new BoolWatermark(value, identifier); + } else { + throw new IllegalArgumentException("Unknown watermark class tag: " + watermarkTypeTag); + } + } + + public Watermark getWatermark() { + return watermark; + } + + public boolean isAligned() { + return isAligned; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WatermarkEvent that = (WatermarkEvent) o; + return isAligned == that.isAligned && Objects.equals(watermark, that.watermark); + } + + @Override + public int hashCode() { + return Objects.hash(watermark, isAligned); + } + + @Override + public String toString() { + return "WatermarkEvent{" + + "watermarkElement=" + + watermark + + ", isAligned=" + + isAligned + + '}'; + } +} diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/EventSerializer.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/EventSerializer.java --- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/EventSerializer.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/serialization/EventSerializer.java @@ -28,6 +28,7 @@ import org.apache.flink.runtime.checkpoint.SavepointType; import org.apache.flink.runtime.checkpoint.SnapshotType; import org.apache.flink.runtime.event.AbstractEvent; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.io.network.api.CancelCheckpointMarker; import org.apache.flink.runtime.io.network.api.CheckpointBarrier; import org.apache.flink.runtime.io.network.api.EndOfData; @@ -81,6 +82,8 @@ public class EventSerializer { private static final int RECOVERY_METADATA = 10; + private static final int GENERALIZED_WATERMARK_EVENT = 11; + private static final byte CHECKPOINT_TYPE_CHECKPOINT = 0; private static final byte CHECKPOINT_TYPE_SAVEPOINT = 1; @@ -154,6 +157,15 @@ public static ByteBuffer toSerializedEvent(AbstractEvent event) throws IOExcepti buf.putInt(0, RECOVERY_METADATA); buf.putInt(4, recoveryMetadata.getFinalBufferSubpartitionId()); return buf; + } else if (eventClass == WatermarkEvent.class) { + try { + final DataOutputSerializer serializer = new DataOutputSerializer(128); + serializer.writeInt(GENERALIZED_WATERMARK_EVENT); + event.write(serializer); + return serializer.wrapAsByteBuffer(); + } catch (IOException e) { + throw new IOException("Error while serializing event.", e); + } } else { try { final DataOutputSerializer serializer = new DataOutputSerializer(128); @@ -203,6 +215,11 @@ public static AbstractEvent fromSerializedEvent(ByteBuffer buffer, ClassLoader c } else if (type == RECOVERY_METADATA) { int subpartitionId = buffer.getInt(); return new RecoveryMetadata(subpartitionId); + } else if (type == GENERALIZED_WATERMARK_EVENT) { + final DataInputDeserializer deserializer = new DataInputDeserializer(buffer); + WatermarkEvent watermarkEvent = new WatermarkEvent(); + watermarkEvent.read(deserializer); + return watermarkEvent; } else if (type == OTHER_EVENT) { try { final DataInputDeserializer deserializer = new DataInputDeserializer(buffer); diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/buffer/Buffer.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/buffer/Buffer.java --- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/buffer/Buffer.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/buffer/Buffer.java @@ -20,6 +20,7 @@ import org.apache.flink.core.memory.MemorySegment; import org.apache.flink.runtime.event.AbstractEvent; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.io.network.api.CheckpointBarrier; import org.apache.flink.runtime.io.network.api.EndOfData; import org.apache.flink.runtime.io.network.api.EndOfPartitionEvent; @@ -328,7 +329,19 @@ enum DataType { END_OF_PARTITION(false, true, false, false, false, false), /** Contains the metadata used during a recovery process. */ - RECOVERY_METADATA(false, true, false, false, false, false); + RECOVERY_METADATA(false, true, false, false, false, false), + + /** + * {@link #ALIGNED_WATERMARK_EVENT} indicates that this buffer represents a serialized + * {@link WatermarkEvent}, which needs to be aligned. + */ + ALIGNED_WATERMARK_EVENT(false, true, true, false, false, false), + + /** + * {@link #UNALIGNED_WATERMARK_EVENT} indicates that this buffer represents a serialized + * {@link WatermarkEvent}, which does not need to be aligned. + */ + UNALIGNED_WATERMARK_EVENT(false, true, false, false, false, false); private final boolean isBuffer; private final boolean isEvent; @@ -401,6 +414,12 @@ public static DataType getDataType(AbstractEvent event, boolean hasPriority) { return END_OF_DATA; } else if (event instanceof EndOfPartitionEvent) { return END_OF_PARTITION; + } else if (event instanceof WatermarkEvent) { + if (((WatermarkEvent) event).isAligned()) { + return ALIGNED_WATERMARK_EVENT; + } else { + return UNALIGNED_WATERMARK_EVENT; + } } else if (!(event instanceof CheckpointBarrier)) { return EVENT_BUFFER; } diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/InputGate.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/InputGate.java --- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/InputGate.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/InputGate.java @@ -131,6 +131,8 @@ public CompletableFuture getAvailableFuture() { return availabilityHelper.getAvailableFuture(); } + public abstract void resumeGateConsumption() throws IOException; + public abstract void resumeConsumption(InputChannelInfo channelInfo) throws IOException; public abstract void acknowledgeAllRecordsProcessed(InputChannelInfo channelInfo) diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/SingleInputGate.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/SingleInputGate.java --- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/SingleInputGate.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/SingleInputGate.java @@ -1130,6 +1130,13 @@ public void sendTaskEvent(TaskEvent event) throws IOException { } } + public void resumeGateConsumption() throws IOException { + checkState(!isFinished(), "InputGate already finished."); + for (InputChannel inputChannel : channels) { + inputChannel.resumeConsumption(); + } + } + @Override public void resumeConsumption(InputChannelInfo channelInfo) throws IOException { checkState(!isFinished(), "InputGate already finished."); diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/UnionInputGate.java b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/UnionInputGate.java --- a/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/UnionInputGate.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/UnionInputGate.java @@ -320,6 +320,12 @@ public void sendTaskEvent(TaskEvent event) throws IOException { } } + public void resumeGateConsumption() throws IOException { + for (Map.Entry entry : inputGatesByGateIndex.entrySet()) { + entry.getValue().resumeGateConsumption(); + } + } + @Override public void resumeConsumption(InputChannelInfo channelInfo) throws IOException { inputGatesByGateIndex.get(channelInfo.getGateIdx()).resumeConsumption(channelInfo); diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/InputGateWithMetrics.java b/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/InputGateWithMetrics.java --- a/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/InputGateWithMetrics.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/InputGateWithMetrics.java @@ -55,6 +55,10 @@ public CompletableFuture getAvailableFuture() { return inputGate.getAvailableFuture(); } + public void resumeGateConsumption() throws IOException { + inputGate.resumeGateConsumption(); + } + @Override public void resumeConsumption(InputChannelInfo channelInfo) throws IOException { inputGate.resumeConsumption(channelInfo); diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamConfig.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamConfig.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamConfig.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamConfig.java @@ -38,6 +38,7 @@ import org.apache.flink.streaming.api.operators.StreamOperator; import org.apache.flink.streaming.api.operators.StreamOperatorFactory; import org.apache.flink.streaming.runtime.tasks.StreamTaskException; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; import org.apache.flink.util.ClassLoaderUtil; import org.apache.flink.util.InstantiationUtil; import org.apache.flink.util.OutputTag; @@ -49,6 +50,7 @@ import java.io.Serializable; import java.time.Duration; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -133,6 +135,15 @@ public class StreamConfig implements Serializable { private static final String ATTRIBUTE = "attribute"; + private static final String WATERMARK_DECLARATIONS = "watermarkDeclarations"; + + /** + * To reduce the deserialization overhead of reading the WatermarkDeclaration, we'll store the + * result after the first deserialization, and return it directly in subsequent reading + * requests. + */ + private Set> deserializedWatermarkDeclarations; + private static final ConfigOption STATE_BACKEND_USE_MANAGED_MEMORY = ConfigOptions.key("statebackend.useManagedMemory") .booleanType() @@ -331,6 +342,28 @@ public TypeSerializer getTypeSerializerSideOut(OutputTag outputTag, Cl } } + public void setWatermarkDeclarations(byte[] serializedWatermarkDeclarations) { + if (serializedWatermarkDeclarations != null) { + config.setBytes(WATERMARK_DECLARATIONS, serializedWatermarkDeclarations); + } + } + + public Set> getWatermarkDeclarations(ClassLoader cl) { + if (deserializedWatermarkDeclarations != null) { + return deserializedWatermarkDeclarations; + } + + try { + Set> watermarkDeclarations = + InstantiationUtil.readObjectFromConfig(this.config, WATERMARK_DECLARATIONS, cl); + deserializedWatermarkDeclarations = + watermarkDeclarations == null ? Collections.emptySet() : watermarkDeclarations; + return deserializedWatermarkDeclarations; + } catch (Exception e) { + throw new StreamTaskException("Could not instantiate serializer.", e); + } + } + public void setupNetworkInputs(TypeSerializer... serializers) { InputConfig[] inputs = new InputConfig[serializers.length]; for (int i = 0; i < serializers.length; i++) { diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamGraph.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamGraph.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamGraph.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamGraph.java @@ -75,7 +75,9 @@ import org.apache.flink.streaming.runtime.tasks.OneInputStreamTask; import org.apache.flink.streaming.runtime.tasks.SourceOperatorStreamTask; import org.apache.flink.streaming.runtime.tasks.SourceStreamTask; +import org.apache.flink.streaming.runtime.tasks.StreamTaskException; import org.apache.flink.streaming.runtime.tasks.TwoInputStreamTask; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; import org.apache.flink.util.FlinkRuntimeException; import org.apache.flink.util.InstantiationUtil; import org.apache.flink.util.OutputTag; @@ -110,6 +112,7 @@ import java.util.stream.Collectors; import static org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration.MINIMAL_CHECKPOINT_TIME; +import static org.apache.flink.streaming.util.watermark.WatermarkUtils.getInternalWatermarkDeclarationsFromStreamGraph; import static org.apache.flink.util.Preconditions.checkArgument; import static org.apache.flink.util.Preconditions.checkNotNull; @@ -191,6 +194,10 @@ public class StreamGraph implements Pipeline, ExecutionPlan { private final Map streamNodeMinResources = new HashMap<>(); + // Serialized watermark declarations of the StreamGraph, which may be null if no watermark is + // declared + private byte[] serializedWatermarkDeclarations; + public StreamGraph( Configuration jobConfiguration, ExecutionConfig executionConfig, @@ -1491,6 +1498,24 @@ private void addNodesThatHaveNoNewPredecessors( } } + public void serializeAndSaveWatermarkDeclarations() { + Set> watermarkDeclarations = + getInternalWatermarkDeclarationsFromStreamGraph(this); + if (!watermarkDeclarations.isEmpty()) { + try { + this.serializedWatermarkDeclarations = + InstantiationUtil.serializeObject(watermarkDeclarations); + } catch (IOException e) { + throw new StreamTaskException("Could not serialize watermark declarations.", e); + } + } + } + + /** Get serialized watermark declarations, note that it may be null. */ + public byte[] getSerializedWatermarkDeclarations() { + return serializedWatermarkDeclarations; + } + @Override public String toString() { return "StreamGraph(jobId: " + jobId + ")"; diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamGraphGenerator.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamGraphGenerator.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamGraphGenerator.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamGraphGenerator.java @@ -289,6 +289,8 @@ public StreamGraph generate() { streamGraph.addUserArtifact(entry.getKey(), entry.getValue()); } + streamGraph.serializeAndSaveWatermarkDeclarations(); + final StreamGraph builtStreamGraph = streamGraph; alreadyTransformed.clear(); diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamNode.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamNode.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamNode.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamNode.java @@ -274,7 +274,6 @@ public void setBufferTimeout(Long bufferTimeout) { this.bufferTimeout = bufferTimeout; } - @VisibleForTesting public StreamOperator getOperator() { assert operatorFactory != null && operatorFactory instanceof SimpleOperatorFactory; return (StreamOperator) ((SimpleOperatorFactory) operatorFactory).getOperator(); diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamingJobGraphGenerator.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamingJobGraphGenerator.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamingJobGraphGenerator.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/StreamingJobGraphGenerator.java @@ -754,6 +754,7 @@ public static List createChain( tryConvertPartitionerForDynamicGraph( chainableOutputs, nonChainableOutputs, jobVertexBuildContext); config.setAttribute(currentNodeAttribute); + config.setWatermarkDeclarations(streamGraph.getSerializedWatermarkDeclarations()); setOperatorConfig(currentNodeId, config, chainInfo, jobVertexBuildContext); setOperatorChainedOutputsConfig(config, chainableOutputs, jobVertexBuildContext); diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/AbstractStreamOperator.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/AbstractStreamOperator.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/AbstractStreamOperator.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/AbstractStreamOperator.java @@ -37,6 +37,7 @@ import org.apache.flink.metrics.MetricGroup; import org.apache.flink.metrics.groups.OperatorMetricGroup; import org.apache.flink.runtime.checkpoint.CheckpointOptions; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.execution.Environment; import org.apache.flink.runtime.jobgraph.OperatorID; import org.apache.flink.runtime.metrics.groups.InternalOperatorMetricGroup; @@ -751,4 +752,19 @@ public void processRecordAttributes2(RecordAttributes recordAttributes) { Arrays.asList(lastRecordAttributes1, lastRecordAttributes2)) .build()); } + + @Experimental + public void processWatermark(WatermarkEvent watermark) throws Exception { + output.emitWatermark(watermark); + } + + @Experimental + public void processWatermark1(WatermarkEvent watermark) throws Exception { + output.emitWatermark(watermark); + } + + @Experimental + public void processWatermark2(WatermarkEvent watermark) throws Exception { + output.emitWatermark(watermark); + } } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/CountingOutput.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/CountingOutput.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/CountingOutput.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/CountingOutput.java @@ -20,6 +20,7 @@ import org.apache.flink.metrics.Counter; import org.apache.flink.metrics.Gauge; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker; import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes; @@ -80,4 +81,9 @@ public Gauge getWatermarkGauge() { public void emitRecordAttributes(RecordAttributes recordAttributes) { output.emitRecordAttributes(recordAttributes); } + + @Override + public void emitWatermark(WatermarkEvent watermark) { + output.emitWatermark(watermark); + } } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/Input.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/Input.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/Input.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/Input.java @@ -20,6 +20,7 @@ import org.apache.flink.annotation.Experimental; import org.apache.flink.annotation.PublicEvolving; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker; import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes; @@ -78,4 +79,11 @@ public interface Input { */ @Experimental default void processRecordAttributes(RecordAttributes recordAttributes) throws Exception {} + + /** + * Processes a {@link org.apache.flink.api.common.watermark.Watermark} that arrived at this + * input, wrapped in a {@link WatermarkEvent}. + */ + @Experimental + default void processWatermark(WatermarkEvent watermark) throws Exception {} } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/KeyedProcessOperator.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/KeyedProcessOperator.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/KeyedProcessOperator.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/KeyedProcessOperator.java @@ -18,6 +18,7 @@ package org.apache.flink.streaming.api.operators; import org.apache.flink.annotation.Internal; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.state.VoidNamespace; import org.apache.flink.runtime.state.VoidNamespaceSerializer; import org.apache.flink.streaming.api.SimpleTimerService; @@ -68,6 +69,11 @@ public void onEventTime(InternalTimer timer) throws Exception invokeUserFunction(TimeDomain.EVENT_TIME, timer); } + @Override + public void processWatermark(WatermarkEvent watermark) throws Exception { + output.emitWatermark(watermark); + } + @Override public void onProcessingTime(InternalTimer timer) throws Exception { collector.eraseTimestamp(); diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/Output.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/Output.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/Output.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/Output.java @@ -20,6 +20,7 @@ import org.apache.flink.annotation.Experimental; import org.apache.flink.annotation.PublicEvolving; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker; import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes; @@ -64,4 +65,11 @@ public interface Output extends Collector { */ @Experimental void emitRecordAttributes(RecordAttributes recordAttributes); + + /** + * Emits a {@link org.apache.flink.api.common.watermark.Watermark} from an operator, wrapped in + * a {@link WatermarkEvent}. + */ + @Experimental + void emitWatermark(WatermarkEvent watermark); } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java @@ -34,6 +34,7 @@ import org.apache.flink.core.io.InputStatus; import org.apache.flink.core.io.SimpleVersionedSerializer; import org.apache.flink.metrics.groups.SourceReaderMetricGroup; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.io.AvailabilityProvider; import org.apache.flink.runtime.io.network.api.StopMode; import org.apache.flink.runtime.metrics.groups.InternalSourceReaderMetricGroup; @@ -205,6 +206,9 @@ private enum OperatingMode { */ private transient PausableRelativeClock mainInputActivityClock; + /** Watermark identifier to whether the watermark are aligned. */ + private final Map watermarkIsAlignedMap; + public SourceOperator( StreamOperatorParameters parameters, FunctionWithException, Exception> @@ -216,7 +220,8 @@ public SourceOperator( Configuration configuration, String localHostname, boolean emitProgressiveWatermarks, - CanEmitBatchOfRecordsChecker canEmitBatchOfRecords) { + CanEmitBatchOfRecordsChecker canEmitBatchOfRecords, + Map watermarkIsAlignedMap) { super(parameters); this.readerFactory = checkNotNull(readerFactory); this.operatorEventGateway = checkNotNull(operatorEventGateway); @@ -230,6 +235,7 @@ public SourceOperator( this.watermarkAlignmentParams = watermarkStrategy.getAlignmentParameters(); this.allowUnalignedSourceSplits = configuration.get(ALLOW_UNALIGNED_SOURCE_SPLITS); this.canEmitBatchOfRecords = checkNotNull(canEmitBatchOfRecords); + this.watermarkIsAlignedMap = watermarkIsAlignedMap; } @Override @@ -325,6 +331,16 @@ public void registerReleaseHookIfAbsent( public int currentParallelism() { return getRuntimeContext().getTaskInfo().getNumberOfParallelSubtasks(); } + + @Override + public void emitWatermark( + org.apache.flink.api.common.watermark.Watermark watermark) { + checkState(watermarkIsAlignedMap.containsKey(watermark.getIdentifier())); + output.emitWatermark( + new WatermarkEvent( + watermark, + watermarkIsAlignedMap.get(watermark.getIdentifier()))); + } }; sourceReader = readerFactory.apply(context); diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/SourceOperatorFactory.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/SourceOperatorFactory.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/SourceOperatorFactory.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/SourceOperatorFactory.java @@ -21,6 +21,7 @@ Licensed to the Apache Software Foundation (ASF) under one import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.eventtime.WatermarkStrategy; import org.apache.flink.api.common.typeinfo.TypeInformation; +import org.apache.flink.api.common.watermark.WatermarkDeclaration; import org.apache.flink.api.connector.source.Boundedness; import org.apache.flink.api.connector.source.Source; import org.apache.flink.api.connector.source.SourceReader; @@ -35,10 +36,18 @@ Licensed to the Apache Software Foundation (ASF) under one import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService; import org.apache.flink.streaming.runtime.tasks.ProcessingTimeServiceAware; import org.apache.flink.streaming.runtime.tasks.StreamTask.CanEmitBatchOfRecordsChecker; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; +import org.apache.flink.streaming.util.watermark.WatermarkUtils; import org.apache.flink.util.function.FunctionWithException; import javax.annotation.Nullable; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + import static org.apache.flink.util.Preconditions.checkNotNull; /** The Factory class for {@link SourceOperator}. */ @@ -118,7 +127,8 @@ public > T createStreamOperator( .getTaskManagerInfo() .getTaskManagerExternalAddress(), emitProgressiveWatermarks, - parameters.getContainingTask().getCanEmitBatchOfRecords()); + parameters.getContainingTask().getCanEmitBatchOfRecords(), + getSourceWatermarkDeclarations()); parameters.getOperatorEventDispatcher().registerEventHandler(operatorId, sourceOperator); @@ -165,6 +175,10 @@ public void setOutputType(TypeInformation type, ExecutionConfig executionCo } } + public Set getSourceWatermarkDeclarations() { + return source.declareWatermarks(); + } + /** * This is a utility method to conjure up a "SplitT" generics variable binding so that we can * construct the SourceOperator without resorting to "all raw types". That way, this methods @@ -184,7 +198,8 @@ SourceOperator instantiateSourceOperator( Configuration config, String localHostName, boolean emitProgressiveWatermarks, - CanEmitBatchOfRecordsChecker canEmitBatchOfRecords) { + CanEmitBatchOfRecordsChecker canEmitBatchOfRecords, + Collection watermarkDeclarations) { // jumping through generics hoops: cast the generics away to then cast them back more // strictly typed @@ -197,6 +212,14 @@ SourceOperator instantiateSourceOperator( final SimpleVersionedSerializer typedSplitSerializer = (SimpleVersionedSerializer) splitSerializer; + Map watermarkIsAlignedMap = + WatermarkUtils.convertToInternalWatermarkDeclarations( + new HashSet<>(watermarkDeclarations)) + .stream() + .collect( + Collectors.toMap( + AbstractInternalWatermarkDeclaration::getIdentifier, + AbstractInternalWatermarkDeclaration::isAligned)); return new SourceOperator<>( parameters, typedReaderFactory, @@ -207,6 +230,7 @@ SourceOperator instantiateSourceOperator( config, localHostName, emitProgressiveWatermarks, - canEmitBatchOfRecords); + canEmitBatchOfRecords, + watermarkIsAlignedMap); } } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/TimestampedCollector.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/TimestampedCollector.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/TimestampedCollector.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/TimestampedCollector.java @@ -19,6 +19,7 @@ package org.apache.flink.streaming.api.operators; import org.apache.flink.annotation.Internal; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker; import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes; @@ -97,4 +98,9 @@ public void emitLatencyMarker(LatencyMarker latencyMarker) { public void emitRecordAttributes(RecordAttributes recordAttributes) { output.emitRecordAttributes(recordAttributes); } + + @Override + public void emitWatermark(WatermarkEvent watermark) { + output.emitWatermark(watermark); + } } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/TwoInputStreamOperator.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/TwoInputStreamOperator.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/TwoInputStreamOperator.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/TwoInputStreamOperator.java @@ -20,6 +20,7 @@ import org.apache.flink.annotation.Experimental; import org.apache.flink.annotation.PublicEvolving; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker; import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes; @@ -114,4 +115,18 @@ default void processRecordAttributes1(RecordAttributes recordAttributes) throws */ @Experimental default void processRecordAttributes2(RecordAttributes recordAttributes) throws Exception {} + + /** + * Processes a {@link org.apache.flink.api.common.watermark.Watermark} that arrived on the first + * input of this operator. + */ + @Experimental + default void processWatermark1(WatermarkEvent watermark) throws Exception {} + + /** + * Processes a {@link org.apache.flink.api.common.watermark.Watermark} that arrived on the + * second input of this operator. + */ + @Experimental + default void processWatermark2(WatermarkEvent watermark) throws Exception {} } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/sort/MultiInputSortingDataInput.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/sort/MultiInputSortingDataInput.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/sort/MultiInputSortingDataInput.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/sort/MultiInputSortingDataInput.java @@ -26,6 +26,7 @@ import org.apache.flink.configuration.Configuration; import org.apache.flink.core.memory.DataOutputSerializer; import org.apache.flink.runtime.checkpoint.channel.ChannelStateWriter; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.io.AvailabilityProvider; import org.apache.flink.runtime.io.disk.iomanager.IOManager; import org.apache.flink.runtime.jobgraph.tasks.TaskInvokable; @@ -433,6 +434,9 @@ public void emitRecordAttributes(RecordAttributes recordAttributes) throws Excep // RecordAttributes is not used in batch execution mode. We will ignore all the // RecordAttributes. } + + @Override + public void emitWatermark(WatermarkEvent watermark) throws Exception {} } /** diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/sort/SortingDataInput.java b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/sort/SortingDataInput.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/sort/SortingDataInput.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/sort/SortingDataInput.java @@ -28,6 +28,7 @@ import org.apache.flink.core.memory.DataOutputSerializer; import org.apache.flink.runtime.checkpoint.CheckpointException; import org.apache.flink.runtime.checkpoint.channel.ChannelStateWriter; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.io.AvailabilityProvider; import org.apache.flink.runtime.io.disk.iomanager.IOManager; import org.apache.flink.runtime.jobgraph.tasks.TaskInvokable; @@ -190,6 +191,9 @@ public void emitRecordAttributes(RecordAttributes recordAttributes) { // The SortingDataInput is only used in batch execution mode. The RecordAttributes is // not used in batch execution mode. We will ignore all the RecordAttributes. } + + @Override + public void emitWatermark(WatermarkEvent watermark) throws Exception {} } @Override diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/AbstractStreamTaskNetworkInput.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/AbstractStreamTaskNetworkInput.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/AbstractStreamTaskNetworkInput.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/AbstractStreamTaskNetworkInput.java @@ -18,8 +18,10 @@ package org.apache.flink.streaming.runtime.io; import org.apache.flink.api.common.typeutils.TypeSerializer; +import org.apache.flink.api.common.watermark.Watermark; import org.apache.flink.runtime.checkpoint.channel.InputChannelInfo; import org.apache.flink.runtime.event.AbstractEvent; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.io.network.api.EndOfData; import org.apache.flink.runtime.io.network.api.EndOfPartitionEvent; import org.apache.flink.runtime.io.network.api.serialization.RecordDeserializer; @@ -31,13 +33,18 @@ import org.apache.flink.streaming.runtime.streamrecord.StreamElement; import org.apache.flink.streaming.runtime.streamrecord.StreamElementSerializer; import org.apache.flink.streaming.runtime.tasks.StreamTask.CanEmitBatchOfRecordsChecker; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; +import org.apache.flink.streaming.runtime.watermark.WatermarkCombiner; import org.apache.flink.streaming.runtime.watermarkstatus.StatusWatermarkValve; +import org.apache.flink.util.ExceptionUtils; import java.io.IOException; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.concurrent.CompletableFuture; import static org.apache.flink.util.Preconditions.checkNotNull; @@ -64,6 +71,7 @@ public abstract class AbstractStreamTaskNetworkInput< private final RecordAttributesCombiner recordAttributesCombiner; private InputChannelInfo lastChannel = null; private R currentRecordDeserializer = null; + protected final Map watermarkCombiners = new HashMap<>(); protected final CanEmitBatchOfRecordsChecker canEmitBatchOfRecords; @@ -74,6 +82,24 @@ public AbstractStreamTaskNetworkInput( int inputIndex, Map recordDeserializers, CanEmitBatchOfRecordsChecker canEmitBatchOfRecords) { + this( + checkpointedInputGate, + inputSerializer, + statusWatermarkValve, + inputIndex, + recordDeserializers, + canEmitBatchOfRecords, + Collections.emptySet()); + } + + public AbstractStreamTaskNetworkInput( + CheckpointedInputGate checkpointedInputGate, + TypeSerializer inputSerializer, + StatusWatermarkValve statusWatermarkValve, + int inputIndex, + Map recordDeserializers, + CanEmitBatchOfRecordsChecker canEmitBatchOfRecords, + Set> watermarkDeclarationSet) { super(); this.checkpointedInputGate = checkpointedInputGate; deserializationDelegate = @@ -91,6 +117,21 @@ public AbstractStreamTaskNetworkInput( this.canEmitBatchOfRecords = checkNotNull(canEmitBatchOfRecords); this.recordAttributesCombiner = new RecordAttributesCombiner(checkpointedInputGate.getNumberOfInputChannels()); + + for (AbstractInternalWatermarkDeclaration watermarkDeclaration : + watermarkDeclarationSet) { + watermarkCombiners.put( + watermarkDeclaration.getIdentifier(), + watermarkDeclaration.createWatermarkCombiner( + flattenedChannelIndices.size(), + () -> { + try { + checkpointedInputGate.resumeGateConsumption(); + } catch (IOException e) { + throw new RuntimeException(e); + } + })); + } } @Override @@ -128,7 +169,7 @@ public DataInputStatus emitNext(DataOutput output) throws Exception { if (bufferOrEvent.get().isBuffer()) { processBuffer(bufferOrEvent.get()); } else { - DataInputStatus status = processEvent(bufferOrEvent.get()); + DataInputStatus status = processEvent(bufferOrEvent.get(), output); if (status == DataInputStatus.MORE_AVAILABLE && canEmitBatchOfRecords.check()) { continue; } @@ -181,7 +222,28 @@ private boolean processElement(StreamElement streamElement, DataOutput output } } - protected DataInputStatus processEvent(BufferOrEvent bufferOrEvent) { + private void processWatermarkEvent( + InputChannelInfo inputChannelInfo, + WatermarkEvent generalizedWatermarkEvent, + DataOutput output) + throws Exception { + Watermark watermark = generalizedWatermarkEvent.getWatermark(); + WatermarkCombiner combiner = watermarkCombiners.get(watermark.getIdentifier()); + combiner.combineWatermark( + watermark, + inputChannelInfo.getInputChannelIdx(), + outputWatermark -> { + try { + output.emitWatermark( + new WatermarkEvent( + outputWatermark, generalizedWatermarkEvent.isAligned())); + } catch (Exception e) { + throw new RuntimeException(e); + } + }); + } + + protected DataInputStatus processEvent(BufferOrEvent bufferOrEvent, DataOutput output) { // Event received final AbstractEvent event = bufferOrEvent.getEvent(); if (event.getClass() == EndOfData.class) { @@ -205,6 +267,13 @@ protected DataInputStatus processEvent(BufferOrEvent bufferOrEvent) { if (checkpointedInputGate.allChannelsRecovered()) { return DataInputStatus.END_OF_RECOVERY; } + } else if (event.getClass() == WatermarkEvent.class) { + try { + processWatermarkEvent( + bufferOrEvent.getChannelInfo(), (WatermarkEvent) event, output); + } catch (Exception e) { + ExceptionUtils.rethrow(e); + } } return DataInputStatus.MORE_AVAILABLE; } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/FinishedDataOutput.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/FinishedDataOutput.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/FinishedDataOutput.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/FinishedDataOutput.java @@ -18,6 +18,7 @@ package org.apache.flink.streaming.runtime.io; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker; import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes; @@ -59,4 +60,9 @@ public void emitLatencyMarker(LatencyMarker latencyMarker) throws Exception { public void emitRecordAttributes(RecordAttributes recordAttributes) throws Exception { LOG.debug("Unexpected recordAttributes after finish() received."); } + + @Override + public void emitWatermark(WatermarkEvent watermark) throws Exception { + LOG.debug("Unexpected watermark {} after finish() received.", watermark); + } } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/PushingAsyncDataInput.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/PushingAsyncDataInput.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/PushingAsyncDataInput.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/PushingAsyncDataInput.java @@ -18,6 +18,7 @@ package org.apache.flink.streaming.runtime.io; import org.apache.flink.annotation.Internal; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.io.AvailabilityProvider; import org.apache.flink.runtime.io.PullingAsyncDataInput; import org.apache.flink.streaming.api.watermark.Watermark; @@ -58,5 +59,7 @@ interface DataOutput { void emitLatencyMarker(LatencyMarker latencyMarker) throws Exception; void emitRecordAttributes(RecordAttributes recordAttributes) throws Exception; + + void emitWatermark(WatermarkEvent watermark) throws Exception; } } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/RecordWriterOutput.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/RecordWriterOutput.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/RecordWriterOutput.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/RecordWriterOutput.java @@ -24,6 +24,7 @@ import org.apache.flink.metrics.SimpleCounter; import org.apache.flink.runtime.checkpoint.CheckpointException; import org.apache.flink.runtime.event.AbstractEvent; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.io.network.api.CheckpointBarrier; import org.apache.flink.runtime.io.network.api.writer.RecordWriter; import org.apache.flink.runtime.plugable.SerializationDelegate; @@ -248,4 +249,21 @@ public void emitRecordAttributes(RecordAttributes recordAttributes) { throw new UncheckedIOException(e); } } + + @Override + public void emitWatermark(WatermarkEvent watermark) { + if (!recordWriter.isSubpartitionDerivable()) { + LOG.warn( + watermark + + " will be ignored, because its correctness cannot not be " + + "guaranteed when the subpartition information is not derivable."); + return; + } + + try { + recordWriter.broadcastEvent(watermark, false); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamMultipleInputProcessorFactory.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamMultipleInputProcessorFactory.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamMultipleInputProcessorFactory.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamMultipleInputProcessorFactory.java @@ -28,6 +28,7 @@ import org.apache.flink.metrics.Counter; import org.apache.flink.metrics.SimpleCounter; import org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptor; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.io.disk.iomanager.IOManager; import org.apache.flink.runtime.jobgraph.tasks.TaskInvokable; import org.apache.flink.runtime.memory.MemoryManager; @@ -119,7 +120,8 @@ public static StreamMultipleInputProcessor create( inflightDataRescalingDescriptor, gatePartitioners, taskInfo, - canEmitBatchOfRecords); + canEmitBatchOfRecords, + streamConfig.getWatermarkDeclarations(userClassloader)); } else if (configuredInput instanceof StreamConfig.SourceInputConfig) { StreamConfig.SourceInputConfig sourceInput = (StreamConfig.SourceInputConfig) configuredInput; @@ -295,6 +297,11 @@ public void emitLatencyMarker(LatencyMarker latencyMarker) throws Exception { public void emitRecordAttributes(RecordAttributes recordAttributes) throws Exception { input.processRecordAttributes(recordAttributes); } + + @Override + public void emitWatermark(WatermarkEvent watermark) throws Exception { + input.processWatermark(watermark); + } } @SuppressWarnings({"unchecked", "rawtypes"}) diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamTaskNetworkInput.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamTaskNetworkInput.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamTaskNetworkInput.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamTaskNetworkInput.java @@ -31,11 +31,14 @@ import org.apache.flink.streaming.runtime.io.checkpointing.CheckpointedInputGate; import org.apache.flink.streaming.runtime.streamrecord.StreamElement; import org.apache.flink.streaming.runtime.tasks.StreamTask.CanEmitBatchOfRecordsChecker; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; import org.apache.flink.streaming.runtime.watermarkstatus.StatusWatermarkValve; import org.apache.flink.streaming.runtime.watermarkstatus.WatermarkStatus; import java.io.IOException; +import java.util.Collections; import java.util.Map; +import java.util.Set; import java.util.concurrent.CompletableFuture; import static java.util.function.Function.identity; @@ -68,13 +71,32 @@ public StreamTaskNetworkInput( StatusWatermarkValve statusWatermarkValve, int inputIndex, CanEmitBatchOfRecordsChecker canEmitBatchOfRecords) { + this( + checkpointedInputGate, + inputSerializer, + ioManager, + statusWatermarkValve, + inputIndex, + canEmitBatchOfRecords, + Collections.emptySet()); + } + + public StreamTaskNetworkInput( + CheckpointedInputGate checkpointedInputGate, + TypeSerializer inputSerializer, + IOManager ioManager, + StatusWatermarkValve statusWatermarkValve, + int inputIndex, + CanEmitBatchOfRecordsChecker canEmitBatchOfRecords, + Set> watermarkDeclarationSet) { super( checkpointedInputGate, inputSerializer, statusWatermarkValve, inputIndex, getRecordDeserializers(checkpointedInputGate, ioManager), - canEmitBatchOfRecords); + canEmitBatchOfRecords, + watermarkDeclarationSet); } // Initialize one deserializer per input channel diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamTaskNetworkInputFactory.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamTaskNetworkInputFactory.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamTaskNetworkInputFactory.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamTaskNetworkInputFactory.java @@ -25,8 +25,10 @@ import org.apache.flink.streaming.runtime.io.recovery.RescalingStreamTaskNetworkInput; import org.apache.flink.streaming.runtime.partitioner.StreamPartitioner; import org.apache.flink.streaming.runtime.tasks.StreamTask.CanEmitBatchOfRecordsChecker; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; import org.apache.flink.streaming.runtime.watermarkstatus.StatusWatermarkValve; +import java.util.Set; import java.util.function.Function; /** Factory for {@link StreamTaskNetworkInput} and {@link RescalingStreamTaskNetworkInput}. */ @@ -44,7 +46,8 @@ public static StreamTaskInput create( InflightDataRescalingDescriptor rescalingDescriptorinflightDataRescalingDescriptor, Function> gatePartitioners, TaskInfo taskInfo, - CanEmitBatchOfRecordsChecker canEmitBatchOfRecords) { + CanEmitBatchOfRecordsChecker canEmitBatchOfRecords, + Set> watermarkDeclarationSet) { return rescalingDescriptorinflightDataRescalingDescriptor.equals( InflightDataRescalingDescriptor.NO_RESCALE) ? new StreamTaskNetworkInput<>( @@ -53,7 +56,8 @@ public static StreamTaskInput create( ioManager, statusWatermarkValve, inputIndex, - canEmitBatchOfRecords) + canEmitBatchOfRecords, + watermarkDeclarationSet) : new RescalingStreamTaskNetworkInput<>( checkpointedInputGate, inputSerializer, diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamTwoInputProcessorFactory.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamTwoInputProcessorFactory.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamTwoInputProcessorFactory.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamTwoInputProcessorFactory.java @@ -26,6 +26,7 @@ import org.apache.flink.core.memory.ManagedMemoryUseCase; import org.apache.flink.metrics.Counter; import org.apache.flink.runtime.checkpoint.InflightDataRescalingDescriptor; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.io.disk.iomanager.IOManager; import org.apache.flink.runtime.jobgraph.tasks.TaskInvokable; import org.apache.flink.runtime.memory.MemoryManager; @@ -94,7 +95,8 @@ public static StreamMultipleInputProcessor create( inflightDataRescalingDescriptor, gatePartitioners, taskInfo, - canEmitBatchOfRecords); + canEmitBatchOfRecords, + streamConfig.getWatermarkDeclarations(userClassloader)); TypeSerializer typeSerializer2 = streamConfig.getTypeSerializerIn(1, userClassloader); StreamTaskInput input2 = StreamTaskNetworkInputFactory.create( @@ -106,7 +108,8 @@ public static StreamMultipleInputProcessor create( inflightDataRescalingDescriptor, gatePartitioners, taskInfo, - canEmitBatchOfRecords); + canEmitBatchOfRecords, + streamConfig.getWatermarkDeclarations(userClassloader)); InputSelectable inputSelectable = streamOperator instanceof InputSelectable ? (InputSelectable) streamOperator : null; @@ -298,6 +301,15 @@ public void emitRecordAttributes(RecordAttributes recordAttributes) throws Excep operator.processRecordAttributes2(recordAttributes); } } + + @Override + public void emitWatermark(WatermarkEvent watermark) throws Exception { + if (inputIndex == 0) { + operator.processWatermark1(watermark); + } else { + operator.processWatermark2(watermark); + } + } } private static class FinishedOnRestoreWatermarkBypass { diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/checkpointing/CheckpointedInputGate.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/checkpointing/CheckpointedInputGate.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/checkpointing/CheckpointedInputGate.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/checkpointing/CheckpointedInputGate.java @@ -227,6 +227,10 @@ public EndOfDataStatus hasReceivedEndOfData() { return inputGate.hasReceivedEndOfData(); } + public void resumeGateConsumption() throws IOException { + inputGate.resumeGateConsumption(); + } + /** * Cleans up all internally held resources. * diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/recovery/RescalingStreamTaskNetworkInput.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/recovery/RescalingStreamTaskNetworkInput.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/recovery/RescalingStreamTaskNetworkInput.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/recovery/RescalingStreamTaskNetworkInput.java @@ -177,15 +177,15 @@ protected DemultiplexingRecordDeserializer getActiveSerializer( return deserialier; } - protected DataInputStatus processEvent(BufferOrEvent bufferOrEvent) { + protected DataInputStatus processEvent(BufferOrEvent bufferOrEvent, DataOutput output) { // Event received final AbstractEvent event = bufferOrEvent.getEvent(); if (event instanceof SubtaskConnectionDescriptor) { getActiveSerializer(bufferOrEvent.getChannelInfo()) .select((SubtaskConnectionDescriptor) event); return DataInputStatus.MORE_AVAILABLE; } - return super.processEvent(bufferOrEvent); + return super.processEvent(bufferOrEvent, output); } @Override diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/BroadcastingOutputCollector.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/BroadcastingOutputCollector.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/BroadcastingOutputCollector.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/BroadcastingOutputCollector.java @@ -19,6 +19,7 @@ import org.apache.flink.metrics.Counter; import org.apache.flink.metrics.Gauge; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.operators.Output; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.metrics.WatermarkGauge; @@ -111,4 +112,11 @@ public void emitRecordAttributes(RecordAttributes recordAttributes) { output.emitRecordAttributes(recordAttributes); } } + + @Override + public void emitWatermark(WatermarkEvent watermark) { + for (OutputWithChainingCheck> output : outputs) { + output.emitWatermark(watermark); + } + } } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/ChainingOutput.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/ChainingOutput.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/ChainingOutput.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/ChainingOutput.java @@ -21,6 +21,7 @@ import org.apache.flink.metrics.Gauge; import org.apache.flink.metrics.SimpleCounter; import org.apache.flink.metrics.groups.OperatorMetricGroup; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.operators.Input; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.io.RecordProcessorUtils; @@ -164,4 +165,13 @@ public void emitRecordAttributes(RecordAttributes recordAttributes) { throw new ExceptionInChainedOperatorException(e); } } + + @Override + public void emitWatermark(WatermarkEvent watermark) { + try { + input.processWatermark(watermark); + } catch (Exception e) { + throw new ExceptionInChainedOperatorException(e); + } + } } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/FinishedOnRestoreMainOperatorOutput.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/FinishedOnRestoreMainOperatorOutput.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/FinishedOnRestoreMainOperatorOutput.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/FinishedOnRestoreMainOperatorOutput.java @@ -19,6 +19,7 @@ package org.apache.flink.streaming.runtime.tasks; import org.apache.flink.metrics.Gauge; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.io.RecordWriterOutput; import org.apache.flink.streaming.runtime.metrics.WatermarkGauge; @@ -77,6 +78,13 @@ public void emitRecordAttributes(RecordAttributes recordAttributes) { } } + @Override + public void emitWatermark(WatermarkEvent watermark) { + for (RecordWriterOutput streamOutput : streamOutputs) { + streamOutput.emitWatermark(watermark); + } + } + @Override public void close() {} diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/OneInputStreamTask.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/OneInputStreamTask.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/OneInputStreamTask.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/OneInputStreamTask.java @@ -23,6 +23,7 @@ import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.core.memory.ManagedMemoryUseCase; import org.apache.flink.metrics.Counter; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.execution.Environment; import org.apache.flink.runtime.io.network.partition.consumer.IndexedInputGate; import org.apache.flink.runtime.metrics.MetricNames; @@ -44,6 +45,7 @@ import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker; import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; import org.apache.flink.streaming.runtime.watermarkstatus.StatusWatermarkValve; import org.apache.flink.streaming.runtime.watermarkstatus.WatermarkStatus; import org.apache.flink.util.function.ThrowingConsumer; @@ -56,6 +58,7 @@ import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.Set; import static org.apache.flink.streaming.api.graph.StreamConfig.requiresSorting; import static org.apache.flink.util.Preconditions.checkNotNull; @@ -195,6 +198,9 @@ private StreamTaskInput createTaskInput(CheckpointedInputGate inputGate) { TypeSerializer inSerializer = configuration.getTypeSerializerIn1(getUserCodeClassLoader()); + Set> watermarkDeclarationSet = + configuration.getWatermarkDeclarations(getUserCodeClassLoader()); + return StreamTaskNetworkInputFactory.create( inputGate, inSerializer, @@ -208,7 +214,8 @@ private StreamTaskInput createTaskInput(CheckpointedInputGate inputGate) { .get(gateIndex) .getPartitioner(), getEnvironment().getTaskInfo(), - getCanEmitBatchOfRecords()); + getCanEmitBatchOfRecords(), + watermarkDeclarationSet); } /** @@ -258,5 +265,10 @@ public void emitLatencyMarker(LatencyMarker latencyMarker) throws Exception { public void emitRecordAttributes(RecordAttributes recordAttributes) throws Exception { operator.processRecordAttributes(recordAttributes); } + + @Override + public void emitWatermark(WatermarkEvent watermark) throws Exception { + operator.processWatermark(watermark); + } } } diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/SourceOperatorStreamTask.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/SourceOperatorStreamTask.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/SourceOperatorStreamTask.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/SourceOperatorStreamTask.java @@ -25,6 +25,7 @@ import org.apache.flink.runtime.checkpoint.CheckpointOptions; import org.apache.flink.runtime.checkpoint.SavepointType; import org.apache.flink.runtime.checkpoint.SnapshotType; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.execution.Environment; import org.apache.flink.runtime.io.network.api.StopMode; import org.apache.flink.runtime.metrics.MetricNames; @@ -324,6 +325,11 @@ public void emitRecordAttributes(RecordAttributes recordAttributes) { output.emitRecordAttributes(recordAttributes); } + @Override + public void emitWatermark(WatermarkEvent watermark) throws Exception { + output.emitWatermark(watermark); + } + @Override public void emitWatermark(Watermark watermark) { long watermarkTimestamp = watermark.getTimestamp(); diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/StreamIterationTail.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/StreamIterationTail.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/StreamIterationTail.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/StreamIterationTail.java @@ -18,6 +18,7 @@ package org.apache.flink.streaming.runtime.tasks; import org.apache.flink.annotation.Internal; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.runtime.execution.Environment; import org.apache.flink.streaming.api.operators.AbstractStreamOperator; import org.apache.flink.streaming.api.operators.OneInputStreamOperator; @@ -142,6 +143,9 @@ public void emitLatencyMarker(LatencyMarker latencyMarker) {} @Override public void emitRecordAttributes(RecordAttributes recordAttributes) {} + @Override + public void emitWatermark(WatermarkEvent watermark) {} + @Override public void collect(StreamRecord record) { try { diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/AbstractInternalWatermarkDeclaration.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/AbstractInternalWatermarkDeclaration.java new file mode 100644 --- /dev/null +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/AbstractInternalWatermarkDeclaration.java @@ -0,0 +1,97 @@ +/* + * 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.runtime.watermark; + +import org.apache.flink.api.common.watermark.BoolWatermarkDeclaration; +import org.apache.flink.api.common.watermark.LongWatermarkDeclaration; +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.api.common.watermark.WatermarkCombinationPolicy; +import org.apache.flink.api.common.watermark.WatermarkDeclaration; +import org.apache.flink.api.common.watermark.WatermarkHandlingStrategy; + +/** + * The {@link AbstractInternalWatermarkDeclaration} class implements the {@code + * WatermarkDeclaration} interface and provides some internal-oriented methods, such as + * getting/setting the {@code align} flag and creating the {@link WatermarkCombiner}. + */ +public abstract class AbstractInternalWatermarkDeclaration implements WatermarkDeclaration { + + protected final String identifier; + + protected final WatermarkCombinationPolicy combinationPolicy; + + protected final WatermarkHandlingStrategy defaultHandlingStrategy; + + protected final boolean isAligned; + + public AbstractInternalWatermarkDeclaration( + String identifier, + WatermarkCombinationPolicy combinationPolicy, + WatermarkHandlingStrategy defaultHandlingStrategy, + boolean isAligned) { + this.identifier = identifier; + this.combinationPolicy = combinationPolicy; + this.defaultHandlingStrategy = defaultHandlingStrategy; + this.isAligned = isAligned; + } + + @Override + public String getIdentifier() { + return identifier; + } + + /** Creates a new {@link Watermark} with the specified value. */ + public abstract Watermark newWatermark(T val); + + public WatermarkCombinationPolicy getCombinationPolicy() { + return combinationPolicy; + } + + public WatermarkHandlingStrategy getDefaultHandlingStrategy() { + return defaultHandlingStrategy; + } + + public boolean isAligned() { + return isAligned; + } + + /** Creates a new {@link WatermarkCombiner} instance. */ + public abstract WatermarkCombiner createWatermarkCombiner( + int numberOfInputChannels, Runnable gateResumer); + + /** + * Converts a user-oriented {@link WatermarkDeclaration} to an internal-oriented {@link + * AbstractInternalWatermarkDeclaration}. + */ + public static AbstractInternalWatermarkDeclaration from( + WatermarkDeclaration watermarkDeclaration) { + if (watermarkDeclaration instanceof AbstractInternalWatermarkDeclaration) { + return (AbstractInternalWatermarkDeclaration) watermarkDeclaration; + } else if (watermarkDeclaration instanceof BoolWatermarkDeclaration) { + return new InternalBoolWatermarkDeclaration( + (BoolWatermarkDeclaration) watermarkDeclaration); + } else if (watermarkDeclaration instanceof LongWatermarkDeclaration) { + return new InternalLongWatermarkDeclaration( + (LongWatermarkDeclaration) watermarkDeclaration); + } else { + throw new IllegalArgumentException( + "Unknown watermark declaration type: " + watermarkDeclaration.getClass()); + } + } +} diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/Alignable.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/Alignable.java new file mode 100644 --- /dev/null +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/Alignable.java @@ -0,0 +1,32 @@ +/* + * 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.runtime.watermark; + +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.api.common.watermark.WatermarkDeclaration; + +/** + * An interface used to represent the special {@link WatermarkDeclaration}s can create aligned + * {@link Watermark}s, which need to be aligned when the operator receives them from input channels. + * Note that this interface is currently only used for internal implementation. + */ +public interface Alignable { + /** Represents whether the created {@link Watermark} needs to be aligned. */ + boolean isAligned(); +} diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/AlignableBoolWatermarkDeclaration.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/AlignableBoolWatermarkDeclaration.java new file mode 100644 --- /dev/null +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/AlignableBoolWatermarkDeclaration.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.runtime.watermark; + +import org.apache.flink.api.common.watermark.BoolWatermarkDeclaration; +import org.apache.flink.api.common.watermark.WatermarkCombinationPolicy; +import org.apache.flink.api.common.watermark.WatermarkHandlingStrategy; +import org.apache.flink.util.Preconditions; + +/** An alignable {@link BoolWatermarkDeclaration}. */ +public class AlignableBoolWatermarkDeclaration extends BoolWatermarkDeclaration + implements Alignable { + private final boolean isAligned; + + public AlignableBoolWatermarkDeclaration( + String identifier, + WatermarkCombinationPolicy combinationPolicyForChannel, + WatermarkHandlingStrategy defaultHandlingStrategyForFunction, + boolean isAligned) { + super(identifier, combinationPolicyForChannel, defaultHandlingStrategyForFunction); + Preconditions.checkArgument( + !isAligned || combinationPolicyForChannel.isCombineWaitForAllChannels(), + "The aligned watermark must wait for all channels during the combining process. Please set the WatermarkCombinationPolicy#combineWaitForAllChannels to true."); + this.isAligned = isAligned; + } + + public boolean isAligned() { + return isAligned; + } +} diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/AlignableLongWatermarkDeclaration.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/AlignableLongWatermarkDeclaration.java new file mode 100644 --- /dev/null +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/AlignableLongWatermarkDeclaration.java @@ -0,0 +1,48 @@ +/* + * 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.runtime.watermark; + +import org.apache.flink.api.common.watermark.LongWatermarkDeclaration; +import org.apache.flink.api.common.watermark.WatermarkCombinationPolicy; +import org.apache.flink.api.common.watermark.WatermarkHandlingStrategy; +import org.apache.flink.util.Preconditions; + +/** An alignable {@link LongWatermarkDeclaration}. */ +public class AlignableLongWatermarkDeclaration extends LongWatermarkDeclaration + implements Alignable { + + private final boolean isAligned; + + public AlignableLongWatermarkDeclaration( + String identifier, + WatermarkCombinationPolicy combinationPolicyForChannel, + WatermarkHandlingStrategy defaultHandlingStrategyForFunction, + boolean isAligned) { + super(identifier, combinationPolicyForChannel, defaultHandlingStrategyForFunction); + Preconditions.checkArgument( + !isAligned || combinationPolicyForChannel.isCombineWaitForAllChannels(), + "The aligned watermark must wait for all channels during the combining process. Please set the WatermarkCombinationPolicy#combineWaitForAllChannels to true."); + this.isAligned = isAligned; + } + + @Override + public boolean isAligned() { + return isAligned; + } +} diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/AlignedWatermarkCombiner.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/AlignedWatermarkCombiner.java new file mode 100644 --- /dev/null +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/AlignedWatermarkCombiner.java @@ -0,0 +1,70 @@ +/* + * 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.runtime.watermark; + +import org.apache.flink.api.common.watermark.Watermark; + +import java.util.BitSet; +import java.util.function.Consumer; + +/** + * A {@link WatermarkCombiner} is design to align {@link Watermark}s. It will combine watermarks + * after receiving watermarks from all upstream input channels. + * + *

The combine process will perform the following three steps: (1) send the combined watermark + * (actually the last received watermark) to downstream, (2) clear the received watermarks, (3) + * resume input gate. + * + *

Note that the aligned Watermarks should have the same value within a batch. + */ +public class AlignedWatermarkCombiner implements WatermarkCombiner { + /** The number of upstream input channels. */ + private int numberOfInputChannels; + + /** A bitset to record whether the watermark has been received from each channel. */ + private final BitSet hasReceiveWatermarks; + + /** The input gate resume callback. */ + private Runnable gateResumer; + + public AlignedWatermarkCombiner(int numberOfInputChannels, Runnable gateResumer) { + this.numberOfInputChannels = numberOfInputChannels; + this.hasReceiveWatermarks = new BitSet(numberOfInputChannels); + this.gateResumer = gateResumer; + } + + @Override + public void combineWatermark( + Watermark watermark, int channelIndex, Consumer watermarkEmitter) + throws Exception { + + // mark the channel has received the watermark + hasReceiveWatermarks.set(channelIndex); + + // once receive all watermarks, perform combine process + if (hasReceiveWatermarks.cardinality() == numberOfInputChannels) { + // send the combined watermark to downstream + watermarkEmitter.accept(watermark); + // clear the received watermarks + hasReceiveWatermarks.clear(); + // resume input gate + gateResumer.run(); + } + } +} diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/BoolWatermarkCombiner.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/BoolWatermarkCombiner.java new file mode 100644 --- /dev/null +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/BoolWatermarkCombiner.java @@ -0,0 +1,125 @@ +/* + * 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.runtime.watermark; + +import org.apache.flink.api.common.watermark.BoolWatermark; +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.api.common.watermark.WatermarkCombinationFunction; +import org.apache.flink.api.common.watermark.WatermarkCombinationPolicy; + +import java.util.BitSet; +import java.util.function.Consumer; + +import static org.apache.flink.util.Preconditions.checkState; + +/** + * A {@link WatermarkCombiner} for unaligned {@link BoolWatermark}s. + * + *

The combination process will perform the following steps: (1) determine if it satisfies the + * condition of {@link WatermarkCombinationPolicy#isCombineWaitForAllChannels()}, (2) calculate the + * combined watermark value, (3) send the combined watermark to downstream only when the value + * differs from the previous sent one or if it's the first time sending. + */ +public class BoolWatermarkCombiner implements WatermarkCombiner { + + private final WatermarkCombinationPolicy combinationPolicy; + + /** The number of upstream input channels. */ + private final int numberOfInputChannels; + + /** A bitset to record whether the watermark has been received from each channel. */ + private final BitSet hasReceiveWatermarks; + + /** The received watermark value for each channel. */ + private final BitSet watermarkValues; + + /** + * Send only the watermark that differs from the previous sent one, we need to record the + * previous sent watermark value and whether is the first time sending. + */ + private boolean previousEmitWatermarkValue = false; + + private boolean isFirstTimeEmit = true; + + public BoolWatermarkCombiner( + WatermarkCombinationPolicy combinationPolicy, int numberOfInputChannels) { + checkState( + combinationPolicy.getWatermarkCombinationFunction() + instanceof WatermarkCombinationFunction.BoolWatermarkCombinationFunction); + this.combinationPolicy = combinationPolicy; + this.numberOfInputChannels = numberOfInputChannels; + this.hasReceiveWatermarks = new BitSet(numberOfInputChannels); + this.watermarkValues = new BitSet(numberOfInputChannels); + + if (combinationPolicy.getWatermarkCombinationFunction() + == WatermarkCombinationFunction.BoolWatermarkCombinationFunction.OR) { + // Initialize the watermarkValues to all false when using OR strategy + watermarkValues.clear(0, numberOfInputChannels); + } else if (combinationPolicy.getWatermarkCombinationFunction() + == WatermarkCombinationFunction.BoolWatermarkCombinationFunction.AND) { + // Initialize the watermarkValues to all true when using AND strategy + watermarkValues.set(0, numberOfInputChannels); + } else { + throw new IllegalArgumentException( + "Illegal WatermarkCombinationFunction for BoolWatermarkCombiner: " + + combinationPolicy.getWatermarkCombinationFunction()); + } + } + + @Override + public void combineWatermark( + Watermark watermark, int channelIndex, Consumer watermarkEmitter) + throws Exception { + checkState(watermark instanceof BoolWatermark); + + hasReceiveWatermarks.set(channelIndex); + // Update the watermark for the current channel + watermarkValues.set(channelIndex, ((BoolWatermark) watermark).getValue()); + + if (combinationPolicy.isCombineWaitForAllChannels() + && hasReceiveWatermarks.cardinality() < numberOfInputChannels) { + // Not all watermarks have been received yet + return; + } + + // calculate the combined watermark value + boolean combinedWatermarkValue; + if (combinationPolicy.getWatermarkCombinationFunction() + == WatermarkCombinationFunction.BoolWatermarkCombinationFunction.OR) { + combinedWatermarkValue = watermarkValues.cardinality() > 0; + } else { + combinedWatermarkValue = watermarkValues.cardinality() == numberOfInputChannels; + } + + if (shouldEmitWatermark(combinedWatermarkValue)) { + // send the combined watermark to downstream + watermarkEmitter.accept( + new BoolWatermark(combinedWatermarkValue, watermark.getIdentifier())); + previousEmitWatermarkValue = combinedWatermarkValue; + } + } + + private boolean shouldEmitWatermark(boolean combinedWatermarkValue) { + if (isFirstTimeEmit) { + isFirstTimeEmit = false; + return true; + } + return combinedWatermarkValue != previousEmitWatermarkValue; + } +} diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/InternalBoolWatermarkDeclaration.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/InternalBoolWatermarkDeclaration.java new file mode 100644 --- /dev/null +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/InternalBoolWatermarkDeclaration.java @@ -0,0 +1,69 @@ +/* + * 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.runtime.watermark; + +import org.apache.flink.api.common.watermark.BoolWatermark; +import org.apache.flink.api.common.watermark.BoolWatermarkDeclaration; +import org.apache.flink.api.common.watermark.WatermarkCombinationPolicy; +import org.apache.flink.api.common.watermark.WatermarkHandlingStrategy; + +/** + * The {@link InternalBoolWatermarkDeclaration} class implements the {@link + * AbstractInternalWatermarkDeclaration} interface and provides additional functionality specific to + * boolean-type watermarks. + */ +public class InternalBoolWatermarkDeclaration + extends AbstractInternalWatermarkDeclaration { + + public InternalBoolWatermarkDeclaration(BoolWatermarkDeclaration declaration) { + this( + declaration.getIdentifier(), + declaration.getCombinationPolicy(), + declaration.getDefaultHandlingStrategy(), + (declaration instanceof Alignable) && ((Alignable) declaration).isAligned()); + } + + public InternalBoolWatermarkDeclaration( + String identifier, + WatermarkCombinationPolicy combinationPolicyForChannel, + WatermarkHandlingStrategy defaultHandlingStrategyForFunction, + boolean isAligned) { + super( + identifier, + combinationPolicyForChannel, + defaultHandlingStrategyForFunction, + isAligned); + } + + /** Creates a new {@code BoolWatermark} with the specified value. */ + @Override + public BoolWatermark newWatermark(Boolean val) { + return new BoolWatermark(val, getIdentifier()); + } + + @Override + public WatermarkCombiner createWatermarkCombiner( + int numberOfInputChannels, Runnable gateResumer) { + if (isAligned) { + return new AlignedWatermarkCombiner(numberOfInputChannels, gateResumer); + } else { + return new BoolWatermarkCombiner(getCombinationPolicy(), numberOfInputChannels); + } + } +} diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/InternalLongWatermarkDeclaration.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/InternalLongWatermarkDeclaration.java new file mode 100644 --- /dev/null +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/InternalLongWatermarkDeclaration.java @@ -0,0 +1,68 @@ +/* + * 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.runtime.watermark; + +import org.apache.flink.api.common.watermark.LongWatermark; +import org.apache.flink.api.common.watermark.LongWatermarkDeclaration; +import org.apache.flink.api.common.watermark.WatermarkCombinationPolicy; +import org.apache.flink.api.common.watermark.WatermarkHandlingStrategy; + +/** + * The {@link InternalLongWatermarkDeclaration} class implements the {@link + * AbstractInternalWatermarkDeclaration} interface and provides additional functionality specific to + * long-type watermarks. + */ +public class InternalLongWatermarkDeclaration extends AbstractInternalWatermarkDeclaration { + + public InternalLongWatermarkDeclaration(LongWatermarkDeclaration declaration) { + this( + declaration.getIdentifier(), + declaration.getCombinationPolicy(), + declaration.getDefaultHandlingStrategy(), + (declaration instanceof Alignable) && ((Alignable) declaration).isAligned()); + } + + public InternalLongWatermarkDeclaration( + String identifier, + WatermarkCombinationPolicy combinationPolicyForChannel, + WatermarkHandlingStrategy defaultHandlingStrategyForFunction, + boolean isAligned) { + super( + identifier, + combinationPolicyForChannel, + defaultHandlingStrategyForFunction, + isAligned); + } + + /** Creates a new {@code LongWatermark} with the specified value. */ + @Override + public LongWatermark newWatermark(Long val) { + return new LongWatermark(val, this.getIdentifier()); + } + + @Override + public WatermarkCombiner createWatermarkCombiner( + int numberOfInputChannels, Runnable gateResumer) { + if (isAligned) { + return new AlignedWatermarkCombiner(numberOfInputChannels, gateResumer); + } else { + return new LongWatermarkCombiner(getCombinationPolicy(), numberOfInputChannels); + } + } +} diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/LongWatermarkCombiner.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/LongWatermarkCombiner.java new file mode 100644 --- /dev/null +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/LongWatermarkCombiner.java @@ -0,0 +1,184 @@ +/* + * 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.runtime.watermark; + +import org.apache.flink.api.common.watermark.LongWatermark; +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.api.common.watermark.WatermarkCombinationFunction; +import org.apache.flink.api.common.watermark.WatermarkCombinationPolicy; +import org.apache.flink.streaming.runtime.watermarkstatus.HeapPriorityQueue; +import org.apache.flink.streaming.runtime.watermarkstatus.HeapPriorityQueue.HeapPriorityQueueElement; + +import java.util.BitSet; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +import static org.apache.flink.util.Preconditions.checkState; + +/** + * A {@link WatermarkCombiner} for unaligned {@link LongWatermark}s. + * + *

The combination process will perform the following steps: (1) determine if it satisfies the + * condition of {@link WatermarkCombinationPolicy#isCombineWaitForAllChannels()}, (2) calculate the + * combined watermark value, (3) send the combined watermark to downstream only when the value + * differs from the previous sent one or if it's the first time sending. + */ +public class LongWatermarkCombiner implements WatermarkCombiner { + + private final WatermarkCombinationPolicy combinationPolicy; + + /** The number of upstream input channels. */ + private final int numberOfInputChannels; + + /** A bitset to record whether the watermark has been received from each channel. */ + private final BitSet hasReceiveWatermarks; + + /** Channel index to {@link LongWatermarkElement}. */ + private final Map channelWatermarks; + + /** A heap-based priority queue to help find the minimum/maximum watermark. */ + private final HeapPriorityQueue orderedChannelWatermarks; + + /** The comparator to compare the watermark value of two {@link LongWatermarkElement}s. */ + private final HeapPriorityQueue.PriorityComparator watermarkComparator; + + /** + * Send only the watermark that differs from the previous sent one, we need to record the + * previous sent watermark value and whether is the first time sending. + */ + private final LongWatermarkElement previousEmitWatermarkElement = new LongWatermarkElement(-1); + + private boolean isFirstTimeEmit = true; + + public LongWatermarkCombiner( + WatermarkCombinationPolicy combinationPolicy, int numberOfInputChannels) { + checkState( + combinationPolicy.getWatermarkCombinationFunction() + instanceof + WatermarkCombinationFunction.NumericWatermarkCombinationFunction); + this.combinationPolicy = combinationPolicy; + this.numberOfInputChannels = numberOfInputChannels; + this.hasReceiveWatermarks = new BitSet(numberOfInputChannels); + this.channelWatermarks = new HashMap<>(numberOfInputChannels); + + // according to the combination strategy create the comparator and the {@link + // LongWatermarkElement} initial value + long initValue; + if (combinationPolicy.getWatermarkCombinationFunction() + == WatermarkCombinationFunction.NumericWatermarkCombinationFunction.MIN) { + this.watermarkComparator = + (left, right) -> + Long.compare(left.getWatermarkValue(), right.getWatermarkValue()); + initValue = Long.MAX_VALUE; + } else { + this.watermarkComparator = + (left, right) -> + Long.compare(right.getWatermarkValue(), left.getWatermarkValue()); + initValue = Long.MIN_VALUE; + } + + // init the watermark elements of {@code #channelWatermarks} and {@code + // #orderedChannelWatermarks} + this.orderedChannelWatermarks = + new HeapPriorityQueue<>(watermarkComparator, numberOfInputChannels); + for (int i = 0; i < numberOfInputChannels; i++) { + LongWatermarkElement watermarkElement = new LongWatermarkElement(initValue); + channelWatermarks.put(i, watermarkElement); + orderedChannelWatermarks.add(watermarkElement); + } + } + + @Override + public void combineWatermark( + Watermark watermark, int channelIndex, Consumer watermarkEmitter) { + checkState(watermark instanceof LongWatermark); + + hasReceiveWatermarks.set(channelIndex); + // Update the watermark for the current channel + channelWatermarks + .get(channelIndex) + .setWatermarkValue(((LongWatermark) watermark).getValue()); + orderedChannelWatermarks.adjustModifiedElement(channelWatermarks.get(channelIndex)); + + if (combinationPolicy.isCombineWaitForAllChannels() + && hasReceiveWatermarks.cardinality() < numberOfInputChannels) { + // Not all watermarks have been received yet + return; + } + + // the combined watermark should be the first node of {@code orderedChannelWatermarks} + + if (shouldEmitWatermark(orderedChannelWatermarks.peek())) { + // send the combined watermark to downstream + watermarkEmitter.accept( + new LongWatermark( + orderedChannelWatermarks.peek().getWatermarkValue(), + watermark.getIdentifier())); + previousEmitWatermarkElement.setWatermarkValue( + orderedChannelWatermarks.peek().getWatermarkValue()); + } + } + + private boolean shouldEmitWatermark(LongWatermarkElement combinedWatermarkElement) { + if (isFirstTimeEmit) { + isFirstTimeEmit = false; + return true; + } + return watermarkComparator.comparePriority( + combinedWatermarkElement, previousEmitWatermarkElement) + != 0; + } + + /** + * This class implements {@link HeapPriorityQueueElement} to help find the maximum/minimum + * {@link LongWatermark}. + */ + protected static class LongWatermarkElement implements HeapPriorityQueueElement { + private long watermarkValue; + + /** + * This field holds the current physical index of this watermark when it is managed by a + * {@link HeapPriorityQueue}. + */ + private int heapIndex = HeapPriorityQueueElement.NOT_CONTAINED; + + public LongWatermarkElement(long watermarkValue) { + this.watermarkValue = watermarkValue; + } + + @Override + public int getInternalIndex() { + return heapIndex; + } + + @Override + public void setInternalIndex(int newIndex) { + this.heapIndex = newIndex; + } + + public void setWatermarkValue(long watermarkValue) { + this.watermarkValue = watermarkValue; + } + + public long getWatermarkValue() { + return watermarkValue; + } + } +} diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/WatermarkCombiner.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/WatermarkCombiner.java new file mode 100644 --- /dev/null +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/WatermarkCombiner.java @@ -0,0 +1,35 @@ +/* + * 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.runtime.watermark; + +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.api.common.watermark.WatermarkCombinationPolicy; +import org.apache.flink.api.common.watermark.WatermarkDeclaration; + +import java.util.function.Consumer; + +/** + * A class used to combine {@link Watermark}s. The combiner will be created by {@link + * WatermarkDeclaration} according to the {@link WatermarkCombinationPolicy}. + */ +public interface WatermarkCombiner { + void combineWatermark( + Watermark watermark, int channelIndex, Consumer watermarkEmitter) + throws Exception; +} diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermarkstatus/HeapPriorityQueue.java b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermarkstatus/HeapPriorityQueue.java --- a/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermarkstatus/HeapPriorityQueue.java +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermarkstatus/HeapPriorityQueue.java @@ -249,7 +249,7 @@ private int increaseSizeByOne() { * * @param type of the compared objects. */ - interface PriorityComparator { + public interface PriorityComparator { /** * Compares two objects for priority. Returns a negative integer, zero, or a positive @@ -267,7 +267,7 @@ interface PriorityComparator { * Interface for objects that can be managed by a {@link HeapPriorityQueue}. Such an object can * only be contained in at most one {@link HeapPriorityQueue} at a time. */ - interface HeapPriorityQueueElement { + public interface HeapPriorityQueueElement { /** * The index that indicates that a {@link HeapPriorityQueueElement} object is not contained diff --git a/flink-runtime/src/main/java/org/apache/flink/streaming/util/watermark/WatermarkUtils.java b/flink-runtime/src/main/java/org/apache/flink/streaming/util/watermark/WatermarkUtils.java new file mode 100644 --- /dev/null +++ b/flink-runtime/src/main/java/org/apache/flink/streaming/util/watermark/WatermarkUtils.java @@ -0,0 +1,98 @@ +/* + * 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.util.watermark; + +import org.apache.flink.api.common.functions.Function; +import org.apache.flink.api.common.watermark.Watermark; +import org.apache.flink.api.common.watermark.WatermarkDeclaration; +import org.apache.flink.datastream.api.function.ProcessFunction; +import org.apache.flink.runtime.asyncprocessing.operators.AbstractAsyncStateUdfStreamOperator; +import org.apache.flink.streaming.api.graph.StreamGraph; +import org.apache.flink.streaming.api.graph.StreamNode; +import org.apache.flink.streaming.api.operators.SimpleOperatorFactory; +import org.apache.flink.streaming.api.operators.SourceOperatorFactory; +import org.apache.flink.streaming.api.operators.StreamOperator; +import org.apache.flink.streaming.runtime.watermark.AbstractInternalWatermarkDeclaration; + +import java.util.Collection; +import java.util.Collections; +import java.util.Set; +import java.util.stream.Collectors; + +/** Utils class for {@link Watermark}. */ +public final class WatermarkUtils { + + /** + * Retrieve the declared watermarks from StreamGraph and convert them into {@code + * InternalWatermarkDeclaration}. + */ + public static Set> + getInternalWatermarkDeclarationsFromStreamGraph(StreamGraph streamGraph) { + Collection streamNodes = streamGraph.getStreamNodes(); + Set declarations = + streamNodes.stream() + .map(StreamNode::getOperatorFactory) + .filter( + factory -> + factory instanceof SimpleOperatorFactory + || factory instanceof SourceOperatorFactory) + .map( + factory -> { + if (factory instanceof SimpleOperatorFactory) { + return getWatermarkDeclarations( + ((SimpleOperatorFactory) factory).getOperator()); + } else { + return ((SourceOperatorFactory) factory) + .getSourceWatermarkDeclarations(); + } + }) + .flatMap(Collection::stream) + .collect(Collectors.toSet()); + return convertToInternalWatermarkDeclarations(declarations); + } + + /** + * Retrieve the user-defined {@link WatermarkDeclaration}s of {@link ProcessFunction}. The + * {@link WatermarkDeclaration} defined by the source operator can be retrieved from {@link + * SourceOperatorFactory#getSourceWatermarkDeclarations()}. + */ + private static Collection getWatermarkDeclarations( + StreamOperator streamOperator) { + if (streamOperator instanceof AbstractAsyncStateUdfStreamOperator) { + Function f = + ((AbstractAsyncStateUdfStreamOperator) streamOperator).getUserFunction(); + if (f instanceof ProcessFunction) { + return ((ProcessFunction) f).declareWatermarks(); + } + } + return Collections.emptySet(); + } + + /** + * Convert user-oriented {@link WatermarkDeclaration} instance to internal-oriented {@link + * AbstractInternalWatermarkDeclaration} instance. + */ + public static Set> + convertToInternalWatermarkDeclarations( + Set watermarkDeclarations) { + return watermarkDeclarations.stream() + .map(AbstractInternalWatermarkDeclaration::from) + .collect(Collectors.toSet()); + } +} diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/BroadcastingOutput.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/BroadcastingOutput.java --- a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/BroadcastingOutput.java +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/BroadcastingOutput.java @@ -18,6 +18,7 @@ package org.apache.flink.table.runtime.operators.multipleinput.output; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.operators.Output; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker; @@ -98,4 +99,11 @@ public void emitRecordAttributes(RecordAttributes recordAttributes) { output.emitRecordAttributes(recordAttributes); } } + + @Override + public void emitWatermark(WatermarkEvent watermark) { + for (Output> output : outputs) { + output.emitWatermark(watermark); + } + } } diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/CopyingSecondInputOfTwoInputStreamOperatorOutput.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/CopyingSecondInputOfTwoInputStreamOperatorOutput.java --- a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/CopyingSecondInputOfTwoInputStreamOperatorOutput.java +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/CopyingSecondInputOfTwoInputStreamOperatorOutput.java @@ -19,6 +19,7 @@ package org.apache.flink.table.runtime.operators.multipleinput.output; import org.apache.flink.api.common.typeutils.TypeSerializer; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.operators.Output; import org.apache.flink.streaming.api.operators.TwoInputStreamOperator; import org.apache.flink.streaming.api.watermark.Watermark; @@ -82,6 +83,15 @@ public void emitRecordAttributes(RecordAttributes recordAttributes) { } } + @Override + public void emitWatermark(WatermarkEvent watermark) { + try { + operator.processWatermark2(watermark); + } catch (Exception e) { + throw new ExceptionInMultipleInputOperatorException(e); + } + } + @Override public void collect(StreamRecord record) { pushToOperator(record); diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/FirstInputOfTwoInputStreamOperatorOutput.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/FirstInputOfTwoInputStreamOperatorOutput.java --- a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/FirstInputOfTwoInputStreamOperatorOutput.java +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/FirstInputOfTwoInputStreamOperatorOutput.java @@ -18,6 +18,7 @@ package org.apache.flink.table.runtime.operators.multipleinput.output; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.operators.Output; import org.apache.flink.streaming.api.operators.TwoInputStreamOperator; import org.apache.flink.streaming.api.watermark.Watermark; @@ -78,6 +79,15 @@ public void emitRecordAttributes(RecordAttributes recordAttributes) { } } + @Override + public void emitWatermark(WatermarkEvent watermark) { + try { + operator.processWatermark1(watermark); + } catch (Exception e) { + throw new ExceptionInMultipleInputOperatorException(e); + } + } + @Override public void collect(StreamRecord record) { pushToOperator(record); diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/OneInputStreamOperatorOutput.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/OneInputStreamOperatorOutput.java --- a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/OneInputStreamOperatorOutput.java +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/OneInputStreamOperatorOutput.java @@ -18,6 +18,7 @@ package org.apache.flink.table.runtime.operators.multipleinput.output; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.operators.OneInputStreamOperator; import org.apache.flink.streaming.api.operators.Output; import org.apache.flink.streaming.api.watermark.Watermark; @@ -77,6 +78,15 @@ public void emitRecordAttributes(RecordAttributes recordAttributes) { } } + @Override + public void emitWatermark(WatermarkEvent watermark) { + try { + operator.processWatermark(watermark); + } catch (Exception e) { + throw new ExceptionInMultipleInputOperatorException(e); + } + } + @Override public void collect(StreamRecord record) { pushToOperator(record); diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/SecondInputOfTwoInputStreamOperatorOutput.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/SecondInputOfTwoInputStreamOperatorOutput.java --- a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/SecondInputOfTwoInputStreamOperatorOutput.java +++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/SecondInputOfTwoInputStreamOperatorOutput.java @@ -18,6 +18,7 @@ package org.apache.flink.table.runtime.operators.multipleinput.output; +import org.apache.flink.runtime.event.WatermarkEvent; import org.apache.flink.streaming.api.operators.Output; import org.apache.flink.streaming.api.operators.TwoInputStreamOperator; import org.apache.flink.streaming.api.watermark.Watermark; @@ -78,6 +79,15 @@ public void emitRecordAttributes(RecordAttributes recordAttributes) { } } + @Override + public void emitWatermark(WatermarkEvent watermark) { + try { + operator.processWatermark2(watermark); + } catch (Exception e) { + throw new ExceptionInMultipleInputOperatorException(e); + } + } + @Override public void collect(StreamRecord record) { pushToOperator(record); diff --git a/pom.xml b/pom.xml --- a/pom.xml +++ b/pom.xml @@ -2398,6 +2398,9 @@ under the License. org.apache.flink.api.connector.sink2.Sink org.apache.flink.walkthrough.common.source.TransactionSource + + org.apache.flink.api.connector.source.Source + org.apache.flink.api.connector.source.SourceReaderContext public