You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by GitBox <gi...@apache.org> on 2021/03/25 12:24:44 UTC
[GitHub] [flink] pnowojski opened a new pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
pnowojski opened a new pull request #15371:
URL: https://github.com/apache/flink/pull/15371
This PR supersedes https://github.com/apache/flink/pull/15322
## What is the purpose of the change
Add a DFS-based state changelog implementation.
## Verifying this change
Added unit tests: `BatchingStateChangeStoreTest`, `FsStateChangelogWriterSqnTest`, `FsStateChangelogWriterTest`
Added integration test: `StateChangelogClientTest`
Still not covered: `RetryingExecutor` (TBD)
Covered by integration test only: `StateChangeFormat`, `StateChangelogHandleStreamImpl` (TBD)
This change is a trivial rework without any test coverage.
## Does this pull request potentially affect one of the following parts:
- Dependencies (does it add or upgrade a dependency): no
- The public API, i.e., is any changed class annotated with `@Public(Evolving)`: no
- The serializers: no
- The runtime per-record code paths (performance sensitive): no
- Anything that affects deployment or recovery: JobManager (and its components), Checkpointing, Kubernetes/Yarn/Mesos, ZooKeeper: yes
- The S3 file system connector: no
## Documentation
- Does this pull request introduce a new feature? no
- If yes, how is the feature documented? no
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] rkhachatryan commented on a change in pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on a change in pull request #15371:
URL: https://github.com/apache/flink/pull/15371#discussion_r603174752
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -0,0 +1,173 @@
+/*
+ * 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.changelog.fs;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static java.lang.Thread.holdsLock;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.apache.flink.util.ExceptionUtils.findThrowable;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * A {@link StateChangeStore} that waits for some configured amount of time before passing the
+ * accumulated state changes to the actual store. The writes are executed asynchronously.
+ */
+@ThreadSafe
+class BatchingStateChangeStore implements StateChangeStore {
+ private static final Logger LOG = LoggerFactory.getLogger(BatchingStateChangeStore.class);
+
+ private final StateChangeStore delegate;
+ private final ScheduledExecutorService scheduler;
+ private final long scheduleDelayMs;
+ private final long sizeThresholdBytes;
+
+ @GuardedBy("scheduled")
+ private final Queue<StoreTask> scheduled;
+
+ @GuardedBy("scheduled")
+ private long scheduledSizeInBytes;
+
+ @GuardedBy("scheduled")
+ private Future<?> scheduledFuture = CompletableFuture.completedFuture(null);
+
+ private AtomicReference<Throwable> error = new AtomicReference<>(null);
+
+ BatchingStateChangeStore(
+ long persistDelayMs, long sizeThresholdBytes, StateChangeStore delegate) {
+ this(
+ persistDelayMs,
+ sizeThresholdBytes,
+ delegate,
+ SchedulerFactory.create(1, "ChangelogRetryScheduler", LOG));
+ }
+
+ BatchingStateChangeStore(
+ long persistDelayMs,
+ long sizeThresholdBytes,
+ StateChangeStore delegate,
+ ScheduledExecutorService scheduler) {
+ this.scheduleDelayMs = persistDelayMs;
+ this.scheduled = new LinkedList<>();
+ this.scheduler = scheduler;
+ this.sizeThresholdBytes = sizeThresholdBytes;
+ this.delegate = delegate;
+ }
+
+ @Override
+ public void save(StoreTask storeTask) {
+ Collection<StateChangeSet> changeSets = storeTask.changeSets;
+ if (error.get() != null) {
+ LOG.debug("don't persist {} changesets, already failed", changeSets.size());
+ storeTask.fail(error.get());
+ return;
+ }
+ LOG.debug("persist {} changeSets", changeSets.size());
+ try {
+ synchronized (scheduled) {
+ scheduled.add(storeTask);
+ scheduledSizeInBytes += storeTask.getSize();
+ scheduleUploadIfNeeded();
+ }
+ } catch (Exception e) {
+ storeTask.fail(e);
+ throw e;
+ }
+ }
+
+ private void scheduleUploadIfNeeded() {
+ checkState(holdsLock(scheduled));
+ if (scheduledFuture.isDone() || isOverSizeThresholdAndCancellationSucceded()) {
+ scheduleUpload();
+ }
+ }
+
+ private boolean isOverSizeThresholdAndCancellationSucceded() {
+ return scheduledSizeInBytes >= sizeThresholdBytes && scheduledFuture.cancel(false);
+ }
Review comment:
IIUC, if `drainAndSave` is being executed but it already passed the re-scheduling section (2) then nothing will be scheduled.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #15371:
URL: https://github.com/apache/flink/pull/15371#issuecomment-806671834
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "202eb502220b8ecd709583c531c65847a37065f2",
"status" : "FAILURE",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=15461",
"triggerID" : "202eb502220b8ecd709583c531c65847a37065f2",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 202eb502220b8ecd709583c531c65847a37065f2 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=15461)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] rkhachatryan commented on a change in pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on a change in pull request #15371:
URL: https://github.com/apache/flink/pull/15371#discussion_r603172057
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/FsStateChangelogWriter.java
##########
@@ -0,0 +1,213 @@
+/*
+ * 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.changelog.fs;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.changelog.fs.StateChangeStore.StoreTask;
+import org.apache.flink.runtime.state.KeyGroupRange;
+import org.apache.flink.runtime.state.StreamStateHandle;
+import org.apache.flink.runtime.state.changelog.SequenceNumber;
+import org.apache.flink.runtime.state.changelog.StateChange;
+import org.apache.flink.runtime.state.changelog.StateChangelogHandleStreamImpl;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriter;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriterFactory.ChangelogCallbackExecutor;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.NotThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Basic implementation of {@link StateChangelogWriter}. It's main purpose is to keep track which
+ * changes are required for the given {@link #persist(SequenceNumber)} call. Especially it takes
+ * care of re-uploading changes from the previous {@link #persist(SequenceNumber)} call, if those
+ * changes haven't been yet {@link #confirm(SequenceNumber, SequenceNumber)}'ed. This is crucial as
+ * until changes are {@link #confirm(SequenceNumber, SequenceNumber)}, they still can be aborted and
+ * removed/deleted.
+ *
+ * <p>For example if checkpoint N-1 fails and is disposed, after checkpoint N has already started.
+ * In this case, when we are persisting {@link StateChangeSet}s for checkpoint N, we need to
+ * re-upload {@link StateChangeSet}s that belonged to checkpoint N-1.
+ */
+@NotThreadSafe
+class FsStateChangelogWriter implements StateChangelogWriter<StateChangelogHandleStreamImpl> {
+ private static final Logger LOG = LoggerFactory.getLogger(FsStateChangelogWriter.class);
+
+ private final UUID logId;
+ private final KeyGroupRange keyGroupRange;
+ private final StateChangeStore store;
+ private final NavigableMap<SequenceNumber, StateChangeSet> changeSets = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> uploaded = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> confirmed = new TreeMap<>();
+ private List<StateChange> activeChangeSet = new ArrayList<>();
+ private SequenceNumber lastAppendedSequenceNumber = SequenceNumber.of(0L);
+ private boolean closed;
+ private final ChangelogCallbackExecutor executor;
+
+ FsStateChangelogWriter(
+ UUID logId,
+ KeyGroupRange keyGroupRange,
+ StateChangeStore store,
+ ChangelogCallbackExecutor executor) {
+ this.logId = logId;
+ this.keyGroupRange = keyGroupRange;
+ this.store = store;
+ this.executor = checkNotNull(executor);
+ }
+
+ @Override
+ public void append(int keyGroup, byte[] value) {
+ LOG.trace("append to {}: keyGroup={} {} bytes", logId, keyGroup, value.length);
+ checkState(!closed, "%s is closed", logId);
+ activeChangeSet.add(new StateChange(keyGroup, value));
+ // size threshold could be added to call persist when reached. considerations:
+ // 0. can actually degrade performance by amplifying number of requests
+ // 1. which range to persist?
+ // 2. how to deal with retries/aborts?
+ }
+
+ @Override
+ public SequenceNumber lastAppendedSequenceNumber() {
+ rollover();
+ LOG.trace("query {} sqn: {}", logId, lastAppendedSequenceNumber);
+ return lastAppendedSequenceNumber;
+ }
+
+ @Override
+ public CompletableFuture<StateChangelogHandleStreamImpl> persist(SequenceNumber from)
+ throws IOException {
+ LOG.debug("persist {} from {}", logId, from);
+ checkNotNull(from);
+ // todo: check range
+
+ rollover();
+ Collection<StoreResult> readyToReturn = confirmed.tailMap(from, true).values();
+ Collection<StateChangeSet> toUpload = changeSets.tailMap(from, true).values();
+ LOG.debug("collected readyToReturn: {}, toUpload: {}", readyToReturn, toUpload);
+
+ StoreTask task = new StoreTask(toUpload);
+ // Handle the result result in supplied executor (mailbox) thread
+ CompletableFuture<StateChangelogHandleStreamImpl> resultFuture =
+ task.getResultFuture()
+ .thenApplyAsync(
+ (results) -> {
+ results.forEach(e -> uploaded.put(e.sequenceNumber, e));
Review comment:
I'm afraid that not supporting aborts can have performance consequences (having more uploads than needed).
Replacing the newer upload with an older one makes the future snapshots incorrect.
So this solution will be neither correct nor informative to estimate efficiency/performance.
As for changing the ownership of checkpoints or logs - seems a much bigger effort. If we decide not to do that (quite likely I suppose) then this code will change significantly and will become more complex (adding pre-uploads also adds complexity).
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #15371:
URL: https://github.com/apache/flink/pull/15371#issuecomment-806671834
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "202eb502220b8ecd709583c531c65847a37065f2",
"status" : "DELETED",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=15461",
"triggerID" : "202eb502220b8ecd709583c531c65847a37065f2",
"triggerType" : "PUSH"
}, {
"hash" : "def801eb5580ad2e14fe4c8dcd0629caf6582d1d",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "def801eb5580ad2e14fe4c8dcd0629caf6582d1d",
"triggerType" : "PUSH"
}, {
"hash" : "e350c69e02165b688a58f381920725ade9301521",
"status" : "SUCCESS",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=15482",
"triggerID" : "e350c69e02165b688a58f381920725ade9301521",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* def801eb5580ad2e14fe4c8dcd0629caf6582d1d UNKNOWN
* e350c69e02165b688a58f381920725ade9301521 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=15482)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] rkhachatryan commented on a change in pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on a change in pull request #15371:
URL: https://github.com/apache/flink/pull/15371#discussion_r602353460
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/FsStateChangelogWriter.java
##########
@@ -0,0 +1,213 @@
+/*
+ * 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.changelog.fs;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.changelog.fs.StateChangeStore.StoreTask;
+import org.apache.flink.runtime.state.KeyGroupRange;
+import org.apache.flink.runtime.state.StreamStateHandle;
+import org.apache.flink.runtime.state.changelog.SequenceNumber;
+import org.apache.flink.runtime.state.changelog.StateChange;
+import org.apache.flink.runtime.state.changelog.StateChangelogHandleStreamImpl;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriter;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriterFactory.ChangelogCallbackExecutor;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.NotThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Basic implementation of {@link StateChangelogWriter}. It's main purpose is to keep track which
+ * changes are required for the given {@link #persist(SequenceNumber)} call. Especially it takes
+ * care of re-uploading changes from the previous {@link #persist(SequenceNumber)} call, if those
+ * changes haven't been yet {@link #confirm(SequenceNumber, SequenceNumber)}'ed. This is crucial as
+ * until changes are {@link #confirm(SequenceNumber, SequenceNumber)}, they still can be aborted and
+ * removed/deleted.
+ *
+ * <p>For example if checkpoint N-1 fails and is disposed, after checkpoint N has already started.
+ * In this case, when we are persisting {@link StateChangeSet}s for checkpoint N, we need to
+ * re-upload {@link StateChangeSet}s that belonged to checkpoint N-1.
+ */
+@NotThreadSafe
+class FsStateChangelogWriter implements StateChangelogWriter<StateChangelogHandleStreamImpl> {
+ private static final Logger LOG = LoggerFactory.getLogger(FsStateChangelogWriter.class);
+
+ private final UUID logId;
+ private final KeyGroupRange keyGroupRange;
+ private final StateChangeStore store;
+ private final NavigableMap<SequenceNumber, StateChangeSet> changeSets = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> uploaded = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> confirmed = new TreeMap<>();
+ private List<StateChange> activeChangeSet = new ArrayList<>();
+ private SequenceNumber lastAppendedSequenceNumber = SequenceNumber.of(0L);
+ private boolean closed;
+ private final ChangelogCallbackExecutor executor;
+
+ FsStateChangelogWriter(
+ UUID logId,
+ KeyGroupRange keyGroupRange,
+ StateChangeStore store,
+ ChangelogCallbackExecutor executor) {
+ this.logId = logId;
+ this.keyGroupRange = keyGroupRange;
+ this.store = store;
+ this.executor = checkNotNull(executor);
+ }
+
+ @Override
+ public void append(int keyGroup, byte[] value) {
+ LOG.trace("append to {}: keyGroup={} {} bytes", logId, keyGroup, value.length);
+ checkState(!closed, "%s is closed", logId);
+ activeChangeSet.add(new StateChange(keyGroup, value));
+ // size threshold could be added to call persist when reached. considerations:
+ // 0. can actually degrade performance by amplifying number of requests
+ // 1. which range to persist?
+ // 2. how to deal with retries/aborts?
+ }
+
+ @Override
+ public SequenceNumber lastAppendedSequenceNumber() {
+ rollover();
+ LOG.trace("query {} sqn: {}", logId, lastAppendedSequenceNumber);
+ return lastAppendedSequenceNumber;
+ }
+
+ @Override
+ public CompletableFuture<StateChangelogHandleStreamImpl> persist(SequenceNumber from)
+ throws IOException {
+ LOG.debug("persist {} from {}", logId, from);
+ checkNotNull(from);
+ // todo: check range
+
+ rollover();
+ Collection<StoreResult> readyToReturn = confirmed.tailMap(from, true).values();
+ Collection<StateChangeSet> toUpload = changeSets.tailMap(from, true).values();
+ LOG.debug("collected readyToReturn: {}, toUpload: {}", readyToReturn, toUpload);
+
+ StoreTask task = new StoreTask(toUpload);
+ // Handle the result result in supplied executor (mailbox) thread
+ CompletableFuture<StateChangelogHandleStreamImpl> resultFuture =
+ task.getResultFuture()
+ .thenApplyAsync(
+ (results) -> {
+ results.forEach(e -> uploaded.put(e.sequenceNumber, e));
Review comment:
I think we need to check here whether the upload result is still relevant (or another upload was started in the meantime). For example, it could have been aborted, or another checkpoint (with the overlapping change range) was started.
(this was one of concerns when I published #15322)
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -0,0 +1,173 @@
+/*
+ * 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.changelog.fs;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static java.lang.Thread.holdsLock;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.apache.flink.util.ExceptionUtils.findThrowable;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * A {@link StateChangeStore} that waits for some configured amount of time before passing the
+ * accumulated state changes to the actual store. The writes are executed asynchronously.
+ */
+@ThreadSafe
+class BatchingStateChangeStore implements StateChangeStore {
+ private static final Logger LOG = LoggerFactory.getLogger(BatchingStateChangeStore.class);
+
+ private final StateChangeStore delegate;
+ private final ScheduledExecutorService scheduler;
+ private final long scheduleDelayMs;
+ private final long sizeThresholdBytes;
+
+ @GuardedBy("scheduled")
+ private final Queue<StoreTask> scheduled;
+
+ @GuardedBy("scheduled")
+ private long scheduledSizeInBytes;
+
+ @GuardedBy("scheduled")
+ private Future<?> scheduledFuture = CompletableFuture.completedFuture(null);
+
+ private AtomicReference<Throwable> error = new AtomicReference<>(null);
+
+ BatchingStateChangeStore(
+ long persistDelayMs, long sizeThresholdBytes, StateChangeStore delegate) {
+ this(
+ persistDelayMs,
+ sizeThresholdBytes,
+ delegate,
+ SchedulerFactory.create(1, "ChangelogRetryScheduler", LOG));
+ }
+
+ BatchingStateChangeStore(
+ long persistDelayMs,
+ long sizeThresholdBytes,
+ StateChangeStore delegate,
+ ScheduledExecutorService scheduler) {
+ this.scheduleDelayMs = persistDelayMs;
+ this.scheduled = new LinkedList<>();
+ this.scheduler = scheduler;
+ this.sizeThresholdBytes = sizeThresholdBytes;
+ this.delegate = delegate;
+ }
+
+ @Override
+ public void save(StoreTask storeTask) {
+ Collection<StateChangeSet> changeSets = storeTask.changeSets;
+ if (error.get() != null) {
+ LOG.debug("don't persist {} changesets, already failed", changeSets.size());
+ storeTask.fail(error.get());
+ return;
+ }
+ LOG.debug("persist {} changeSets", changeSets.size());
+ try {
+ synchronized (scheduled) {
+ scheduled.add(storeTask);
+ scheduledSizeInBytes += storeTask.getSize();
+ scheduleUploadIfNeeded();
+ }
+ } catch (Exception e) {
+ storeTask.fail(e);
+ throw e;
+ }
+ }
+
+ private void scheduleUploadIfNeeded() {
+ checkState(holdsLock(scheduled));
+ if (scheduledFuture.isDone() || isOverSizeThresholdAndCancellationSucceded()) {
+ scheduleUpload();
Review comment:
I think there is a race condition here which could lead to upload not to be scheduled:
1. Future is runnig in `drainAndSave()`, enters `scheduleUploadIfNeeded()` and sees no need to reschedule (no data added)
2. It exits the `synchronized` section but not the task yet (so future isn't finished yet)
3. Another thread adds data and sees future.isDone == false, so it doesn't schedule neither
WDYT?
(the related issue below is about `scheduledFuture.cancel`, this one is about `scheduledFuture.isDone()`; I guess fix will address both of them)
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -0,0 +1,173 @@
+/*
+ * 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.changelog.fs;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static java.lang.Thread.holdsLock;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.apache.flink.util.ExceptionUtils.findThrowable;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * A {@link StateChangeStore} that waits for some configured amount of time before passing the
+ * accumulated state changes to the actual store. The writes are executed asynchronously.
+ */
+@ThreadSafe
+class BatchingStateChangeStore implements StateChangeStore {
+ private static final Logger LOG = LoggerFactory.getLogger(BatchingStateChangeStore.class);
+
+ private final StateChangeStore delegate;
+ private final ScheduledExecutorService scheduler;
+ private final long scheduleDelayMs;
+ private final long sizeThresholdBytes;
+
+ @GuardedBy("scheduled")
+ private final Queue<StoreTask> scheduled;
+
+ @GuardedBy("scheduled")
+ private long scheduledSizeInBytes;
+
+ @GuardedBy("scheduled")
+ private Future<?> scheduledFuture = CompletableFuture.completedFuture(null);
+
+ private AtomicReference<Throwable> error = new AtomicReference<>(null);
+
+ BatchingStateChangeStore(
+ long persistDelayMs, long sizeThresholdBytes, StateChangeStore delegate) {
+ this(
+ persistDelayMs,
+ sizeThresholdBytes,
+ delegate,
+ SchedulerFactory.create(1, "ChangelogRetryScheduler", LOG));
+ }
+
+ BatchingStateChangeStore(
+ long persistDelayMs,
+ long sizeThresholdBytes,
+ StateChangeStore delegate,
+ ScheduledExecutorService scheduler) {
+ this.scheduleDelayMs = persistDelayMs;
+ this.scheduled = new LinkedList<>();
+ this.scheduler = scheduler;
+ this.sizeThresholdBytes = sizeThresholdBytes;
+ this.delegate = delegate;
+ }
+
+ @Override
+ public void save(StoreTask storeTask) {
+ Collection<StateChangeSet> changeSets = storeTask.changeSets;
+ if (error.get() != null) {
+ LOG.debug("don't persist {} changesets, already failed", changeSets.size());
+ storeTask.fail(error.get());
+ return;
+ }
+ LOG.debug("persist {} changeSets", changeSets.size());
+ try {
+ synchronized (scheduled) {
+ scheduled.add(storeTask);
+ scheduledSizeInBytes += storeTask.getSize();
+ scheduleUploadIfNeeded();
+ }
+ } catch (Exception e) {
+ storeTask.fail(e);
+ throw e;
+ }
+ }
+
+ private void scheduleUploadIfNeeded() {
+ checkState(holdsLock(scheduled));
+ if (scheduledFuture.isDone() || isOverSizeThresholdAndCancellationSucceded()) {
+ scheduleUpload();
+ }
+ }
+
+ private boolean isOverSizeThresholdAndCancellationSucceded() {
+ return scheduledSizeInBytes >= sizeThresholdBytes && scheduledFuture.cancel(false);
+ }
Review comment:
I think the 2nd check may result in threshold being exceeded but not scheduled for upload:
1. T1: add 1 byte, schedule future 1
2. Executor: waits and eventually runs future 1, calls `scheduleUploadIfNeeded` and returns without scheduling; now thread gets suspended by the OS (so future 1 isn't completed)
2. T1: add more bytes exceeding the threshold; try to cancel future 1 and fail => future2 is not scheduled by T1
4. Executor also doesn't schedule any future
WDYT?
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -136,21 +133,23 @@ private void drainAndSave() {
tasks = new ArrayList<>(scheduled);
scheduled.clear();
scheduledSizeInBytes = 0;
- scheduledFuture = null;
}
try {
- if (error != null) {
- tasks.forEach(task -> task.fail(error));
+ if (error.get() != null) {
+ tasks.forEach(task -> task.fail(error.get()));
return;
}
- retryingExecutor.execute(retryPolicy, () -> delegate.save(tasks));
+ delegate.save(tasks);
+
+ synchronized (scheduled) {
+ scheduleUploadIfNeeded();
+ }
} catch (Throwable t) {
tasks.forEach(task -> task.fail(t));
if (findThrowable(t, IOException.class).isPresent()) {
LOG.warn("Caught IO exception while uploading", t);
} else {
- error = t;
- throw t;
+ error.compareAndSet(null, t);
Review comment:
Could you explain the removal of `throw t;` ?
Without it:
1. error can be not logged at all - if no more upload scheduled
2. or if upload errors are not logged later
3. it can be logged with a delay (complicated debug)
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -136,21 +133,23 @@ private void drainAndSave() {
tasks = new ArrayList<>(scheduled);
scheduled.clear();
scheduledSizeInBytes = 0;
- scheduledFuture = null;
}
try {
- if (error != null) {
- tasks.forEach(task -> task.fail(error));
+ if (error.get() != null) {
+ tasks.forEach(task -> task.fail(error.get()));
return;
}
- retryingExecutor.execute(retryPolicy, () -> delegate.save(tasks));
+ delegate.save(tasks);
+
+ synchronized (scheduled) {
+ scheduleUploadIfNeeded();
+ }
Review comment:
This won't be executed in case of exception (but I guess it will change if concurrency issues are addressed).
But more important, no future uploads will start because `this.error` is set later in `catch` block. I guess the assumption is that a single failure leads to the whole job failover?
But that shouldn't be the case, as tasks should tolerate checkpoint failures and it's the JM who decides how to handle checkpoint failures.
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -0,0 +1,173 @@
+/*
+ * 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.changelog.fs;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static java.lang.Thread.holdsLock;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.apache.flink.util.ExceptionUtils.findThrowable;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * A {@link StateChangeStore} that waits for some configured amount of time before passing the
+ * accumulated state changes to the actual store. The writes are executed asynchronously.
+ */
+@ThreadSafe
+class BatchingStateChangeStore implements StateChangeStore {
+ private static final Logger LOG = LoggerFactory.getLogger(BatchingStateChangeStore.class);
+
+ private final StateChangeStore delegate;
+ private final ScheduledExecutorService scheduler;
+ private final long scheduleDelayMs;
+ private final long sizeThresholdBytes;
+
+ @GuardedBy("scheduled")
+ private final Queue<StoreTask> scheduled;
+
+ @GuardedBy("scheduled")
+ private long scheduledSizeInBytes;
+
+ @GuardedBy("scheduled")
+ private Future<?> scheduledFuture = CompletableFuture.completedFuture(null);
+
+ private AtomicReference<Throwable> error = new AtomicReference<>(null);
+
+ BatchingStateChangeStore(
+ long persistDelayMs, long sizeThresholdBytes, StateChangeStore delegate) {
+ this(
+ persistDelayMs,
+ sizeThresholdBytes,
+ delegate,
+ SchedulerFactory.create(1, "ChangelogRetryScheduler", LOG));
+ }
+
+ BatchingStateChangeStore(
+ long persistDelayMs,
+ long sizeThresholdBytes,
+ StateChangeStore delegate,
+ ScheduledExecutorService scheduler) {
+ this.scheduleDelayMs = persistDelayMs;
+ this.scheduled = new LinkedList<>();
+ this.scheduler = scheduler;
+ this.sizeThresholdBytes = sizeThresholdBytes;
+ this.delegate = delegate;
+ }
+
+ @Override
+ public void save(StoreTask storeTask) {
+ Collection<StateChangeSet> changeSets = storeTask.changeSets;
+ if (error.get() != null) {
+ LOG.debug("don't persist {} changesets, already failed", changeSets.size());
+ storeTask.fail(error.get());
+ return;
+ }
+ LOG.debug("persist {} changeSets", changeSets.size());
+ try {
+ synchronized (scheduled) {
+ scheduled.add(storeTask);
+ scheduledSizeInBytes += storeTask.getSize();
+ scheduleUploadIfNeeded();
+ }
+ } catch (Exception e) {
+ storeTask.fail(e);
+ throw e;
+ }
+ }
+
+ private void scheduleUploadIfNeeded() {
+ checkState(holdsLock(scheduled));
+ if (scheduledFuture.isDone() || isOverSizeThresholdAndCancellationSucceded()) {
+ scheduleUpload();
+ }
+ }
+
+ private boolean isOverSizeThresholdAndCancellationSucceded() {
+ return scheduledSizeInBytes >= sizeThresholdBytes && scheduledFuture.cancel(false);
+ }
+
+ private void scheduleUpload() {
+ checkState(scheduledFuture.isDone());
+ long delay = scheduleDelayMs;
+ if (scheduleDelayMs == 0 || scheduledSizeInBytes >= sizeThresholdBytes) {
+ scheduledFuture = scheduler.submit(this::drainAndSave);
+ } else {
+ scheduledFuture = scheduler.schedule(this::drainAndSave, delay, MILLISECONDS);
+ }
+ }
+
+ private void drainAndSave() {
+ Collection<StoreTask> tasks;
+ synchronized (scheduled) {
+ tasks = new ArrayList<>(scheduled);
+ scheduled.clear();
+ scheduledSizeInBytes = 0;
+ }
+ try {
+ if (error.get() != null) {
+ tasks.forEach(task -> task.fail(error.get()));
+ return;
+ }
+ delegate.save(tasks);
Review comment:
This is a single-threaded upload now, I think we need more threads as discussed offline.
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/FsStateChangelogWriter.java
##########
@@ -0,0 +1,213 @@
+/*
+ * 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.changelog.fs;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.changelog.fs.StateChangeStore.StoreTask;
+import org.apache.flink.runtime.state.KeyGroupRange;
+import org.apache.flink.runtime.state.StreamStateHandle;
+import org.apache.flink.runtime.state.changelog.SequenceNumber;
+import org.apache.flink.runtime.state.changelog.StateChange;
+import org.apache.flink.runtime.state.changelog.StateChangelogHandleStreamImpl;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriter;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriterFactory.ChangelogCallbackExecutor;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.NotThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Basic implementation of {@link StateChangelogWriter}. It's main purpose is to keep track which
+ * changes are required for the given {@link #persist(SequenceNumber)} call. Especially it takes
+ * care of re-uploading changes from the previous {@link #persist(SequenceNumber)} call, if those
+ * changes haven't been yet {@link #confirm(SequenceNumber, SequenceNumber)}'ed. This is crucial as
+ * until changes are {@link #confirm(SequenceNumber, SequenceNumber)}, they still can be aborted and
+ * removed/deleted.
+ *
+ * <p>For example if checkpoint N-1 fails and is disposed, after checkpoint N has already started.
+ * In this case, when we are persisting {@link StateChangeSet}s for checkpoint N, we need to
+ * re-upload {@link StateChangeSet}s that belonged to checkpoint N-1.
+ */
+@NotThreadSafe
+class FsStateChangelogWriter implements StateChangelogWriter<StateChangelogHandleStreamImpl> {
+ private static final Logger LOG = LoggerFactory.getLogger(FsStateChangelogWriter.class);
+
+ private final UUID logId;
+ private final KeyGroupRange keyGroupRange;
+ private final StateChangeStore store;
+ private final NavigableMap<SequenceNumber, StateChangeSet> changeSets = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> uploaded = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> confirmed = new TreeMap<>();
+ private List<StateChange> activeChangeSet = new ArrayList<>();
+ private SequenceNumber lastAppendedSequenceNumber = SequenceNumber.of(0L);
+ private boolean closed;
+ private final ChangelogCallbackExecutor executor;
+
+ FsStateChangelogWriter(
+ UUID logId,
+ KeyGroupRange keyGroupRange,
+ StateChangeStore store,
+ ChangelogCallbackExecutor executor) {
+ this.logId = logId;
+ this.keyGroupRange = keyGroupRange;
+ this.store = store;
+ this.executor = checkNotNull(executor);
+ }
+
+ @Override
+ public void append(int keyGroup, byte[] value) {
+ LOG.trace("append to {}: keyGroup={} {} bytes", logId, keyGroup, value.length);
+ checkState(!closed, "%s is closed", logId);
+ activeChangeSet.add(new StateChange(keyGroup, value));
+ // size threshold could be added to call persist when reached. considerations:
+ // 0. can actually degrade performance by amplifying number of requests
+ // 1. which range to persist?
+ // 2. how to deal with retries/aborts?
+ }
+
+ @Override
+ public SequenceNumber lastAppendedSequenceNumber() {
+ rollover();
+ LOG.trace("query {} sqn: {}", logId, lastAppendedSequenceNumber);
+ return lastAppendedSequenceNumber;
+ }
+
+ @Override
+ public CompletableFuture<StateChangelogHandleStreamImpl> persist(SequenceNumber from)
+ throws IOException {
+ LOG.debug("persist {} from {}", logId, from);
+ checkNotNull(from);
+ // todo: check range
+
+ rollover();
+ Collection<StoreResult> readyToReturn = confirmed.tailMap(from, true).values();
+ Collection<StateChangeSet> toUpload = changeSets.tailMap(from, true).values();
+ LOG.debug("collected readyToReturn: {}, toUpload: {}", readyToReturn, toUpload);
+
+ StoreTask task = new StoreTask(toUpload);
+ // Handle the result result in supplied executor (mailbox) thread
+ CompletableFuture<StateChangelogHandleStreamImpl> resultFuture =
+ task.getResultFuture()
+ .thenApplyAsync(
+ (results) -> {
+ results.forEach(e -> uploaded.put(e.sequenceNumber, e));
+ return buildHandle(results, readyToReturn);
+ },
+ executor::execute);
+ store.save(task);
+ return resultFuture;
+ }
+
+ @Override
+ public void close() {
+ LOG.debug("close {}", logId);
+ checkState(!closed);
+ closed = true;
+ activeChangeSet.clear();
+ // todo in MVP or later: cleanup if transition succeeded and had non-shared state
+ changeSets.clear();
+ uploaded.clear();
+ confirmed.clear();
+ // the store is closed from the owning FsStateChangelogClient
+ }
+
+ @Override
+ public void confirm(SequenceNumber from, SequenceNumber to) {
+ LOG.debug("confirm {} from {} to {}", logId, from, to);
+ uploaded.subMap(from, true, to, false)
+ .forEach(
+ (sequenceNumber, changeSetAndResult) -> {
+ changeSets.remove(sequenceNumber);
+ uploaded.remove(sequenceNumber);
+ confirmed.put(sequenceNumber, changeSetAndResult);
Review comment:
I think that we need to check whether this range is still relevant (or was truncated in the meantime).
(this was one of concerns when I published #15322)
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/FsStateChangelogWriter.java
##########
@@ -0,0 +1,213 @@
+/*
+ * 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.changelog.fs;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.changelog.fs.StateChangeStore.StoreTask;
+import org.apache.flink.runtime.state.KeyGroupRange;
+import org.apache.flink.runtime.state.StreamStateHandle;
+import org.apache.flink.runtime.state.changelog.SequenceNumber;
+import org.apache.flink.runtime.state.changelog.StateChange;
+import org.apache.flink.runtime.state.changelog.StateChangelogHandleStreamImpl;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriter;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriterFactory.ChangelogCallbackExecutor;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.NotThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Basic implementation of {@link StateChangelogWriter}. It's main purpose is to keep track which
+ * changes are required for the given {@link #persist(SequenceNumber)} call. Especially it takes
+ * care of re-uploading changes from the previous {@link #persist(SequenceNumber)} call, if those
+ * changes haven't been yet {@link #confirm(SequenceNumber, SequenceNumber)}'ed. This is crucial as
+ * until changes are {@link #confirm(SequenceNumber, SequenceNumber)}, they still can be aborted and
+ * removed/deleted.
+ *
+ * <p>For example if checkpoint N-1 fails and is disposed, after checkpoint N has already started.
+ * In this case, when we are persisting {@link StateChangeSet}s for checkpoint N, we need to
+ * re-upload {@link StateChangeSet}s that belonged to checkpoint N-1.
+ */
+@NotThreadSafe
+class FsStateChangelogWriter implements StateChangelogWriter<StateChangelogHandleStreamImpl> {
+ private static final Logger LOG = LoggerFactory.getLogger(FsStateChangelogWriter.class);
+
+ private final UUID logId;
+ private final KeyGroupRange keyGroupRange;
+ private final StateChangeStore store;
+ private final NavigableMap<SequenceNumber, StateChangeSet> changeSets = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> uploaded = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> confirmed = new TreeMap<>();
+ private List<StateChange> activeChangeSet = new ArrayList<>();
+ private SequenceNumber lastAppendedSequenceNumber = SequenceNumber.of(0L);
+ private boolean closed;
+ private final ChangelogCallbackExecutor executor;
+
+ FsStateChangelogWriter(
+ UUID logId,
+ KeyGroupRange keyGroupRange,
+ StateChangeStore store,
+ ChangelogCallbackExecutor executor) {
+ this.logId = logId;
+ this.keyGroupRange = keyGroupRange;
+ this.store = store;
+ this.executor = checkNotNull(executor);
+ }
+
+ @Override
+ public void append(int keyGroup, byte[] value) {
+ LOG.trace("append to {}: keyGroup={} {} bytes", logId, keyGroup, value.length);
+ checkState(!closed, "%s is closed", logId);
+ activeChangeSet.add(new StateChange(keyGroup, value));
+ // size threshold could be added to call persist when reached. considerations:
+ // 0. can actually degrade performance by amplifying number of requests
+ // 1. which range to persist?
+ // 2. how to deal with retries/aborts?
+ }
+
+ @Override
+ public SequenceNumber lastAppendedSequenceNumber() {
+ rollover();
+ LOG.trace("query {} sqn: {}", logId, lastAppendedSequenceNumber);
+ return lastAppendedSequenceNumber;
+ }
+
+ @Override
+ public CompletableFuture<StateChangelogHandleStreamImpl> persist(SequenceNumber from)
+ throws IOException {
+ LOG.debug("persist {} from {}", logId, from);
+ checkNotNull(from);
+ // todo: check range
+
+ rollover();
+ Collection<StoreResult> readyToReturn = confirmed.tailMap(from, true).values();
+ Collection<StateChangeSet> toUpload = changeSets.tailMap(from, true).values();
Review comment:
I'm thinking how could we later implement pre-emptive upload (i.e. call `persist()` from `append()`).
In this version (#15371 or #15322 as opposed to #14839), we need to filter out already uploaded changes (`uploaded.subMap`) from `toUpload`.
But we also don't want to include the changes from the previous, not yet confirmed/nor aborted checkpoint. Which will also reside in `uploaded`. Do you have any idea how to implement this?
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/RetryingExecutor.java
##########
@@ -1,149 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.flink.changelog.fs;
-
-import org.apache.flink.util.function.RunnableWithException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Optional;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-
-/**
- * A {@link RunnableWithException} executor that schedules a next attempt upon timeout based on
- * {@link RetryPolicy}. Aimed to curb tail latencies
- */
-class RetryingExecutor implements AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(RetryingExecutor.class);
Review comment:
I'd rather like to see this removal as a separate commit.
I'm also not sure that it should be removed. Are you planning to resurrect it in a subsequent PR?
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] rkhachatryan commented on a change in pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on a change in pull request #15371:
URL: https://github.com/apache/flink/pull/15371#discussion_r603184057
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -136,21 +133,23 @@ private void drainAndSave() {
tasks = new ArrayList<>(scheduled);
scheduled.clear();
scheduledSizeInBytes = 0;
- scheduledFuture = null;
}
try {
- if (error != null) {
- tasks.forEach(task -> task.fail(error));
+ if (error.get() != null) {
+ tasks.forEach(task -> task.fail(error.get()));
return;
}
- retryingExecutor.execute(retryPolicy, () -> delegate.save(tasks));
+ delegate.save(tasks);
+
+ synchronized (scheduled) {
+ scheduleUploadIfNeeded();
+ }
Review comment:
Yes, I think this would solve the 1st issue.
WDYT about the 2nd, more important one?
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot commented on pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
flinkbot commented on pull request #15371:
URL: https://github.com/apache/flink/pull/15371#issuecomment-806647938
Thanks a lot for your contribution to the Apache Flink project. I'm the @flinkbot. I help the community
to review your pull request. We will use this comment to track the progress of the review.
## Automated Checks
Last check on commit 202eb502220b8ecd709583c531c65847a37065f2 (Thu Mar 25 12:28:06 UTC 2021)
**Warnings:**
* **3 pom.xml files were touched**: Check for build and licensing issues.
* No documentation files were touched! Remember to keep the Flink docs up to date!
<sub>Mention the bot in a comment to re-run the automated checks.</sub>
## Review Progress
* ❓ 1. The [description] looks good.
* ❓ 2. There is [consensus] that the contribution should go into to Flink.
* ❓ 3. Needs [attention] from.
* ❓ 4. The change fits into the overall [architecture].
* ❓ 5. Overall code [quality] is good.
Please see the [Pull Request Review Guide](https://flink.apache.org/contributing/reviewing-prs.html) for a full explanation of the review process.<details>
The Bot is tracking the review progress through labels. Labels are applied according to the order of the review items. For consensus, approval by a Flink committer of PMC member is required <summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot approve description` to approve one or more aspects (aspects: `description`, `consensus`, `architecture` and `quality`)
- `@flinkbot approve all` to approve all aspects
- `@flinkbot approve-until architecture` to approve everything until `architecture`
- `@flinkbot attention @username1 [@username2 ..]` to require somebody's attention
- `@flinkbot disapprove architecture` to remove an approval you gave earlier
</details>
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] rkhachatryan commented on a change in pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on a change in pull request #15371:
URL: https://github.com/apache/flink/pull/15371#discussion_r603181723
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -136,21 +133,23 @@ private void drainAndSave() {
tasks = new ArrayList<>(scheduled);
scheduled.clear();
scheduledSizeInBytes = 0;
- scheduledFuture = null;
}
try {
- if (error != null) {
- tasks.forEach(task -> task.fail(error));
+ if (error.get() != null) {
+ tasks.forEach(task -> task.fail(error.get()));
return;
}
- retryingExecutor.execute(retryPolicy, () -> delegate.save(tasks));
+ delegate.save(tasks);
+
+ synchronized (scheduled) {
+ scheduleUploadIfNeeded();
+ }
} catch (Throwable t) {
tasks.forEach(task -> task.fail(t));
if (findThrowable(t, IOException.class).isPresent()) {
LOG.warn("Caught IO exception while uploading", t);
} else {
- error = t;
- throw t;
+ error.compareAndSet(null, t);
Review comment:
You're right (in my version, the method was also called directly).
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] pnowojski commented on a change in pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
pnowojski commented on a change in pull request #15371:
URL: https://github.com/apache/flink/pull/15371#discussion_r603113393
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/FsStateChangelogWriter.java
##########
@@ -0,0 +1,213 @@
+/*
+ * 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.changelog.fs;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.changelog.fs.StateChangeStore.StoreTask;
+import org.apache.flink.runtime.state.KeyGroupRange;
+import org.apache.flink.runtime.state.StreamStateHandle;
+import org.apache.flink.runtime.state.changelog.SequenceNumber;
+import org.apache.flink.runtime.state.changelog.StateChange;
+import org.apache.flink.runtime.state.changelog.StateChangelogHandleStreamImpl;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriter;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriterFactory.ChangelogCallbackExecutor;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.NotThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Basic implementation of {@link StateChangelogWriter}. It's main purpose is to keep track which
+ * changes are required for the given {@link #persist(SequenceNumber)} call. Especially it takes
+ * care of re-uploading changes from the previous {@link #persist(SequenceNumber)} call, if those
+ * changes haven't been yet {@link #confirm(SequenceNumber, SequenceNumber)}'ed. This is crucial as
+ * until changes are {@link #confirm(SequenceNumber, SequenceNumber)}, they still can be aborted and
+ * removed/deleted.
+ *
+ * <p>For example if checkpoint N-1 fails and is disposed, after checkpoint N has already started.
+ * In this case, when we are persisting {@link StateChangeSet}s for checkpoint N, we need to
+ * re-upload {@link StateChangeSet}s that belonged to checkpoint N-1.
+ */
+@NotThreadSafe
+class FsStateChangelogWriter implements StateChangelogWriter<StateChangelogHandleStreamImpl> {
+ private static final Logger LOG = LoggerFactory.getLogger(FsStateChangelogWriter.class);
+
+ private final UUID logId;
+ private final KeyGroupRange keyGroupRange;
+ private final StateChangeStore store;
+ private final NavigableMap<SequenceNumber, StateChangeSet> changeSets = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> uploaded = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> confirmed = new TreeMap<>();
+ private List<StateChange> activeChangeSet = new ArrayList<>();
+ private SequenceNumber lastAppendedSequenceNumber = SequenceNumber.of(0L);
+ private boolean closed;
+ private final ChangelogCallbackExecutor executor;
+
+ FsStateChangelogWriter(
+ UUID logId,
+ KeyGroupRange keyGroupRange,
+ StateChangeStore store,
+ ChangelogCallbackExecutor executor) {
+ this.logId = logId;
+ this.keyGroupRange = keyGroupRange;
+ this.store = store;
+ this.executor = checkNotNull(executor);
+ }
+
+ @Override
+ public void append(int keyGroup, byte[] value) {
+ LOG.trace("append to {}: keyGroup={} {} bytes", logId, keyGroup, value.length);
+ checkState(!closed, "%s is closed", logId);
+ activeChangeSet.add(new StateChange(keyGroup, value));
+ // size threshold could be added to call persist when reached. considerations:
+ // 0. can actually degrade performance by amplifying number of requests
+ // 1. which range to persist?
+ // 2. how to deal with retries/aborts?
+ }
+
+ @Override
+ public SequenceNumber lastAppendedSequenceNumber() {
+ rollover();
+ LOG.trace("query {} sqn: {}", logId, lastAppendedSequenceNumber);
+ return lastAppendedSequenceNumber;
+ }
+
+ @Override
+ public CompletableFuture<StateChangelogHandleStreamImpl> persist(SequenceNumber from)
+ throws IOException {
+ LOG.debug("persist {} from {}", logId, from);
+ checkNotNull(from);
+ // todo: check range
+
+ rollover();
+ Collection<StoreResult> readyToReturn = confirmed.tailMap(from, true).values();
+ Collection<StateChangeSet> toUpload = changeSets.tailMap(from, true).values();
+ LOG.debug("collected readyToReturn: {}, toUpload: {}", readyToReturn, toUpload);
+
+ StoreTask task = new StoreTask(toUpload);
+ // Handle the result result in supplied executor (mailbox) thread
+ CompletableFuture<StateChangelogHandleStreamImpl> resultFuture =
+ task.getResultFuture()
+ .thenApplyAsync(
+ (results) -> {
+ results.forEach(e -> uploaded.put(e.sequenceNumber, e));
Review comment:
I think you are right. This mailbox WIP had simplify too much the re-uploading tracking logic.
On the other hand, maybe fixing it now would be a wasted effort, as we are not sure how final re-uploading logic will be handled as it even might be completely removed in the final version? Maybe let's say `notifyCheckpointAbort` is not supported (and throw an exception) until we figure out a solution for the JM/TM changelog ownership question?
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -0,0 +1,173 @@
+/*
+ * 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.changelog.fs;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static java.lang.Thread.holdsLock;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.apache.flink.util.ExceptionUtils.findThrowable;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * A {@link StateChangeStore} that waits for some configured amount of time before passing the
+ * accumulated state changes to the actual store. The writes are executed asynchronously.
+ */
+@ThreadSafe
+class BatchingStateChangeStore implements StateChangeStore {
+ private static final Logger LOG = LoggerFactory.getLogger(BatchingStateChangeStore.class);
+
+ private final StateChangeStore delegate;
+ private final ScheduledExecutorService scheduler;
+ private final long scheduleDelayMs;
+ private final long sizeThresholdBytes;
+
+ @GuardedBy("scheduled")
+ private final Queue<StoreTask> scheduled;
+
+ @GuardedBy("scheduled")
+ private long scheduledSizeInBytes;
+
+ @GuardedBy("scheduled")
+ private Future<?> scheduledFuture = CompletableFuture.completedFuture(null);
+
+ private AtomicReference<Throwable> error = new AtomicReference<>(null);
+
+ BatchingStateChangeStore(
+ long persistDelayMs, long sizeThresholdBytes, StateChangeStore delegate) {
+ this(
+ persistDelayMs,
+ sizeThresholdBytes,
+ delegate,
+ SchedulerFactory.create(1, "ChangelogRetryScheduler", LOG));
+ }
+
+ BatchingStateChangeStore(
+ long persistDelayMs,
+ long sizeThresholdBytes,
+ StateChangeStore delegate,
+ ScheduledExecutorService scheduler) {
+ this.scheduleDelayMs = persistDelayMs;
+ this.scheduled = new LinkedList<>();
+ this.scheduler = scheduler;
+ this.sizeThresholdBytes = sizeThresholdBytes;
+ this.delegate = delegate;
+ }
+
+ @Override
+ public void save(StoreTask storeTask) {
+ Collection<StateChangeSet> changeSets = storeTask.changeSets;
+ if (error.get() != null) {
+ LOG.debug("don't persist {} changesets, already failed", changeSets.size());
+ storeTask.fail(error.get());
+ return;
+ }
+ LOG.debug("persist {} changeSets", changeSets.size());
+ try {
+ synchronized (scheduled) {
+ scheduled.add(storeTask);
+ scheduledSizeInBytes += storeTask.getSize();
+ scheduleUploadIfNeeded();
+ }
+ } catch (Exception e) {
+ storeTask.fail(e);
+ throw e;
+ }
+ }
+
+ private void scheduleUploadIfNeeded() {
+ checkState(holdsLock(scheduled));
+ if (scheduledFuture.isDone() || isOverSizeThresholdAndCancellationSucceded()) {
+ scheduleUpload();
+ }
+ }
+
+ private boolean isOverSizeThresholdAndCancellationSucceded() {
+ return scheduledSizeInBytes >= sizeThresholdBytes && scheduledFuture.cancel(false);
+ }
Review comment:
My intention was that if cancellation doesn't succeed, it means it's already running, and `drainAndSave` will take care of rescheduling next upload. Isn't this happening?
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -0,0 +1,173 @@
+/*
+ * 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.changelog.fs;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static java.lang.Thread.holdsLock;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.apache.flink.util.ExceptionUtils.findThrowable;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * A {@link StateChangeStore} that waits for some configured amount of time before passing the
+ * accumulated state changes to the actual store. The writes are executed asynchronously.
+ */
+@ThreadSafe
+class BatchingStateChangeStore implements StateChangeStore {
+ private static final Logger LOG = LoggerFactory.getLogger(BatchingStateChangeStore.class);
+
+ private final StateChangeStore delegate;
+ private final ScheduledExecutorService scheduler;
+ private final long scheduleDelayMs;
+ private final long sizeThresholdBytes;
+
+ @GuardedBy("scheduled")
+ private final Queue<StoreTask> scheduled;
+
+ @GuardedBy("scheduled")
+ private long scheduledSizeInBytes;
+
+ @GuardedBy("scheduled")
+ private Future<?> scheduledFuture = CompletableFuture.completedFuture(null);
+
+ private AtomicReference<Throwable> error = new AtomicReference<>(null);
+
+ BatchingStateChangeStore(
+ long persistDelayMs, long sizeThresholdBytes, StateChangeStore delegate) {
+ this(
+ persistDelayMs,
+ sizeThresholdBytes,
+ delegate,
+ SchedulerFactory.create(1, "ChangelogRetryScheduler", LOG));
+ }
+
+ BatchingStateChangeStore(
+ long persistDelayMs,
+ long sizeThresholdBytes,
+ StateChangeStore delegate,
+ ScheduledExecutorService scheduler) {
+ this.scheduleDelayMs = persistDelayMs;
+ this.scheduled = new LinkedList<>();
+ this.scheduler = scheduler;
+ this.sizeThresholdBytes = sizeThresholdBytes;
+ this.delegate = delegate;
+ }
+
+ @Override
+ public void save(StoreTask storeTask) {
+ Collection<StateChangeSet> changeSets = storeTask.changeSets;
+ if (error.get() != null) {
+ LOG.debug("don't persist {} changesets, already failed", changeSets.size());
+ storeTask.fail(error.get());
+ return;
+ }
+ LOG.debug("persist {} changeSets", changeSets.size());
+ try {
+ synchronized (scheduled) {
+ scheduled.add(storeTask);
+ scheduledSizeInBytes += storeTask.getSize();
+ scheduleUploadIfNeeded();
+ }
+ } catch (Exception e) {
+ storeTask.fail(e);
+ throw e;
+ }
+ }
+
+ private void scheduleUploadIfNeeded() {
+ checkState(holdsLock(scheduled));
+ if (scheduledFuture.isDone() || isOverSizeThresholdAndCancellationSucceded()) {
+ scheduleUpload();
+ }
+ }
+
+ private boolean isOverSizeThresholdAndCancellationSucceded() {
+ return scheduledSizeInBytes >= sizeThresholdBytes && scheduledFuture.cancel(false);
+ }
+
+ private void scheduleUpload() {
+ checkState(scheduledFuture.isDone());
+ long delay = scheduleDelayMs;
+ if (scheduleDelayMs == 0 || scheduledSizeInBytes >= sizeThresholdBytes) {
+ scheduledFuture = scheduler.submit(this::drainAndSave);
+ } else {
+ scheduledFuture = scheduler.schedule(this::drainAndSave, delay, MILLISECONDS);
+ }
+ }
+
+ private void drainAndSave() {
+ Collection<StoreTask> tasks;
+ synchronized (scheduled) {
+ tasks = new ArrayList<>(scheduled);
+ scheduled.clear();
+ scheduledSizeInBytes = 0;
+ }
+ try {
+ if (error.get() != null) {
+ tasks.forEach(task -> task.fail(error.get()));
+ return;
+ }
+ delegate.save(tasks);
Review comment:
Yes we do, I wanted to simplify the first version for reviewing and later add a bit more sophisticated logic for handling concurrent writes. At the moment I'm not sure how multi threaded writes should actually be working in the first place (each one writing to an independent file? I'm a bit worried about this approach from the perspective of the recovery).
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -136,21 +133,23 @@ private void drainAndSave() {
tasks = new ArrayList<>(scheduled);
scheduled.clear();
scheduledSizeInBytes = 0;
- scheduledFuture = null;
}
try {
- if (error != null) {
- tasks.forEach(task -> task.fail(error));
+ if (error.get() != null) {
+ tasks.forEach(task -> task.fail(error.get()));
return;
}
- retryingExecutor.execute(retryPolicy, () -> delegate.save(tasks));
+ delegate.save(tasks);
+
+ synchronized (scheduled) {
+ scheduleUploadIfNeeded();
+ }
Review comment:
I think you are right, this should be moved to finally block?
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -136,21 +133,23 @@ private void drainAndSave() {
tasks = new ArrayList<>(scheduled);
scheduled.clear();
scheduledSizeInBytes = 0;
- scheduledFuture = null;
}
try {
- if (error != null) {
- tasks.forEach(task -> task.fail(error));
+ if (error.get() != null) {
+ tasks.forEach(task -> task.fail(error.get()));
return;
}
- retryingExecutor.execute(retryPolicy, () -> delegate.save(tasks));
+ delegate.save(tasks);
+
+ synchronized (scheduled) {
+ scheduleUploadIfNeeded();
+ }
} catch (Throwable t) {
tasks.forEach(task -> task.fail(t));
if (findThrowable(t, IOException.class).isPresent()) {
LOG.warn("Caught IO exception while uploading", t);
} else {
- error = t;
- throw t;
+ error.compareAndSet(null, t);
Review comment:
This is a top level method from the uploader/executor thread pool and the only meaningful way of returning the error to the task thread is via `error`? If we throw here, it would have no effect, or am I missing something?
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/FsStateChangelogWriter.java
##########
@@ -0,0 +1,213 @@
+/*
+ * 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.changelog.fs;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.changelog.fs.StateChangeStore.StoreTask;
+import org.apache.flink.runtime.state.KeyGroupRange;
+import org.apache.flink.runtime.state.StreamStateHandle;
+import org.apache.flink.runtime.state.changelog.SequenceNumber;
+import org.apache.flink.runtime.state.changelog.StateChange;
+import org.apache.flink.runtime.state.changelog.StateChangelogHandleStreamImpl;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriter;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriterFactory.ChangelogCallbackExecutor;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.NotThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Basic implementation of {@link StateChangelogWriter}. It's main purpose is to keep track which
+ * changes are required for the given {@link #persist(SequenceNumber)} call. Especially it takes
+ * care of re-uploading changes from the previous {@link #persist(SequenceNumber)} call, if those
+ * changes haven't been yet {@link #confirm(SequenceNumber, SequenceNumber)}'ed. This is crucial as
+ * until changes are {@link #confirm(SequenceNumber, SequenceNumber)}, they still can be aborted and
+ * removed/deleted.
+ *
+ * <p>For example if checkpoint N-1 fails and is disposed, after checkpoint N has already started.
+ * In this case, when we are persisting {@link StateChangeSet}s for checkpoint N, we need to
+ * re-upload {@link StateChangeSet}s that belonged to checkpoint N-1.
+ */
+@NotThreadSafe
+class FsStateChangelogWriter implements StateChangelogWriter<StateChangelogHandleStreamImpl> {
+ private static final Logger LOG = LoggerFactory.getLogger(FsStateChangelogWriter.class);
+
+ private final UUID logId;
+ private final KeyGroupRange keyGroupRange;
+ private final StateChangeStore store;
+ private final NavigableMap<SequenceNumber, StateChangeSet> changeSets = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> uploaded = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> confirmed = new TreeMap<>();
+ private List<StateChange> activeChangeSet = new ArrayList<>();
+ private SequenceNumber lastAppendedSequenceNumber = SequenceNumber.of(0L);
+ private boolean closed;
+ private final ChangelogCallbackExecutor executor;
+
+ FsStateChangelogWriter(
+ UUID logId,
+ KeyGroupRange keyGroupRange,
+ StateChangeStore store,
+ ChangelogCallbackExecutor executor) {
+ this.logId = logId;
+ this.keyGroupRange = keyGroupRange;
+ this.store = store;
+ this.executor = checkNotNull(executor);
+ }
+
+ @Override
+ public void append(int keyGroup, byte[] value) {
+ LOG.trace("append to {}: keyGroup={} {} bytes", logId, keyGroup, value.length);
+ checkState(!closed, "%s is closed", logId);
+ activeChangeSet.add(new StateChange(keyGroup, value));
+ // size threshold could be added to call persist when reached. considerations:
+ // 0. can actually degrade performance by amplifying number of requests
+ // 1. which range to persist?
+ // 2. how to deal with retries/aborts?
+ }
+
+ @Override
+ public SequenceNumber lastAppendedSequenceNumber() {
+ rollover();
+ LOG.trace("query {} sqn: {}", logId, lastAppendedSequenceNumber);
+ return lastAppendedSequenceNumber;
+ }
+
+ @Override
+ public CompletableFuture<StateChangelogHandleStreamImpl> persist(SequenceNumber from)
+ throws IOException {
+ LOG.debug("persist {} from {}", logId, from);
+ checkNotNull(from);
+ // todo: check range
+
+ rollover();
+ Collection<StoreResult> readyToReturn = confirmed.tailMap(from, true).values();
+ Collection<StateChangeSet> toUpload = changeSets.tailMap(from, true).values();
Review comment:
First and foremost, I'm not sure how much longer we will have this re-uploading logic and if we will, in what form?
But assuming no changes to the ownership of the changelog, why couldn't we just move/call the code from the `persist()` to `preEmptiveUpload()`? One issue would be that we would have to store the result of `preEmptiveUpload()` as `FsStateChangelogWriter` state instead of just returning it, so that we can combine the final `StateChangelogHandleStreamImpl` in the `persist()` call, but isn't that all?
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] rkhachatryan commented on a change in pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on a change in pull request #15371:
URL: https://github.com/apache/flink/pull/15371#discussion_r603195388
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/FsStateChangelogWriter.java
##########
@@ -0,0 +1,213 @@
+/*
+ * 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.changelog.fs;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.changelog.fs.StateChangeStore.StoreTask;
+import org.apache.flink.runtime.state.KeyGroupRange;
+import org.apache.flink.runtime.state.StreamStateHandle;
+import org.apache.flink.runtime.state.changelog.SequenceNumber;
+import org.apache.flink.runtime.state.changelog.StateChange;
+import org.apache.flink.runtime.state.changelog.StateChangelogHandleStreamImpl;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriter;
+import org.apache.flink.runtime.state.changelog.StateChangelogWriterFactory.ChangelogCallbackExecutor;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.NotThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.List;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.util.Preconditions.checkNotNull;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * Basic implementation of {@link StateChangelogWriter}. It's main purpose is to keep track which
+ * changes are required for the given {@link #persist(SequenceNumber)} call. Especially it takes
+ * care of re-uploading changes from the previous {@link #persist(SequenceNumber)} call, if those
+ * changes haven't been yet {@link #confirm(SequenceNumber, SequenceNumber)}'ed. This is crucial as
+ * until changes are {@link #confirm(SequenceNumber, SequenceNumber)}, they still can be aborted and
+ * removed/deleted.
+ *
+ * <p>For example if checkpoint N-1 fails and is disposed, after checkpoint N has already started.
+ * In this case, when we are persisting {@link StateChangeSet}s for checkpoint N, we need to
+ * re-upload {@link StateChangeSet}s that belonged to checkpoint N-1.
+ */
+@NotThreadSafe
+class FsStateChangelogWriter implements StateChangelogWriter<StateChangelogHandleStreamImpl> {
+ private static final Logger LOG = LoggerFactory.getLogger(FsStateChangelogWriter.class);
+
+ private final UUID logId;
+ private final KeyGroupRange keyGroupRange;
+ private final StateChangeStore store;
+ private final NavigableMap<SequenceNumber, StateChangeSet> changeSets = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> uploaded = new TreeMap<>();
+ private final NavigableMap<SequenceNumber, StoreResult> confirmed = new TreeMap<>();
+ private List<StateChange> activeChangeSet = new ArrayList<>();
+ private SequenceNumber lastAppendedSequenceNumber = SequenceNumber.of(0L);
+ private boolean closed;
+ private final ChangelogCallbackExecutor executor;
+
+ FsStateChangelogWriter(
+ UUID logId,
+ KeyGroupRange keyGroupRange,
+ StateChangeStore store,
+ ChangelogCallbackExecutor executor) {
+ this.logId = logId;
+ this.keyGroupRange = keyGroupRange;
+ this.store = store;
+ this.executor = checkNotNull(executor);
+ }
+
+ @Override
+ public void append(int keyGroup, byte[] value) {
+ LOG.trace("append to {}: keyGroup={} {} bytes", logId, keyGroup, value.length);
+ checkState(!closed, "%s is closed", logId);
+ activeChangeSet.add(new StateChange(keyGroup, value));
+ // size threshold could be added to call persist when reached. considerations:
+ // 0. can actually degrade performance by amplifying number of requests
+ // 1. which range to persist?
+ // 2. how to deal with retries/aborts?
+ }
+
+ @Override
+ public SequenceNumber lastAppendedSequenceNumber() {
+ rollover();
+ LOG.trace("query {} sqn: {}", logId, lastAppendedSequenceNumber);
+ return lastAppendedSequenceNumber;
+ }
+
+ @Override
+ public CompletableFuture<StateChangelogHandleStreamImpl> persist(SequenceNumber from)
+ throws IOException {
+ LOG.debug("persist {} from {}", logId, from);
+ checkNotNull(from);
+ // todo: check range
+
+ rollover();
+ Collection<StoreResult> readyToReturn = confirmed.tailMap(from, true).values();
+ Collection<StateChangeSet> toUpload = changeSets.tailMap(from, true).values();
Review comment:
So for pre-emptive uploads there will be a separate collection which will also be updated by a separate callback. We'll also have to truncate it.
Sounds a bit complex but I think it should work.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #15371:
URL: https://github.com/apache/flink/pull/15371#issuecomment-806671834
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "202eb502220b8ecd709583c531c65847a37065f2",
"status" : "FAILURE",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=15461",
"triggerID" : "202eb502220b8ecd709583c531c65847a37065f2",
"triggerType" : "PUSH"
}, {
"hash" : "def801eb5580ad2e14fe4c8dcd0629caf6582d1d",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "def801eb5580ad2e14fe4c8dcd0629caf6582d1d",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 202eb502220b8ecd709583c531c65847a37065f2 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=15461)
* def801eb5580ad2e14fe4c8dcd0629caf6582d1d UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #15371:
URL: https://github.com/apache/flink/pull/15371#issuecomment-806671834
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "202eb502220b8ecd709583c531c65847a37065f2",
"status" : "FAILURE",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=15461",
"triggerID" : "202eb502220b8ecd709583c531c65847a37065f2",
"triggerType" : "PUSH"
}, {
"hash" : "def801eb5580ad2e14fe4c8dcd0629caf6582d1d",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "def801eb5580ad2e14fe4c8dcd0629caf6582d1d",
"triggerType" : "PUSH"
}, {
"hash" : "e350c69e02165b688a58f381920725ade9301521",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "e350c69e02165b688a58f381920725ade9301521",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 202eb502220b8ecd709583c531c65847a37065f2 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=15461)
* def801eb5580ad2e14fe4c8dcd0629caf6582d1d UNKNOWN
* e350c69e02165b688a58f381920725ade9301521 UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot commented on pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
flinkbot commented on pull request #15371:
URL: https://github.com/apache/flink/pull/15371#issuecomment-806671834
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "202eb502220b8ecd709583c531c65847a37065f2",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "202eb502220b8ecd709583c531c65847a37065f2",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 202eb502220b8ecd709583c531c65847a37065f2 UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] flinkbot edited a comment on pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #15371:
URL: https://github.com/apache/flink/pull/15371#issuecomment-806671834
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "202eb502220b8ecd709583c531c65847a37065f2",
"status" : "FAILURE",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=15461",
"triggerID" : "202eb502220b8ecd709583c531c65847a37065f2",
"triggerType" : "PUSH"
}, {
"hash" : "def801eb5580ad2e14fe4c8dcd0629caf6582d1d",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "def801eb5580ad2e14fe4c8dcd0629caf6582d1d",
"triggerType" : "PUSH"
}, {
"hash" : "e350c69e02165b688a58f381920725ade9301521",
"status" : "PENDING",
"url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=15482",
"triggerID" : "e350c69e02165b688a58f381920725ade9301521",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 202eb502220b8ecd709583c531c65847a37065f2 Azure: [FAILURE](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=15461)
* def801eb5580ad2e14fe4c8dcd0629caf6582d1d UNKNOWN
* e350c69e02165b688a58f381920725ade9301521 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=15482)
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run travis` re-run the last Travis build
- `@flinkbot run azure` re-run the last Azure build
</details>
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] rkhachatryan commented on a change in pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on a change in pull request #15371:
URL: https://github.com/apache/flink/pull/15371#discussion_r603177917
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -0,0 +1,173 @@
+/*
+ * 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.changelog.fs;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static java.lang.Thread.holdsLock;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.apache.flink.util.ExceptionUtils.findThrowable;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * A {@link StateChangeStore} that waits for some configured amount of time before passing the
+ * accumulated state changes to the actual store. The writes are executed asynchronously.
+ */
+@ThreadSafe
+class BatchingStateChangeStore implements StateChangeStore {
+ private static final Logger LOG = LoggerFactory.getLogger(BatchingStateChangeStore.class);
+
+ private final StateChangeStore delegate;
+ private final ScheduledExecutorService scheduler;
+ private final long scheduleDelayMs;
+ private final long sizeThresholdBytes;
+
+ @GuardedBy("scheduled")
+ private final Queue<StoreTask> scheduled;
+
+ @GuardedBy("scheduled")
+ private long scheduledSizeInBytes;
+
+ @GuardedBy("scheduled")
+ private Future<?> scheduledFuture = CompletableFuture.completedFuture(null);
+
+ private AtomicReference<Throwable> error = new AtomicReference<>(null);
+
+ BatchingStateChangeStore(
+ long persistDelayMs, long sizeThresholdBytes, StateChangeStore delegate) {
+ this(
+ persistDelayMs,
+ sizeThresholdBytes,
+ delegate,
+ SchedulerFactory.create(1, "ChangelogRetryScheduler", LOG));
+ }
+
+ BatchingStateChangeStore(
+ long persistDelayMs,
+ long sizeThresholdBytes,
+ StateChangeStore delegate,
+ ScheduledExecutorService scheduler) {
+ this.scheduleDelayMs = persistDelayMs;
+ this.scheduled = new LinkedList<>();
+ this.scheduler = scheduler;
+ this.sizeThresholdBytes = sizeThresholdBytes;
+ this.delegate = delegate;
+ }
+
+ @Override
+ public void save(StoreTask storeTask) {
+ Collection<StateChangeSet> changeSets = storeTask.changeSets;
+ if (error.get() != null) {
+ LOG.debug("don't persist {} changesets, already failed", changeSets.size());
+ storeTask.fail(error.get());
+ return;
+ }
+ LOG.debug("persist {} changeSets", changeSets.size());
+ try {
+ synchronized (scheduled) {
+ scheduled.add(storeTask);
+ scheduledSizeInBytes += storeTask.getSize();
+ scheduleUploadIfNeeded();
+ }
+ } catch (Exception e) {
+ storeTask.fail(e);
+ throw e;
+ }
+ }
+
+ private void scheduleUploadIfNeeded() {
+ checkState(holdsLock(scheduled));
+ if (scheduledFuture.isDone() || isOverSizeThresholdAndCancellationSucceded()) {
+ scheduleUpload();
+ }
+ }
+
+ private boolean isOverSizeThresholdAndCancellationSucceded() {
+ return scheduledSizeInBytes >= sizeThresholdBytes && scheduledFuture.cancel(false);
+ }
+
+ private void scheduleUpload() {
+ checkState(scheduledFuture.isDone());
+ long delay = scheduleDelayMs;
+ if (scheduleDelayMs == 0 || scheduledSizeInBytes >= sizeThresholdBytes) {
+ scheduledFuture = scheduler.submit(this::drainAndSave);
+ } else {
+ scheduledFuture = scheduler.schedule(this::drainAndSave, delay, MILLISECONDS);
+ }
+ }
+
+ private void drainAndSave() {
+ Collection<StoreTask> tasks;
+ synchronized (scheduled) {
+ tasks = new ArrayList<>(scheduled);
+ scheduled.clear();
+ scheduledSizeInBytes = 0;
+ }
+ try {
+ if (error.get() != null) {
+ tasks.forEach(task -> task.fail(error.get()));
+ return;
+ }
+ delegate.save(tasks);
Review comment:
Yes, each upload should be an independent file so it shouldn't affect the recovery.
I think we should have it in the first version (not sure whether this PR or not) especially if we ignore aborts.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] pnowojski closed pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
pnowojski closed pull request #15371:
URL: https://github.com/apache/flink/pull/15371
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [flink] rkhachatryan commented on a change in pull request #15371: [FLINK-19503][state] Add DFS-based StateChangelog
Posted by GitBox <gi...@apache.org>.
rkhachatryan commented on a change in pull request #15371:
URL: https://github.com/apache/flink/pull/15371#discussion_r603174752
##########
File path: flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/BatchingStateChangeStore.java
##########
@@ -0,0 +1,173 @@
+/*
+ * 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.changelog.fs;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static java.lang.Thread.holdsLock;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.apache.flink.util.ExceptionUtils.findThrowable;
+import static org.apache.flink.util.Preconditions.checkState;
+
+/**
+ * A {@link StateChangeStore} that waits for some configured amount of time before passing the
+ * accumulated state changes to the actual store. The writes are executed asynchronously.
+ */
+@ThreadSafe
+class BatchingStateChangeStore implements StateChangeStore {
+ private static final Logger LOG = LoggerFactory.getLogger(BatchingStateChangeStore.class);
+
+ private final StateChangeStore delegate;
+ private final ScheduledExecutorService scheduler;
+ private final long scheduleDelayMs;
+ private final long sizeThresholdBytes;
+
+ @GuardedBy("scheduled")
+ private final Queue<StoreTask> scheduled;
+
+ @GuardedBy("scheduled")
+ private long scheduledSizeInBytes;
+
+ @GuardedBy("scheduled")
+ private Future<?> scheduledFuture = CompletableFuture.completedFuture(null);
+
+ private AtomicReference<Throwable> error = new AtomicReference<>(null);
+
+ BatchingStateChangeStore(
+ long persistDelayMs, long sizeThresholdBytes, StateChangeStore delegate) {
+ this(
+ persistDelayMs,
+ sizeThresholdBytes,
+ delegate,
+ SchedulerFactory.create(1, "ChangelogRetryScheduler", LOG));
+ }
+
+ BatchingStateChangeStore(
+ long persistDelayMs,
+ long sizeThresholdBytes,
+ StateChangeStore delegate,
+ ScheduledExecutorService scheduler) {
+ this.scheduleDelayMs = persistDelayMs;
+ this.scheduled = new LinkedList<>();
+ this.scheduler = scheduler;
+ this.sizeThresholdBytes = sizeThresholdBytes;
+ this.delegate = delegate;
+ }
+
+ @Override
+ public void save(StoreTask storeTask) {
+ Collection<StateChangeSet> changeSets = storeTask.changeSets;
+ if (error.get() != null) {
+ LOG.debug("don't persist {} changesets, already failed", changeSets.size());
+ storeTask.fail(error.get());
+ return;
+ }
+ LOG.debug("persist {} changeSets", changeSets.size());
+ try {
+ synchronized (scheduled) {
+ scheduled.add(storeTask);
+ scheduledSizeInBytes += storeTask.getSize();
+ scheduleUploadIfNeeded();
+ }
+ } catch (Exception e) {
+ storeTask.fail(e);
+ throw e;
+ }
+ }
+
+ private void scheduleUploadIfNeeded() {
+ checkState(holdsLock(scheduled));
+ if (scheduledFuture.isDone() || isOverSizeThresholdAndCancellationSucceded()) {
+ scheduleUpload();
+ }
+ }
+
+ private boolean isOverSizeThresholdAndCancellationSucceded() {
+ return scheduledSizeInBytes >= sizeThresholdBytes && scheduledFuture.cancel(false);
+ }
Review comment:
IIUC, if `drainAndSave` is being executing but it already passed the re-scheduling section (2) then nothing will be scheduled.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org