rkhachatryan commented on a change in pull request #16606: URL: https://github.com/apache/flink/pull/16606#discussion_r717260198
########## File path: flink-state-backends/flink-statebackend-changelog/src/main/java/org/apache/flink/state/changelog/materializer/PeriodicMaterializer.java ########## @@ -0,0 +1,263 @@ +/* + * 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.state.changelog.materializer; + +import org.apache.flink.annotation.VisibleForTesting; +import org.apache.flink.core.fs.FileSystemSafetyNet; +import org.apache.flink.runtime.checkpoint.CheckpointOptions; +import org.apache.flink.runtime.checkpoint.CheckpointType; +import org.apache.flink.runtime.mailbox.MailboxExecutor; +import org.apache.flink.runtime.state.CheckpointStorageLocationReference; +import org.apache.flink.runtime.state.CheckpointStorageWorkerView; +import org.apache.flink.runtime.state.CheckpointStreamFactory; +import org.apache.flink.runtime.state.KeyedStateHandle; +import org.apache.flink.runtime.state.SnapshotResult; +import org.apache.flink.runtime.state.Snapshotable; +import org.apache.flink.runtime.state.StateObject; +import org.apache.flink.runtime.state.changelog.ChangelogStateHandle; +import org.apache.flink.runtime.state.changelog.SequenceNumber; +import org.apache.flink.runtime.state.changelog.StateChangelogWriter; +import org.apache.flink.util.concurrent.ExecutorThreadFactory; +import org.apache.flink.util.concurrent.FutureUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nonnull; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RunnableFuture; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; +import static org.apache.flink.util.Preconditions.checkState; + +/** Periodically make materialization for the delegated state backend. */ +public class PeriodicMaterializer { + private static final Logger LOG = LoggerFactory.getLogger(PeriodicMaterializer.class); + + /** + * ChangelogStateBackend only supports CheckpointType.CHECKPOINT; The rest of information in + * CheckpointOptions is not used in Snapshotable#snapshot(). More details in FLINK-23441. + */ + private static final CheckpointOptions CHECKPOINT_OPTIONS = + new CheckpointOptions( + CheckpointType.CHECKPOINT, CheckpointStorageLocationReference.getDefault()); + + /** task mailbox executor, execute from Task Thread. */ + private final MailboxExecutor mailboxExecutor; + + /** Async thread pool, to complete async phase of materialization. */ + private final ExecutorService asyncOperationsThreadPool; + + /** scheduled executor, periodically trigger materialization. */ + private final ScheduledExecutorService periodicExecutor; + + private final CheckpointStreamFactory streamFactory; + + private final Snapshotable keyedStateBackend; + + private final StateChangelogWriter<ChangelogStateHandle> stateChangelogWriter; + + private final AsyncExceptionHandler asyncExceptionHandler; + + private final int allowedNumberOfFailures; + + /** Materialization failure retries. */ + private final AtomicInteger retries; + + /** Making sure only one materialization on going at a time. */ + private final AtomicBoolean materializationOnGoing; + + private long materializedId; + + private MaterializedState materializedState; + + public PeriodicMaterializer( + MailboxExecutor mailboxExecutor, + ExecutorService asyncOperationsThreadPool, + Snapshotable keyedStateBackend, + CheckpointStorageWorkerView checkpointStorageWorkerView, + StateChangelogWriter<ChangelogStateHandle> stateChangelogWriter, + AsyncExceptionHandler asyncExceptionHandler, + MaterializedState materializedState, + long periodicMaterializeInitDelay, + long periodicMaterializeInterval, + int allowedNumberOfFailures, + boolean materializationEnabled) { + this.mailboxExecutor = mailboxExecutor; + this.asyncOperationsThreadPool = asyncOperationsThreadPool; + this.keyedStateBackend = keyedStateBackend; + this.stateChangelogWriter = stateChangelogWriter; + this.asyncExceptionHandler = asyncExceptionHandler; + this.periodicExecutor = + Executors.newSingleThreadScheduledExecutor( + new ExecutorThreadFactory("periodic-materialization")); + this.streamFactory = shared -> checkpointStorageWorkerView.createTaskOwnedStateStream(); + this.allowedNumberOfFailures = allowedNumberOfFailures; + this.materializationOnGoing = new AtomicBoolean(false); + this.retries = new AtomicInteger(allowedNumberOfFailures); + + this.materializedId = 0; + this.materializedState = materializedState; + + if (materializationEnabled) { + this.periodicExecutor.scheduleAtFixedRate( + this::triggerMaterialization, + periodicMaterializeInitDelay, + periodicMaterializeInterval, + TimeUnit.MILLISECONDS); + } + } + + @VisibleForTesting + public void triggerMaterialization() { + mailboxExecutor.execute( + () -> { + // Only one materialization ongoing at a time + if (!materializationOnGoing.compareAndSet(false, true)) { + return; + } + + SequenceNumber upTo = stateChangelogWriter.lastAppendedSequenceNumber().next(); Review comment: Resolved by using the proposal [above](https://github.com/apache/flink/pull/16606#discussion_r682621905). ########## File path: flink-core/src/main/java/org/apache/flink/api/common/ExecutionConfig.java ########## @@ -127,13 +128,29 @@ private boolean forceAvro = false; private long autoWatermarkInterval = 200; + // ---------- statebackend related configurations ------------------------------ /** * Interval in milliseconds for sending latency tracking marks from the sources to the sinks. */ private long latencyTrackingInterval = MetricOptions.LATENCY_INTERVAL.defaultValue(); private boolean isLatencyTrackingConfigured = false; + /** Interval in milliseconds to perform periodic materialization. */ + private long periodicMaterializeInterval = + StateBackendOptions.PERIODIC_MATERIALIZATION_INTERVAL.defaultValue(); + + /** Interval in milliseconds for initial delay of periodic materialization. */ + private long periodicMaterializeInitDelay = + StateBackendOptions.PERIODIC_MATERIALIZATION_INIT_DELAY.defaultValue(); + + /** Max allowed number of failures */ + private int materializationMaxAllowedFailures = + StateBackendOptions.MATERIALIZATION_MAX_ALLOWED_FAILURES.defaultValue(); + + /** Flag to enable periodic materialization */ + private boolean isPeriodicMaterializationEnabled = false; Review comment: Resolved by removing the flag. ########## File path: pom.xml ########## @@ -1518,7 +1518,7 @@ under the License. random: enable it randomly, unless explicitly set unset: don't alter the configuration --> - <checkpointing.changelog>random</checkpointing.changelog> + <checkpointing.changelog>on</checkpointing.changelog> Review comment: Could you then move it to a separate commit please? ########## File path: pom.xml ########## @@ -1518,7 +1518,7 @@ under the License. random: enable it randomly, unless explicitly set unset: don't alter the configuration --> - <checkpointing.changelog>random</checkpointing.changelog> + <checkpointing.changelog>on</checkpointing.changelog> Review comment: Could you then move it to a separate commit please? (so that it's not accidentially merged) ########## File path: flink-state-backends/flink-statebackend-changelog/src/main/java/org/apache/flink/state/changelog/PeriodicMaterializationManager.java ########## @@ -0,0 +1,269 @@ +/* + * 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.state.changelog; + +import org.apache.flink.api.common.operators.MailboxExecutor; +import org.apache.flink.core.fs.FileSystemSafetyNet; +import org.apache.flink.runtime.state.KeyedStateHandle; +import org.apache.flink.runtime.state.SnapshotResult; +import org.apache.flink.runtime.state.StateObject; +import org.apache.flink.runtime.state.changelog.SequenceNumber; +import org.apache.flink.runtime.taskmanager.AsyncExceptionHandler; +import org.apache.flink.util.concurrent.ExecutorThreadFactory; +import org.apache.flink.util.concurrent.FutureUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.Closeable; +import java.util.Optional; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RunnableFuture; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.apache.flink.util.Preconditions.checkNotNull; + +/** Stateless Materialization Manager. */ +public class PeriodicMaterializationManager implements Closeable { + private static final Logger LOG = LoggerFactory.getLogger(PeriodicMaterializationManager.class); + + /** task mailbox executor, execute from Task Thread. */ + private final MailboxExecutor mailboxExecutor; + + /** Async thread pool, to complete async phase of materialization. */ + private final ExecutorService asyncOperationsThreadPool; + + /** scheduled executor, periodically trigger materialization. */ + private final ScheduledExecutorService periodicExecutor; + + private final AsyncExceptionHandler asyncExceptionHandler; + + private final String subtaskName; + + private final long periodicMaterializeDelay; + + /** Allowed number of consecutive materialization failures. */ + private final int allowedNumberOfFailures; + + /** Number of consecutive materialization failures. */ + private final AtomicInteger numberOfConsecutiveFailures; + + private final ChangelogKeyedStateBackend<?> keyedStateBackend; + + private boolean started = false; + + PeriodicMaterializationManager( + MailboxExecutor mailboxExecutor, + ExecutorService asyncOperationsThreadPool, + String subtaskName, + AsyncExceptionHandler asyncExceptionHandler, + ChangelogKeyedStateBackend<?> keyedStateBackend, + long periodicMaterializeDelay, + int allowedNumberOfFailures) { + this.mailboxExecutor = checkNotNull(mailboxExecutor); + this.asyncOperationsThreadPool = checkNotNull(asyncOperationsThreadPool); + this.subtaskName = checkNotNull(subtaskName); + this.asyncExceptionHandler = checkNotNull(asyncExceptionHandler); + this.keyedStateBackend = checkNotNull(keyedStateBackend); + + this.periodicMaterializeDelay = periodicMaterializeDelay; + this.allowedNumberOfFailures = allowedNumberOfFailures; + this.numberOfConsecutiveFailures = new AtomicInteger(0); + + this.periodicExecutor = + Executors.newSingleThreadScheduledExecutor( + new ExecutorThreadFactory( + "periodic-materialization-scheduler-" + subtaskName)); + } + + public void start() { + if (!started) { + + started = true; + + LOG.info( + "Task {} starts periodic materialization, scheduling the next one in {} seconds", + subtaskName, + periodicMaterializeDelay / 1000); + + scheduleNextMaterialization(); + } + } + + private void triggerMaterialization() { + mailboxExecutor.execute( + () -> { + Optional<MaterializationRunnable> materializationRunnableOptional = + keyedStateBackend.initMaterialization(); + + if (materializationRunnableOptional.isPresent()) { + MaterializationRunnable runnable = materializationRunnableOptional.get(); + asyncOperationsThreadPool.execute( + () -> + asyncMaterializationPhase( + runnable.getMaterializationRunnable(), + runnable.getMaterializedTo())); + } else { + scheduleNextMaterialization(); + + LOG.info( + "Task {} has no state updates since last materialization, " + + "skip this one and schedule the next one in {} seconds", + subtaskName, + periodicMaterializeDelay / 1000); + } + }, + "materialization"); + } + + private void asyncMaterializationPhase( + RunnableFuture<SnapshotResult<KeyedStateHandle>> materializedRunnableFuture, + SequenceNumber upTo) { + + SnapshotResult<KeyedStateHandle> materializedSnapshot = + uploadSnapshot(materializedRunnableFuture); + + // if succeed, update state and finish up + if (materializedSnapshot != null) { + + numberOfConsecutiveFailures.set(0); + + final SnapshotResult<KeyedStateHandle> copyMaterializedSnapshot = materializedSnapshot; + + mailboxExecutor.execute( + () -> + keyedStateBackend.updateChangelogSnapshotState( + copyMaterializedSnapshot, + upTo), + "Task {} update materializedSnapshot up to changelog sequence number: {}", + subtaskName, + upTo); + } + + LOG.info( + "Task {} schedules the next materialization in {} seconds.", + subtaskName, + periodicMaterializeDelay / 1000); + + scheduleNextMaterialization(); Review comment: > Do you mean it is possible that before failover is triggered, another materialization is triggered? > And what's the problem if scheduleNextMaterialization is called? Yes. One problem is that it likely will fail (because some of the executors is shut/ting down), and potentially prevent failover. If not, it's just unnecessary upload. Besides that, the code would be much cleaner IMO. ########## File path: flink-state-backends/flink-statebackend-changelog/src/test/resources/log4j2-test.properties ########## @@ -18,11 +18,11 @@ # Set root logger level to OFF to not flood build logs # set manually to INFO for debugging purposes -rootLogger.level = OFF +rootLogger.level = INFO Review comment: > I will change the logging level back. Thanks! > BTW, what's the problem for layout.pattern? Do you mean we should remove it? Actually, the change is correct, non-standard pattern was used before, sorry. Let's keep this change. -- 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]
