gyfora commented on code in PR #1231:
URL: 
https://github.com/apache/flink-kubernetes-operator/pull/1231#discussion_r4710455085


##########
flink-kubernetes-operator-bluegreen-client/src/main/java/org/apache/flink/kubernetes/operator/bluegreen/client/WatermarkGateProcessFunction.java:
##########
@@ -0,0 +1,366 @@
+/*
+ * 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.kubernetes.operator.bluegreen.client;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.functions.OpenContext;
+import 
org.apache.flink.kubernetes.operator.api.bluegreen.BlueGreenDeploymentType;
+import org.apache.flink.kubernetes.operator.api.bluegreen.GateContext;
+import org.apache.flink.kubernetes.operator.api.bluegreen.GateMetrics;
+import org.apache.flink.kubernetes.operator.api.bluegreen.GateOutputMode;
+import org.apache.flink.kubernetes.operator.api.bluegreen.TransitionStage;
+import org.apache.flink.metrics.Gauge;
+import org.apache.flink.streaming.api.TimerService;
+import org.apache.flink.streaming.api.functions.ProcessFunction;
+import org.apache.flink.util.Collector;
+import org.apache.flink.util.Preconditions;
+
+import java.io.Serializable;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+
+/** Watermark based GateProcessFunction (streaming). */
+public class WatermarkGateProcessFunction<I> extends GateProcessFunction<I>
+        implements Serializable {
+
+    // A standby subtask without a record for this long since it learned the 
toggle owes nothing to
+    // the hand-over: there is nothing it could still emit before its 
watermark passes the toggle.
+    @VisibleForTesting static final long IDLE_DONE_MS = 30_000L;
+
+    private final Function<I, Long> watermarkExtractor;
+
+    private WatermarkGateContext currentWatermarkGateContext;
+
+    // Hand-over progress, read by the HAND_OVER_DONE gauge from the metric 
reporter's thread
+    private transient volatile boolean pastToggle;
+    private transient volatile long toggleKnownSince = -1L;
+    private transient volatile long lastRecordAt = -1L;
+
+    // What this subtask does with its records, and for which toggle, as last 
logged
+    private transient Decision decision;
+    private transient Long decisionToggle;
+    private transient boolean noWatermarkLogged;
+
+    WatermarkGateProcessFunction(
+            BlueGreenDeploymentType blueGreenDeploymentType,
+            String namespace,
+            String configMapName,
+            Function<I, Long> watermarkExtractor) {
+        super(blueGreenDeploymentType, namespace, configMapName);
+
+        Preconditions.checkNotNull(watermarkExtractor);
+
+        this.watermarkExtractor = watermarkExtractor;
+    }
+
+    /**
+     * Creates the gate of a job deployed by a FlinkBlueGreenDeployment in the 
ADVANCED transition
+     * mode, to be placed in front of the operator that writes the job's 
output.
+     *
+     * @param flinkConfig the job's configuration, e.g. {@code 
env.getConfiguration().toMap()}, in
+     *     which the operator sets the keys the gate needs
+     * @param watermarkExtractor the epoch milliseconds of a record's event 
time, the time the job's
+     *     watermark is built from, or {@code null} for a record without one. 
It is shipped with the
+     *     gate, so a lambda or method reference passed here is made 
serializable.
+     */
+    public static <I> WatermarkGateProcessFunction<I> create(
+            Map<String, String> flinkConfig, WatermarkExtractor<I> 
watermarkExtractor) {
+        requireConfigKey(flinkConfig, "bluegreen.active-deployment-type");
+        requireConfigKey(flinkConfig, "kubernetes.namespace");
+        requireConfigKey(flinkConfig, "bluegreen.configmap.name");
+        return new WatermarkGateProcessFunction<I>(
+                BlueGreenDeploymentType.valueOf(
+                        flinkConfig.get("bluegreen.active-deployment-type")),
+                flinkConfig.get("kubernetes.namespace"),
+                flinkConfig.get("bluegreen.configmap.name"),
+                watermarkExtractor);
+    }
+
+    private static void requireConfigKey(Map<String, String> config, String 
key) {
+        if (config.get(key) == null) {
+            throw new IllegalArgumentException(
+                    "WatermarkGateProcessFunction requires config key '"
+                            + key
+                            + "' to be set. The operator sets it on the 
deployments of a"
+                            + " FlinkBlueGreenDeployment in the ADVANCED 
transition mode: pass the"
+                            + " job's configuration, e.g. 
env.getConfiguration().toMap().");
+        }
+    }
+
+    @Override
+    public void open(OpenContext openContext) throws Exception {
+        // Deserialization does not run field initializers: set the progress 
before super.open()
+        // reads the ConfigMap for the first time
+        pastToggle = false;
+        toggleKnownSince = -1L;
+        lastRecordAt = -1L;
+        decision = null;
+        decisionToggle = null;
+        noWatermarkLogged = false;
+        super.open(openContext);
+        getRuntimeContext()
+                .getMetricGroup()
+                .gauge(
+                        GateMetrics.HAND_OVER_DONE,
+                        (Gauge<Integer>) () -> 
isHandOverDone(System.currentTimeMillis()) ? 1 : 0);
+    }
+
+    /**
+     * Whether this subtask, as the standby, has nothing left to emit for the 
hand-over: its
+     * watermark has passed the toggle, or it has had no record for {@link 
#IDLE_DONE_MS} since it
+     * learned the toggle. A subtask that receives no records never sees its 
watermark pass the
+     * toggle, but it owes nothing either.
+     */
+    @VisibleForTesting
+    boolean isHandOverDone(long now) {
+        if (pastToggle) {
+            return true;
+        }
+        long since = toggleKnownSince;
+        return since >= 0 && now - Math.max(since, lastRecordAt) >= 
IDLE_DONE_MS;
+    }
+
+    @Override
+    protected void onContextUpdate(GateContext baseContext, Map<String, 
String> data) {
+        var fetchedWatermarkContext = WatermarkGateContext.create(baseContext, 
data);
+        logDebug("Refreshing WatermarkGateContext with data: " + data);
+
+        if (currentWatermarkGateContext == null) {
+            logInfo("currentWatermarkGateContext INITIALIZED: " + 
fetchedWatermarkContext);
+            currentWatermarkGateContext = fetchedWatermarkContext;
+        } else if 
(!currentWatermarkGateContext.equals(fetchedWatermarkContext)) {
+            logInfo("currentWatermarkGateContext UPDATED: " + 
fetchedWatermarkContext);
+            currentWatermarkGateContext = fetchedWatermarkContext;
+        }
+        trackToggle(currentWatermarkGateContext.getWatermarkToggleValue());
+    }
+
+    /** A new transition starts without a toggle, which resets the hand-over 
progress. */
+    private void trackToggle(Long toggle) {
+        if (toggle == null) {
+            pastToggle = false;
+            toggleKnownSince = -1L;
+        } else {
+            noWatermarkLogged = false;
+            if (toggleKnownSince < 0) {
+                toggleKnownSince = System.currentTimeMillis();
+            }
+        }
+    }
+
+    @Override
+    protected void processElementActive(
+            I value, ProcessFunction<I, I>.Context ctx, Collector<I> out)
+            throws IllegalAccessException {
+        Long wmToggleValue = 
currentWatermarkGateContext.getWatermarkToggleValue();
+        if (wmToggleValue != null) {
+            if (isFullyOpen(ctx.timerService(), wmToggleValue)) {
+                decide(
+                        
currentWatermarkGateContext.getBaseContext().isFirstDeployment()
+                                ? Decision.PASS_ALL
+                                : Decision.PASS_ALL_PAST_TOGGLE,
+                        wmToggleValue);
+                out.collect(value);
+                return;
+            }
+            decide(Decision.PASS_FROM_TOGGLE, wmToggleValue);
+            if (wmToggleValue <= timestampOf(value)) {
+                out.collect(value);
+            }
+        } else {
+            // Transitioning to Active
+            var currentGateStage = 
currentWatermarkGateContext.getBaseContext().getGateStage();
+            if (currentGateStage == TransitionStage.TRANSITIONING) {
+                decide(Decision.HOLD_UNTIL_TOGGLE, null);
+                notifyWaitingForWatermark(ctx);
+            } else {
+                decide(Decision.HOLD_UNTIL_TRANSITION, null);

Review Comment:
   Overall I find these gate process function implementations very complex, I 
wouldn't expect anyone to be able to use these interfaces / implementations 
correctly in this form
   
   Is there a way that we could simplify this into a pluggable utility that 
users could use within their existing operator (ProcessFunction, 
KeyedProcessFunction, ... etc)
   
   ```
   WatermarkGate gate = WatermarkGate.create(....) / initialize in open 
   
   
   // During record processing
   if (gate.shouldProcess(ctx.getTimestamp())) {
     out.collect(processedData)
   }
   
   ```
   
   It's also a bit weird to pass a watermark extractor to the function, the 
watermark should come from upstream, and received by the underlying stream 
operator.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to