You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by ro...@apache.org on 2022/12/01 17:59:17 UTC
[flink] branch master updated: [FLINK-29928][runtime, state] Share RocksDB memory across TM slots
This is an automated email from the ASF dual-hosted git repository.
roman pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink.git
The following commit(s) were added to refs/heads/master by this push:
new 3b6d08e57f6 [FLINK-29928][runtime, state] Share RocksDB memory across TM slots
3b6d08e57f6 is described below
commit 3b6d08e57f644cddcdac1fb5a110d44172652c3a
Author: Roman Khachatryan <kh...@gmail.com>
AuthorDate: Fri Nov 18 11:06:19 2022 +0100
[FLINK-29928][runtime, state] Share RocksDB memory across TM slots
---
docs/content.zh/docs/ops/state/state_backends.md | 2 +-
docs/content/docs/ops/state/state_backends.md | 2 +-
.../generated/rocksdb_configuration.html | 8 +-
.../generated/state_backend_rocksdb_section.html | 8 +-
.../state/api/runtime/SavepointEnvironment.java | 9 +
.../flink/runtime/execution/Environment.java | 4 +
.../flink/runtime/memory/SharedResources.java | 8 +-
.../flink/runtime/taskexecutor/TaskExecutor.java | 7 +
.../runtime/taskexecutor/TaskManagerServices.java | 13 +-
.../runtime/taskmanager/RuntimeEnvironment.java | 9 +
.../org/apache/flink/runtime/taskmanager/Task.java | 7 +
.../operators/testutils/DummyEnvironment.java | 6 +
.../operators/testutils/MockEnvironment.java | 9 +
.../runtime/taskexecutor/TaskExecutorTest.java | 147 +++++++++++-
.../taskexecutor/TaskManagerServicesBuilder.java | 6 +-
.../runtime/taskmanager/TaskAsyncCallTest.java | 2 +
.../flink/runtime/taskmanager/TestTaskBuilder.java | 2 +
.../flink/runtime/testutils/InMemoryReporter.java | 23 ++
.../runtime/util/JvmExitOnFatalErrorTest.java | 2 +
.../state/EmbeddedRocksDBStateBackend.java | 2 +-
.../state/RocksDBMemoryConfiguration.java | 5 +
.../state/RocksDBMemoryControllerUtils.java | 11 +-
.../streaming/state/RocksDBOperationUtils.java | 46 +---
.../contrib/streaming/state/RocksDBOptions.java | 21 +-
.../streaming/state/RocksDBSharedResources.java | 4 +
.../state/RocksDBSharedResourcesFactory.java | 183 +++++++++++++++
.../state/RocksDBSharedResourcesFactoryTest.java | 162 ++++++++++++++
.../tasks/InterruptSensitiveRestoreTest.java | 2 +
.../runtime/tasks/StreamMockEnvironment.java | 9 +
.../runtime/tasks/StreamTaskSystemExitTest.java | 2 +
.../runtime/tasks/StreamTaskTerminationTest.java | 2 +
.../runtime/tasks/SynchronousCheckpointITCase.java | 2 +
.../tasks/TaskCheckpointingBehaviourTest.java | 2 +
.../TaskManagerWideRocksDbMemorySharingITCase.java | 249 +++++++++++++++++++++
34 files changed, 913 insertions(+), 63 deletions(-)
diff --git a/docs/content.zh/docs/ops/state/state_backends.md b/docs/content.zh/docs/ops/state/state_backends.md
index a987992e472..a78339228a6 100644
--- a/docs/content.zh/docs/ops/state/state_backends.md
+++ b/docs/content.zh/docs/ops/state/state_backends.md
@@ -235,7 +235,7 @@ Flink还提供了两个参数来控制*写路径*(MemTable)和*读路径*(
<span class="label label-info">注意</span> 上述机制开启时将覆盖用户在 [`PredefinedOptions`](#predefined-per-columnfamily-options) 和 [`RocksDBOptionsFactory`](#passing-options-factory-to-rocksdb) 中对 block cache 和 write buffer 进行的配置。
<span class="label label-info">注意</span> *仅面向专业用户*:若要手动控制内存,可以将 `state.backend.rocksdb.memory.managed` 设置为 `false`,并通过 [`ColumnFamilyOptions`](#passing-options-factory-to-rocksdb) 配置 RocksDB。
-或者可以复用上述 cache/write-buffer-manager 机制,但将内存大小设置为与 Flink 的托管内存大小无关的固定大小(通过 `state.backend.rocksdb.memory.fixed-per-slot` 选项)。
+或者可以复用上述 cache/write-buffer-manager 机制,但将内存大小设置为与 Flink 的托管内存大小无关的固定大小(通过 `state.backend.rocksdb.memory.fixed-per-slot`/`state.backend.rocksdb.memory.fixed-per-tm` 选项)。
注意在这两种情况下,用户都需要确保在 JVM 之外有足够的内存可供 RocksDB 使用。
<a name="timers-heap-vs-rocksdb"></a>
diff --git a/docs/content/docs/ops/state/state_backends.md b/docs/content/docs/ops/state/state_backends.md
index b4b2ac2eec3..28c7b02fbe6 100644
--- a/docs/content/docs/ops/state/state_backends.md
+++ b/docs/content/docs/ops/state/state_backends.md
@@ -226,7 +226,7 @@ When the above described mechanism (`cache` and `write buffer manager`) is enabl
{{< /hint >}}
{{< details "Expert Mode" >}}
-To control memory manually, you can set `state.backend.rocksdb.memory.managed` to `false` and configure RocksDB via [`ColumnFamilyOptions`](#passing-options-factory-to-rocksdb). Alternatively, you can use the above mentioned cache/buffer-manager mechanism, but set the memory size to a fixed amount independent of Flink's managed memory size (`state.backend.rocksdb.memory.fixed-per-slot` option). Note that in both cases, users need to ensure on their own that enough memory is available out [...]
+To control memory manually, you can set `state.backend.rocksdb.memory.managed` to `false` and configure RocksDB via [`ColumnFamilyOptions`](#passing-options-factory-to-rocksdb). Alternatively, you can use the above mentioned cache/buffer-manager mechanism, but set the memory size to a fixed amount independent of Flink's managed memory size (`state.backend.rocksdb.memory.fixed-per-slot` or `state.backend.rocksdb.memory.fixed-per-tm` options). Note that in both cases, users need to ensure [...]
{{< /details >}}
### Timers (Heap vs. RocksDB)
diff --git a/docs/layouts/shortcodes/generated/rocksdb_configuration.html b/docs/layouts/shortcodes/generated/rocksdb_configuration.html
index 8959e308ffb..977de4392f0 100644
--- a/docs/layouts/shortcodes/generated/rocksdb_configuration.html
+++ b/docs/layouts/shortcodes/generated/rocksdb_configuration.html
@@ -24,7 +24,13 @@
<td><h5>state.backend.rocksdb.memory.fixed-per-slot</h5></td>
<td style="word-wrap: break-word;">(none)</td>
<td>MemorySize</td>
- <td>The fixed total amount of memory, shared among all RocksDB instances per slot. This option overrides the 'state.backend.rocksdb.memory.managed' option when configured. If neither this option, nor the 'state.backend.rocksdb.memory.managed' optionare set, then each RocksDB column family state has its own memory caches (as controlled by the column family options).</td>
+ <td>The fixed total amount of memory, shared among all RocksDB instances per slot. This option overrides the 'state.backend.rocksdb.memory.managed' option when configured.</td>
+ </tr>
+ <tr>
+ <td><h5>state.backend.rocksdb.memory.fixed-per-tm</h5></td>
+ <td style="word-wrap: break-word;">(none)</td>
+ <td>MemorySize</td>
+ <td>The fixed total amount of memory, shared among all RocksDB instances per Task Manager (cluster-level option). This option only takes effect if neither 'state.backend.rocksdb.memory.managed' nor 'state.backend.rocksdb.memory.fixed-per-slot' are not configured. If none is configured then each RocksDB column family state has its own memory caches (as controlled by the column family options). The relevant options for the shared resources (e.g. write-buffer-ratio) can be set o [...]
</tr>
<tr>
<td><h5>state.backend.rocksdb.memory.high-prio-pool-ratio</h5></td>
diff --git a/docs/layouts/shortcodes/generated/state_backend_rocksdb_section.html b/docs/layouts/shortcodes/generated/state_backend_rocksdb_section.html
index ad50ef186b4..fa92a7783cf 100644
--- a/docs/layouts/shortcodes/generated/state_backend_rocksdb_section.html
+++ b/docs/layouts/shortcodes/generated/state_backend_rocksdb_section.html
@@ -12,7 +12,13 @@
<td><h5>state.backend.rocksdb.memory.fixed-per-slot</h5></td>
<td style="word-wrap: break-word;">(none)</td>
<td>MemorySize</td>
- <td>The fixed total amount of memory, shared among all RocksDB instances per slot. This option overrides the 'state.backend.rocksdb.memory.managed' option when configured. If neither this option, nor the 'state.backend.rocksdb.memory.managed' optionare set, then each RocksDB column family state has its own memory caches (as controlled by the column family options).</td>
+ <td>The fixed total amount of memory, shared among all RocksDB instances per slot. This option overrides the 'state.backend.rocksdb.memory.managed' option when configured.</td>
+ </tr>
+ <tr>
+ <td><h5>state.backend.rocksdb.memory.fixed-per-tm</h5></td>
+ <td style="word-wrap: break-word;">(none)</td>
+ <td>MemorySize</td>
+ <td>The fixed total amount of memory, shared among all RocksDB instances per Task Manager (cluster-level option). This option only takes effect if neither 'state.backend.rocksdb.memory.managed' nor 'state.backend.rocksdb.memory.fixed-per-slot' are not configured. If none is configured then each RocksDB column family state has its own memory caches (as controlled by the column family options). The relevant options for the shared resources (e.g. write-buffer-ratio) can be set o [...]
</tr>
<tr>
<td><h5>state.backend.rocksdb.memory.high-prio-pool-ratio</h5></td>
diff --git a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointEnvironment.java b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointEnvironment.java
index 6c0b45b1e1a..ee230c39d4b 100644
--- a/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointEnvironment.java
+++ b/flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointEnvironment.java
@@ -47,6 +47,7 @@ import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.jobgraph.tasks.TaskOperatorEventGateway;
import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.TaskMetricGroup;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.operators.coordination.CoordinationRequest;
@@ -100,6 +101,8 @@ public class SavepointEnvironment implements Environment {
private final MemoryManager memoryManager;
+ private final SharedResources sharedResources;
+
private final AccumulatorRegistry accumulatorRegistry;
private final UserCodeClassLoader userCodeClassLoader;
@@ -126,6 +129,7 @@ public class SavepointEnvironment implements Environment {
this.taskStateManager = new SavepointTaskStateManager(prioritizedOperatorSubtaskState);
this.ioManager = new IOManagerAsync(ConfigurationUtils.parseTempDirectories(configuration));
this.memoryManager = MemoryManager.create(64 * 1024 * 1024, DEFAULT_PAGE_SIZE);
+ this.sharedResources = new SharedResources();
this.accumulatorRegistry = new AccumulatorRegistry(jobID, attemptID);
this.userCodeClassLoader = UserCodeClassLoaderRuntimeContextAdapter.from(ctx);
@@ -200,6 +204,11 @@ public class SavepointEnvironment implements Environment {
return memoryManager;
}
+ @Override
+ public SharedResources getSharedResources() {
+ return sharedResources;
+ }
+
@Override
public UserCodeClassLoader getUserCodeClassLoader() {
return userCodeClassLoader;
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/execution/Environment.java b/flink-runtime/src/main/java/org/apache/flink/runtime/execution/Environment.java
index cdbf8dec937..40a587fd5c3 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/execution/Environment.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/execution/Environment.java
@@ -39,6 +39,7 @@ import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.jobgraph.tasks.TaskOperatorEventGateway;
import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.TaskMetricGroup;
import org.apache.flink.runtime.query.TaskKvStateRegistry;
import org.apache.flink.runtime.state.CheckpointStorageAccess;
@@ -147,6 +148,9 @@ public interface Environment {
*/
MemoryManager getMemoryManager();
+ /** @return the resources shared among all tasks of this task manager. */
+ SharedResources getSharedResources();
+
/** Returns the user code class loader */
UserCodeClassLoader getUserCodeClassLoader();
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/memory/SharedResources.java b/flink-runtime/src/main/java/org/apache/flink/runtime/memory/SharedResources.java
index 4bc4859db62..f867ae0c7c5 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/memory/SharedResources.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/memory/SharedResources.java
@@ -31,7 +31,7 @@ import java.util.function.LongConsumer;
import static org.apache.flink.util.Preconditions.checkState;
/** A map that keeps track of acquired shared resources and handles their allocation disposal. */
-final class SharedResources {
+public final class SharedResources {
private final ReentrantLock lock = new ReentrantLock();
@@ -45,7 +45,7 @@ final class SharedResources {
* <p>The resource must be released when no longer used. That releases the lease. When all
* leases are released, the resource is disposed.
*/
- <T extends AutoCloseable> ResourceAndSize<T> getOrAllocateSharedResource(
+ public <T extends AutoCloseable> ResourceAndSize<T> getOrAllocateSharedResource(
String type,
Object leaseHolder,
LongFunctionWithException<T, Exception> initializer,
@@ -94,7 +94,7 @@ final class SharedResources {
*
* <p>This method takes an additional hook that is called when the resource is disposed.
*/
- void release(String type, Object leaseHolder, LongConsumer releaser) throws Exception {
+ public void release(String type, Object leaseHolder, LongConsumer releaser) throws Exception {
lock.lock();
try {
final LeasedResource<?> resource = reservedResources.get(type);
@@ -130,7 +130,7 @@ final class SharedResources {
// ------------------------------------------------------------------------
/** A resource handle with size. */
- interface ResourceAndSize<T extends AutoCloseable> {
+ public interface ResourceAndSize<T extends AutoCloseable> {
T resourceHandle();
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/TaskExecutor.java b/flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/TaskExecutor.java
index 854d83d5d14..6e2a3c46bf6 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/TaskExecutor.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/TaskExecutor.java
@@ -71,6 +71,7 @@ import org.apache.flink.runtime.jobmaster.ResourceManagerAddress;
import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalListener;
import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalService;
import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.messages.TaskThreadInfoResponse;
import org.apache.flink.runtime.messages.ThreadInfoSample;
@@ -227,6 +228,9 @@ public class TaskExecutor extends RpcEndpoint implements TaskExecutorGateway {
private final Executor ioExecutor;
+ /** {@link MemoryManager} shared across all tasks. */
+ private final SharedResources sharedResources;
+
// --------- task slot allocation table -----------
private final TaskSlotTable<Task> taskSlotTable;
@@ -342,6 +346,8 @@ public class TaskExecutor extends RpcEndpoint implements TaskExecutorGateway {
this.slotAllocationSnapshotPersistenceService =
taskExecutorServices.getSlotAllocationSnapshotPersistenceService();
+
+ this.sharedResources = taskExecutorServices.getSharedResources();
}
private HeartbeatManager<Void, TaskExecutorHeartbeatPayload>
@@ -737,6 +743,7 @@ public class TaskExecutor extends RpcEndpoint implements TaskExecutorGateway {
tdd.getProducedPartitions(),
tdd.getInputGates(),
memoryManager,
+ sharedResources,
taskExecutorServices.getIOManager(),
taskExecutorServices.getShuffleEnvironment(),
taskExecutorServices.getKvStateService(),
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/TaskManagerServices.java b/flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/TaskManagerServices.java
index 5bc5f292092..d439146f263 100755
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/TaskManagerServices.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/TaskManagerServices.java
@@ -30,6 +30,7 @@ import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.runtime.io.disk.iomanager.IOManagerAsync;
import org.apache.flink.runtime.io.network.TaskEventDispatcher;
import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.rpc.FatalErrorHandler;
import org.apache.flink.runtime.shuffle.ShuffleEnvironment;
import org.apache.flink.runtime.shuffle.ShuffleEnvironmentContext;
@@ -83,6 +84,7 @@ public class TaskManagerServices {
private final ExecutorService ioExecutor;
private final LibraryCacheManager libraryCacheManager;
private final SlotAllocationSnapshotPersistenceService slotAllocationSnapshotPersistenceService;
+ private final SharedResources sharedResources;
TaskManagerServices(
UnresolvedTaskManagerLocation unresolvedTaskManagerLocation,
@@ -99,7 +101,8 @@ public class TaskManagerServices {
TaskEventDispatcher taskEventDispatcher,
ExecutorService ioExecutor,
LibraryCacheManager libraryCacheManager,
- SlotAllocationSnapshotPersistenceService slotAllocationSnapshotPersistenceService) {
+ SlotAllocationSnapshotPersistenceService slotAllocationSnapshotPersistenceService,
+ SharedResources sharedResources) {
this.unresolvedTaskManagerLocation =
Preconditions.checkNotNull(unresolvedTaskManagerLocation);
@@ -117,6 +120,7 @@ public class TaskManagerServices {
this.ioExecutor = Preconditions.checkNotNull(ioExecutor);
this.libraryCacheManager = Preconditions.checkNotNull(libraryCacheManager);
this.slotAllocationSnapshotPersistenceService = slotAllocationSnapshotPersistenceService;
+ this.sharedResources = Preconditions.checkNotNull(sharedResources);
}
// --------------------------------------------------------------------------------------------
@@ -179,6 +183,10 @@ public class TaskManagerServices {
return libraryCacheManager;
}
+ public SharedResources getSharedResources() {
+ return sharedResources;
+ }
+
// --------------------------------------------------------------------------------------------
// Shut down method
// --------------------------------------------------------------------------------------------
@@ -377,7 +385,8 @@ public class TaskManagerServices {
taskEventDispatcher,
ioExecutor,
libraryCacheManager,
- slotAllocationSnapshotPersistenceService);
+ slotAllocationSnapshotPersistenceService,
+ new SharedResources());
}
private static TaskSlotTable<Task> createTaskSlotTable(
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/RuntimeEnvironment.java b/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/RuntimeEnvironment.java
index 50f0d797a52..74ce5e3fd32 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/RuntimeEnvironment.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/RuntimeEnvironment.java
@@ -40,6 +40,7 @@ import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.jobgraph.tasks.TaskOperatorEventGateway;
import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.TaskMetricGroup;
import org.apache.flink.runtime.query.TaskKvStateRegistry;
import org.apache.flink.runtime.state.CheckpointStorageAccess;
@@ -72,6 +73,7 @@ public class RuntimeEnvironment implements Environment {
private final UserCodeClassLoader userCodeClassLoader;
private final MemoryManager memManager;
+ private final SharedResources sharedResources;
private final IOManager ioManager;
private final BroadcastVariableManager bcVarManager;
private final TaskStateManager taskStateManager;
@@ -116,6 +118,7 @@ public class RuntimeEnvironment implements Environment {
Configuration taskConfiguration,
UserCodeClassLoader userCodeClassLoader,
MemoryManager memManager,
+ SharedResources sharedResources,
IOManager ioManager,
BroadcastVariableManager bcVarManager,
TaskStateManager taskStateManager,
@@ -143,6 +146,7 @@ public class RuntimeEnvironment implements Environment {
this.taskConfiguration = checkNotNull(taskConfiguration);
this.userCodeClassLoader = checkNotNull(userCodeClassLoader);
this.memManager = checkNotNull(memManager);
+ this.sharedResources = checkNotNull(sharedResources);
this.ioManager = checkNotNull(ioManager);
this.bcVarManager = checkNotNull(bcVarManager);
this.taskStateManager = checkNotNull(taskStateManager);
@@ -219,6 +223,11 @@ public class RuntimeEnvironment implements Environment {
return memManager;
}
+ @Override
+ public SharedResources getSharedResources() {
+ return sharedResources;
+ }
+
@Override
public IOManager getIOManager() {
return ioManager;
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/Task.java b/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/Task.java
index 6dff6974e47..059534f346e 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/Task.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/Task.java
@@ -66,6 +66,7 @@ import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.jobgraph.tasks.TaskInvokable;
import org.apache.flink.runtime.jobgraph.tasks.TaskOperatorEventGateway;
import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.TaskMetricGroup;
import org.apache.flink.runtime.operators.coordination.OperatorEvent;
import org.apache.flink.runtime.operators.coordination.TaskNotRunningException;
@@ -191,6 +192,9 @@ public class Task
/** The memory manager to be used by this task. */
private final MemoryManager memoryManager;
+ /** Shared memory manager provided by the task manager. */
+ private final SharedResources sharedResources;
+
/** The I/O manager to be used by this task. */
private final IOManager ioManager;
@@ -302,6 +306,7 @@ public class Task
List<ResultPartitionDeploymentDescriptor> resultPartitionDeploymentDescriptors,
List<InputGateDeploymentDescriptor> inputGateDeploymentDescriptors,
MemoryManager memManager,
+ SharedResources sharedResources,
IOManager ioManager,
ShuffleEnvironment<?, ?> shuffleEnvironment,
KvStateService kvStateService,
@@ -352,6 +357,7 @@ public class Task
tmConfig.getLong(TaskManagerOptions.TASK_CANCELLATION_TIMEOUT);
this.memoryManager = Preconditions.checkNotNull(memManager);
+ this.sharedResources = Preconditions.checkNotNull(sharedResources);
this.ioManager = Preconditions.checkNotNull(ioManager);
this.broadcastVariableManager = Preconditions.checkNotNull(bcVarManager);
this.taskEventDispatcher = Preconditions.checkNotNull(taskEventDispatcher);
@@ -685,6 +691,7 @@ public class Task
taskConfiguration,
userCodeClassLoader,
memoryManager,
+ sharedResources,
ioManager,
broadcastVariableManager,
taskStateManager,
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/DummyEnvironment.java b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/DummyEnvironment.java
index db98c9ef15c..260e83331bb 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/DummyEnvironment.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/DummyEnvironment.java
@@ -39,6 +39,7 @@ import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.jobgraph.tasks.TaskOperatorEventGateway;
import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.TaskMetricGroup;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.query.KvStateRegistry;
@@ -165,6 +166,11 @@ public class DummyEnvironment implements Environment {
return null;
}
+ @Override
+ public SharedResources getSharedResources() {
+ return null;
+ }
+
@Override
public UserCodeClassLoader getUserCodeClassLoader() {
if (userClassLoader == null) {
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/MockEnvironment.java b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/MockEnvironment.java
index 3f3b2594a29..a5a53780b6c 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/MockEnvironment.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/MockEnvironment.java
@@ -43,6 +43,7 @@ import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.jobgraph.tasks.TaskOperatorEventGateway;
import org.apache.flink.runtime.mailbox.SyncMailboxExecutor;
import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.TaskMetricGroup;
import org.apache.flink.runtime.query.KvStateRegistry;
import org.apache.flink.runtime.query.TaskKvStateRegistry;
@@ -80,6 +81,8 @@ public class MockEnvironment implements Environment, AutoCloseable {
private final MemoryManager memManager;
+ private final SharedResources sharedResources;
+
private final IOManager ioManager;
private final TaskStateManager taskStateManager;
@@ -167,6 +170,7 @@ public class MockEnvironment implements Environment, AutoCloseable {
this.executionAttemptID = createExecutionAttemptId(jobVertexID, subtaskIndex, 0);
this.memManager = memManager;
+ this.sharedResources = new SharedResources();
this.ioManager = ioManager;
this.taskManagerRuntimeInfo = taskManagerRuntimeInfo;
@@ -235,6 +239,11 @@ public class MockEnvironment implements Environment, AutoCloseable {
return this.memManager;
}
+ @Override
+ public SharedResources getSharedResources() {
+ return this.sharedResources;
+ }
+
@Override
public IOManager getIOManager() {
return this.ioManager;
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskExecutorTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskExecutorTest.java
index 8e70fd1d1c9..ca0055ed71e 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskExecutorTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskExecutorTest.java
@@ -38,6 +38,7 @@ import org.apache.flink.runtime.clusterframework.types.SlotID;
import org.apache.flink.runtime.deployment.TaskDeploymentDescriptor;
import org.apache.flink.runtime.deployment.TaskDeploymentDescriptorBuilder;
import org.apache.flink.runtime.entrypoint.ClusterInformation;
+import org.apache.flink.runtime.execution.Environment;
import org.apache.flink.runtime.execution.librarycache.TestingClassLoaderLease;
import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
import org.apache.flink.runtime.externalresource.ExternalResourceInfoProvider;
@@ -117,6 +118,7 @@ import org.apache.flink.util.function.FunctionUtils;
import org.apache.flink.util.function.TriConsumer;
import org.apache.flink.util.function.TriConsumerWithException;
+import org.apache.flink.shaded.curator5.com.google.common.collect.Iterators;
import org.apache.flink.shaded.guava30.com.google.common.collect.Lists;
import org.junit.After;
@@ -128,6 +130,7 @@ import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestName;
import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
@@ -152,7 +155,9 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
+import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.stream.IntStream.range;
@@ -2545,13 +2550,7 @@ public class TaskExecutorTest extends TestLogger {
range(0, 5).mapToObj(i -> new AllocationID()).toArray(AllocationID[]::new);
try (TaskExecutorTestingContext ctx = createTaskExecutorTestingContext(slots.length)) {
ctx.start();
- ResourceManagerId rmId;
- {
- CompletableFuture<Tuple3<ResourceID, InstanceID, SlotReport>>
- initialSlotReportFuture = new CompletableFuture<>();
- rmId = createAndRegisterResourceManager(initialSlotReportFuture);
- initialSlotReportFuture.get();
- }
+ ResourceManagerId rmId = getResourceManagerId();
TaskExecutorGateway tm = ctx.taskExecutor.getSelfGateway(TaskExecutorGateway.class);
for (int i = 0; i < slots.length; i++) {
@@ -2575,9 +2574,7 @@ public class TaskExecutorTest extends TestLogger {
tm.cancelTask(exec, timeout).get();
// wait for task thread to notify TM about its final state
// (taskSlotTable isn't thread safe - using MainThread)
- while (callInMain(ctx, () -> ctx.taskSlotTable.getTasks(jobId).hasNext())) {
- Thread.sleep(50);
- }
+ waitForTasks(ctx, numTasks -> numTasks > 0);
for (int i = 0; i < slots.length; i++) {
tm.freeSlot(slots[i], new RuntimeException("test exception"), timeout).get();
@@ -3037,4 +3034,134 @@ public class TaskExecutorTest extends TestLogger {
.callAsync(booleanCallable, Duration.ofSeconds(5))
.get();
}
+
+ @Test
+ public void testSharedResourcesLifecycle() throws Exception {
+ SharedResourceCollectingInvokable.reset();
+ AllocationID[] slots =
+ range(0, 5).mapToObj(i -> new AllocationID()).toArray(AllocationID[]::new);
+
+ try (TaskExecutorTestingContext ctx = createTaskExecutorTestingContext(slots.length)) {
+ // prepare: start services
+ ctx.start();
+ ResourceManagerId rmId = getResourceManagerId();
+ TaskExecutorGateway taskGateway =
+ ctx.taskExecutor.getSelfGateway(TaskExecutorGateway.class);
+ // prepare: request slots
+ for (int i = 0; i < slots.length; i++) {
+ requestSlot(
+ taskGateway,
+ jobId,
+ slots[i],
+ new SlotID(ctx.taskExecutor.getResourceID(), i),
+ ResourceProfile.UNKNOWN,
+ ctx.jobMasterGateway.getAddress(),
+ rmId);
+ }
+ ctx.offerSlotsLatch.await();
+ // prepare: submit tasks
+ List<ExecutionAttemptID> executions = new ArrayList<>(slots.length);
+ for (AllocationID allocationID : slots) {
+ executions.add(
+ submit(
+ allocationID,
+ ctx.jobMasterGateway,
+ taskGateway,
+ SharedResourceCollectingInvokable.class));
+ }
+ waitForTasks(ctx, numTasks -> numTasks < slots.length);
+ // cancel tasks
+ // verify that the resource is not released as long as there are tasks running
+ for (int i = 0; i < executions.size(); i++) {
+ int numRemaining = slots.length - i;
+ ctx.taskExecutor.cancelTask(executions.get(i), timeout).get();
+ waitForTasks(ctx, numTasks -> numTasks > numRemaining);
+ if (numRemaining > 0) {
+ assertEquals(0, SharedResourceCollectingInvokable.timesDeallocated.get());
+ }
+ }
+ }
+ // verify
+ assertEquals(1, SharedResourceCollectingInvokable.timesAllocated.get());
+ assertEquals(1, SharedResourceCollectingInvokable.timesDeallocated.get());
+ }
+
+ private void waitForTasks(
+ TaskExecutorTestingContext ctx, Function<Integer, Boolean> waitPredicate)
+ throws InterruptedException, ExecutionException {
+ while (callInMain(
+ ctx,
+ () -> waitPredicate.apply(Iterators.size(ctx.taskSlotTable.getTasks(jobId))))) {
+ Thread.sleep(50);
+ }
+ }
+
+ private ResourceManagerId getResourceManagerId()
+ throws InterruptedException, ExecutionException {
+ CompletableFuture<Tuple3<ResourceID, InstanceID, SlotReport>> initialSlotReportFuture =
+ new CompletableFuture<>();
+ ResourceManagerId rmId = createAndRegisterResourceManager(initialSlotReportFuture);
+ initialSlotReportFuture.get();
+ return rmId;
+ }
+
+ public static class SharedResourceCollectingInvokable implements TaskInvokable {
+
+ public static void reset() {
+ timesAllocated.set(0);
+ timesDeallocated.set(0);
+ }
+
+ private static final String RESOURCE_ID = "test";
+ private static final AtomicInteger timesAllocated = new AtomicInteger(0);
+ private static final AtomicInteger timesDeallocated = new AtomicInteger(0);
+
+ private final Environment env;
+ private final Object leaseHolder;
+ private volatile boolean cancelled = false;
+
+ public SharedResourceCollectingInvokable(Environment env) {
+ this.env = env;
+ this.leaseHolder = new Object();
+ }
+
+ @Override
+ public void invoke() throws Exception {
+ this.env
+ .getSharedResources()
+ .getOrAllocateSharedResource(
+ RESOURCE_ID,
+ leaseHolder,
+ unused -> {
+ timesAllocated.incrementAndGet();
+ return timesDeallocated::incrementAndGet;
+ },
+ 0L);
+ while (!cancelled) {
+ Thread.sleep(50);
+ }
+ }
+
+ @Override
+ public void restore() throws Exception {}
+
+ @Override
+ public void cleanUp(@Nullable Throwable throwable) throws Exception {
+ env.getSharedResources().release(RESOURCE_ID, leaseHolder, unused -> {});
+ }
+
+ @Override
+ public void cancel() throws Exception {
+ cancelled = true;
+ }
+
+ @Override
+ public boolean isUsingNonBlockingInput() {
+ return false;
+ }
+
+ @Override
+ public void maybeInterruptOnCancel(
+ Thread toInterrupt, @Nullable String taskName, @Nullable Long timeout) {}
+ }
}
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskManagerServicesBuilder.java b/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskManagerServicesBuilder.java
index a2d299cc848..cfbf6548dd5 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskManagerServicesBuilder.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskManagerServicesBuilder.java
@@ -24,6 +24,7 @@ import org.apache.flink.runtime.execution.librarycache.TestingLibraryCacheManage
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.runtime.io.network.TaskEventDispatcher;
import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.query.KvStateRegistry;
import org.apache.flink.runtime.registration.RetryingRegistrationConfiguration;
import org.apache.flink.runtime.shuffle.ShuffleEnvironment;
@@ -59,6 +60,7 @@ public class TaskManagerServicesBuilder {
private TaskExecutorStateChangelogStoragesManager taskChangelogStoragesManager;
private TaskEventDispatcher taskEventDispatcher;
private LibraryCacheManager libraryCacheManager;
+ private SharedResources sharedResources;
private long managedMemorySize;
private SlotAllocationSnapshotPersistenceService slotAllocationSnapshotPersistenceService;
@@ -84,6 +86,7 @@ public class TaskManagerServicesBuilder {
managedMemorySize = MemoryManager.MIN_PAGE_SIZE;
this.slotAllocationSnapshotPersistenceService =
NoOpSlotAllocationSnapshotPersistenceService.INSTANCE;
+ sharedResources = new SharedResources();
}
public TaskManagerServicesBuilder setUnresolvedTaskManagerLocation(
@@ -174,6 +177,7 @@ public class TaskManagerServicesBuilder {
taskEventDispatcher,
Executors.newSingleThreadScheduledExecutor(),
libraryCacheManager,
- slotAllocationSnapshotPersistenceService);
+ slotAllocationSnapshotPersistenceService,
+ sharedResources);
}
}
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/taskmanager/TaskAsyncCallTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/taskmanager/TaskAsyncCallTest.java
index 2d63ea3787b..1eb55ab0c04 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/taskmanager/TaskAsyncCallTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/taskmanager/TaskAsyncCallTest.java
@@ -44,6 +44,7 @@ import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.TaskMetricGroup;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.query.KvStateRegistry;
@@ -199,6 +200,7 @@ public class TaskAsyncCallTest extends TestLogger {
Collections.<ResultPartitionDeploymentDescriptor>emptyList(),
Collections.<InputGateDeploymentDescriptor>emptyList(),
mock(MemoryManager.class),
+ new SharedResources(),
mock(IOManager.class),
shuffleEnvironment,
new KvStateService(new KvStateRegistry(), null, null),
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/taskmanager/TestTaskBuilder.java b/flink-runtime/src/test/java/org/apache/flink/runtime/taskmanager/TestTaskBuilder.java
index e64c1ed401c..a2559c5e650 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/taskmanager/TestTaskBuilder.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/taskmanager/TestTaskBuilder.java
@@ -40,6 +40,7 @@ import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
import org.apache.flink.runtime.jobgraph.tasks.TaskInvokable;
import org.apache.flink.runtime.memory.MemoryManagerBuilder;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.TaskMetricGroup;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.operators.testutils.MockInputSplitProvider;
@@ -206,6 +207,7 @@ public final class TestTaskBuilder {
resultPartitions,
inputGates,
MemoryManagerBuilder.newBuilder().setMemorySize(1024 * 1024).build(),
+ new SharedResources(),
mock(IOManager.class),
shuffleEnvironment,
kvStateService,
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/testutils/InMemoryReporter.java b/flink-runtime/src/test/java/org/apache/flink/runtime/testutils/InMemoryReporter.java
index ed9cf73dda4..4abb4558d4b 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/testutils/InMemoryReporter.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/testutils/InMemoryReporter.java
@@ -19,6 +19,7 @@ package org.apache.flink.runtime.testutils;
import org.apache.flink.annotation.Experimental;
import org.apache.flink.api.common.JobID;
+import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.MetricOptions;
import org.apache.flink.metrics.LogicalScopeProvider;
@@ -166,6 +167,28 @@ public class InMemoryReporter implements MetricReporter {
}
}
+ public List<Tuple3<MetricGroup, String, Metric>> findJobMetricGroups(
+ JobID jobId, String metricPattern) {
+ Pattern pattern = Pattern.compile(metricPattern);
+ synchronized (this) {
+ return metrics.entrySet().stream()
+ .filter(group -> Objects.equals(getJobId(group.getKey()), jobId.toString()))
+ .flatMap(
+ group ->
+ group.getValue().entrySet().stream()
+ .filter(
+ metric ->
+ pattern.matcher(metric.getKey()).find())
+ .map(
+ metric ->
+ Tuple3.of(
+ group.getKey(),
+ metric.getKey(),
+ metric.getValue())))
+ .collect(Collectors.toList());
+ }
+ }
+
private String getSubtaskId(OperatorMetricGroup g) {
return g.getAllVariables().get(ScopeFormat.SCOPE_TASK_SUBTASK_INDEX);
}
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/util/JvmExitOnFatalErrorTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/util/JvmExitOnFatalErrorTest.java
index d86e2219af5..18c026105e5 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/util/JvmExitOnFatalErrorTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/util/JvmExitOnFatalErrorTest.java
@@ -45,6 +45,7 @@ import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.memory.MemoryManager;
import org.apache.flink.runtime.memory.MemoryManagerBuilder;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.query.KvStateRegistry;
import org.apache.flink.runtime.shuffle.ShuffleEnvironment;
@@ -233,6 +234,7 @@ public class JvmExitOnFatalErrorTest extends TestLogger {
Collections.<ResultPartitionDeploymentDescriptor>emptyList(),
Collections.<InputGateDeploymentDescriptor>emptyList(),
memoryManager,
+ new SharedResources(),
ioManager,
shuffleEnvironment,
new KvStateService(new KvStateRegistry(), null, null),
diff --git a/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/EmbeddedRocksDBStateBackend.java b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/EmbeddedRocksDBStateBackend.java
index 8ce78342d3c..eb2f3f48cc8 100644
--- a/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/EmbeddedRocksDBStateBackend.java
+++ b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/EmbeddedRocksDBStateBackend.java
@@ -460,7 +460,7 @@ public class EmbeddedRocksDBStateBackend extends AbstractManagedMemoryStateBacke
final OpaqueMemoryResource<RocksDBSharedResources> sharedResources =
RocksDBOperationUtils.allocateSharedCachesIfConfigured(
- memoryConfiguration, env.getMemoryManager(), managedMemoryFraction, LOG);
+ memoryConfiguration, env, managedMemoryFraction, LOG);
if (sharedResources != null) {
LOG.info("Obtained shared RocksDB cache of size {} bytes", sharedResources.getSize());
}
diff --git a/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBMemoryConfiguration.java b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBMemoryConfiguration.java
index 129f5ba6f39..5c412e99365 100644
--- a/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBMemoryConfiguration.java
+++ b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBMemoryConfiguration.java
@@ -18,6 +18,7 @@
package org.apache.flink.contrib.streaming.state;
+import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.MemorySize;
import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.util.Preconditions;
@@ -240,4 +241,8 @@ public final class RocksDBMemoryConfiguration implements Serializable {
return newConfig;
}
+
+ public static RocksDBMemoryConfiguration fromConfiguration(Configuration configuration) {
+ return fromOtherAndConfiguration(new RocksDBMemoryConfiguration(), configuration);
+ }
}
diff --git a/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBMemoryControllerUtils.java b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBMemoryControllerUtils.java
index 78aa1a5e7da..2ea022137b8 100644
--- a/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBMemoryControllerUtils.java
+++ b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBMemoryControllerUtils.java
@@ -23,12 +23,15 @@ import org.apache.flink.annotation.VisibleForTesting;
import org.rocksdb.Cache;
import org.rocksdb.LRUCache;
import org.rocksdb.WriteBufferManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Utils to create {@link Cache} and {@link WriteBufferManager} which are used to control total
* memory usage of RocksDB.
*/
public class RocksDBMemoryControllerUtils {
+ private static final Logger LOG = LoggerFactory.getLogger(RocksDBMemoryControllerUtils.class);
/**
* Allocate memory controllable RocksDB shared resources.
@@ -57,6 +60,12 @@ public class RocksDBMemoryControllerUtils {
RocksDBMemoryControllerUtils.createWriteBufferManager(
writeBufferManagerCapacity, cache);
+ LOG.debug(
+ "Allocated RocksDB shared resources, calculatedCacheCapacity: {}, highPriorityPoolRatio: {}, writeBufferManagerCapacity: {}, usingPartitionedIndexFilters: {}",
+ calculatedCacheCapacity,
+ highPriorityPoolRatio,
+ writeBufferManagerCapacity,
+ usingPartitionedIndexFilters);
return new RocksDBSharedResources(
cache, wbm, writeBufferManagerCapacity, usingPartitionedIndexFilters);
}
@@ -82,7 +91,7 @@ public class RocksDBMemoryControllerUtils {
* @return The actual calculated cache capacity.
*/
@VisibleForTesting
- static long calculateActualCacheCapacity(long totalMemorySize, double writeBufferRatio) {
+ public static long calculateActualCacheCapacity(long totalMemorySize, double writeBufferRatio) {
return (long) ((3 - writeBufferRatio) * totalMemorySize / 3);
}
diff --git a/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBOperationUtils.java b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBOperationUtils.java
index 9f06c19817c..0d09dc7b729 100644
--- a/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBOperationUtils.java
+++ b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBOperationUtils.java
@@ -19,14 +19,13 @@ package org.apache.flink.contrib.streaming.state;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.contrib.streaming.state.ttl.RocksDbTtlCompactFiltersManager;
-import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.execution.Environment;
import org.apache.flink.runtime.memory.OpaqueMemoryResource;
import org.apache.flink.runtime.state.RegisteredStateMetaInfoBase;
import org.apache.flink.util.FlinkRuntimeException;
import org.apache.flink.util.IOUtils;
import org.apache.flink.util.OperatingSystem;
import org.apache.flink.util.Preconditions;
-import org.apache.flink.util.function.LongFunctionWithException;
import org.rocksdb.ColumnFamilyDescriptor;
import org.rocksdb.ColumnFamilyHandle;
@@ -53,10 +52,6 @@ import static org.apache.flink.contrib.streaming.state.RocksDBKeyedStateBackend.
public class RocksDBOperationUtils {
private static final Logger LOG = LoggerFactory.getLogger(RocksDBOperationUtils.class);
- private static final String MANAGED_MEMORY_RESOURCE_ID = "state-rocks-managed-memory";
-
- private static final String FIXED_SLOT_MEMORY_RESOURCE_ID = "state-rocks-fixed-slot-memory";
-
public static RocksDB openDB(
String path,
List<ColumnFamilyDescriptor> stateColumnFamilyDescriptors,
@@ -256,42 +251,21 @@ public class RocksDBOperationUtils {
@Nullable
public static OpaqueMemoryResource<RocksDBSharedResources> allocateSharedCachesIfConfigured(
- RocksDBMemoryConfiguration memoryConfig,
- MemoryManager memoryManager,
+ RocksDBMemoryConfiguration jobMemoryConfig,
+ Environment env,
double memoryFraction,
Logger logger)
throws IOException {
- if (!memoryConfig.isUsingFixedMemoryPerSlot() && !memoryConfig.isUsingManagedMemory()) {
- return null;
- }
-
- final double highPriorityPoolRatio = memoryConfig.getHighPriorityPoolRatio();
- final double writeBufferRatio = memoryConfig.getWriteBufferRatio();
- final boolean usingPartitionedIndexFilters = memoryConfig.isUsingPartitionedIndexFilters();
-
- final LongFunctionWithException<RocksDBSharedResources, Exception> allocator =
- (size) ->
- RocksDBMemoryControllerUtils.allocateRocksDBSharedResources(
- size,
- writeBufferRatio,
- highPriorityPoolRatio,
- usingPartitionedIndexFilters);
-
try {
- if (memoryConfig.isUsingFixedMemoryPerSlot()) {
- assert memoryConfig.getFixedMemoryPerSlot() != null;
-
- logger.info("Getting fixed-size shared cache for RocksDB.");
- return memoryManager.getExternalSharedMemoryResource(
- FIXED_SLOT_MEMORY_RESOURCE_ID,
- allocator,
- memoryConfig.getFixedMemoryPerSlot().getBytes());
- } else {
- logger.info("Getting managed memory shared cache for RocksDB.");
- return memoryManager.getSharedMemoryResourceForManagedMemory(
- MANAGED_MEMORY_RESOURCE_ID, allocator, memoryFraction);
+ RocksDBSharedResourcesFactory factory =
+ RocksDBSharedResourcesFactory.from(jobMemoryConfig, env);
+ if (factory == null) {
+ return null;
}
+
+ return factory.create(jobMemoryConfig, env, memoryFraction, logger);
+
} catch (Exception e) {
throw new IOException("Failed to acquire shared cache resource for RocksDB", e);
}
diff --git a/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBOptions.java b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBOptions.java
index f9d602d8013..44ad83e2dd8 100644
--- a/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBOptions.java
+++ b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBOptions.java
@@ -118,10 +118,23 @@ public class RocksDBOptions {
.withDescription(
String.format(
"The fixed total amount of memory, shared among all RocksDB instances per slot. "
- + "This option overrides the '%s' option when configured. If neither this option, nor the '%s' option"
- + "are set, then each RocksDB column family state has its own memory caches (as controlled by the column "
- + "family options).",
- USE_MANAGED_MEMORY.key(), USE_MANAGED_MEMORY.key()));
+ + "This option overrides the '%s' option when configured.",
+ USE_MANAGED_MEMORY.key()));
+
+ @Documentation.Section(Documentation.Sections.STATE_BACKEND_ROCKSDB)
+ public static final ConfigOption<MemorySize> FIX_PER_TM_MEMORY_SIZE =
+ ConfigOptions.key("state.backend.rocksdb.memory.fixed-per-tm")
+ .memoryType()
+ .noDefaultValue()
+ .withDescription(
+ String.format(
+ "The fixed total amount of memory, shared among all RocksDB instances per Task Manager (cluster-level option). "
+ + "This option only takes effect if neither '%s' nor '%s' are not configured. If none is configured "
+ + "then each RocksDB column family state has its own memory caches (as controlled by the column "
+ + "family options). "
+ + "The relevant options for the shared resources (e.g. write-buffer-ratio) can be set on the same level (flink-conf.yaml)."
+ + "Note, that this feature breaks resource isolation between the slots",
+ USE_MANAGED_MEMORY.key(), FIX_PER_SLOT_MEMORY_SIZE.key()));
@Documentation.Section(Documentation.Sections.STATE_BACKEND_ROCKSDB)
public static final ConfigOption<Double> WRITE_BUFFER_RATIO =
diff --git a/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBSharedResources.java b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBSharedResources.java
index f48f4eb0256..3258b06e9f8 100644
--- a/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBSharedResources.java
+++ b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBSharedResources.java
@@ -20,12 +20,15 @@ package org.apache.flink.contrib.streaming.state;
import org.rocksdb.Cache;
import org.rocksdb.WriteBufferManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* The set of resources that can be shared by all RocksDB instances in a slot. Sharing these
* resources helps RocksDB a predictable resource footprint.
*/
final class RocksDBSharedResources implements AutoCloseable {
+ private static final Logger LOG = LoggerFactory.getLogger(RocksDBSharedResources.class);
private final Cache cache;
@@ -63,6 +66,7 @@ final class RocksDBSharedResources implements AutoCloseable {
@Override
public void close() {
+ LOG.debug("Closing RocksDBSharedResources");
writeBufferManager.close();
cache.close();
}
diff --git a/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBSharedResourcesFactory.java b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBSharedResourcesFactory.java
new file mode 100644
index 00000000000..06cbd62f67d
--- /dev/null
+++ b/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBSharedResourcesFactory.java
@@ -0,0 +1,183 @@
+/*
+ * 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.contrib.streaming.state;
+
+import org.apache.flink.configuration.MemorySize;
+import org.apache.flink.runtime.execution.Environment;
+import org.apache.flink.runtime.memory.OpaqueMemoryResource;
+import org.apache.flink.runtime.memory.SharedResources;
+import org.apache.flink.util.function.LongFunctionWithException;
+import org.apache.flink.util.function.ThrowingRunnable;
+
+import org.slf4j.Logger;
+
+import javax.annotation.Nullable;
+
+import static org.apache.flink.contrib.streaming.state.RocksDBOptions.FIX_PER_TM_MEMORY_SIZE;
+
+/**
+ * A factory of {@link RocksDBSharedResources}. Encapsulates memory share scope (e.g. TM, Slot) and
+ * lifecycle (managed/unmanaged).
+ */
+enum RocksDBSharedResourcesFactory {
+ /** Memory allocated per Slot (shared across slot tasks), managed by Flink. */
+ SLOT_SHARED_MANAGED(false, MemoryShareScope.SLOT) {
+ @Override
+ protected OpaqueMemoryResource<RocksDBSharedResources> createInternal(
+ RocksDBMemoryConfiguration jobMemoryConfig,
+ String resourceId,
+ Environment env,
+ double memoryFraction,
+ LongFunctionWithException<RocksDBSharedResources, Exception> allocator)
+ throws Exception {
+ return env.getMemoryManager()
+ .getSharedMemoryResourceForManagedMemory(resourceId, allocator, memoryFraction);
+ }
+ },
+ /** Memory allocated per Slot (shared across slot tasks), unmanaged. */
+ SLOT_SHARED_UNMANAGED(false, MemoryShareScope.SLOT) {
+ @Override
+ protected OpaqueMemoryResource<RocksDBSharedResources> createInternal(
+ RocksDBMemoryConfiguration jobMemoryConfig,
+ String resourceId,
+ Environment env,
+ double memoryFraction,
+ LongFunctionWithException<RocksDBSharedResources, Exception> allocator)
+ throws Exception {
+ return env.getMemoryManager()
+ .getExternalSharedMemoryResource(
+ resourceId,
+ allocator,
+ jobMemoryConfig.getFixedMemoryPerSlot().getBytes());
+ }
+ },
+ /** Memory allocated per TM (shared across all tasks), unmanaged. */
+ TM_SHARED_UNMANAGED(false, MemoryShareScope.TM) {
+ @Override
+ protected OpaqueMemoryResource<RocksDBSharedResources> createInternal(
+ RocksDBMemoryConfiguration jobMemoryConfig,
+ String resourceId,
+ Environment env,
+ double memoryFraction,
+ LongFunctionWithException<RocksDBSharedResources, Exception> allocator)
+ throws Exception {
+
+ SharedResources sharedResources = env.getSharedResources();
+ Object leaseHolder = new Object();
+ SharedResources.ResourceAndSize<RocksDBSharedResources> resource =
+ sharedResources.getOrAllocateSharedResource(
+ resourceId, leaseHolder, allocator, getTmSharedMemorySize(env));
+ ThrowingRunnable<Exception> disposer =
+ () -> sharedResources.release(resourceId, leaseHolder, unused -> {});
+
+ return new OpaqueMemoryResource<>(resource.resourceHandle(), resource.size(), disposer);
+ }
+ };
+
+ private final boolean managed;
+ private final MemoryShareScope shareScope;
+
+ RocksDBSharedResourcesFactory(boolean managed, MemoryShareScope shareScope) {
+ this.managed = managed;
+ this.shareScope = shareScope;
+ }
+
+ @Nullable
+ public static RocksDBSharedResourcesFactory from(
+ RocksDBMemoryConfiguration jobMemoryConfig, Environment env) {
+ if (jobMemoryConfig.isUsingFixedMemoryPerSlot()) {
+ return RocksDBSharedResourcesFactory.SLOT_SHARED_UNMANAGED;
+ } else if (jobMemoryConfig.isUsingManagedMemory()) {
+ return RocksDBSharedResourcesFactory.SLOT_SHARED_MANAGED;
+ } else if (getTmSharedMemorySize(env) > 0) {
+ return RocksDBSharedResourcesFactory.TM_SHARED_UNMANAGED;
+ } else {
+ // not shared and not managed - allocate per column family
+ return null;
+ }
+ }
+
+ public final OpaqueMemoryResource<RocksDBSharedResources> create(
+ RocksDBMemoryConfiguration jobMemoryConfig,
+ Environment env,
+ double memoryFraction,
+ Logger logger)
+ throws Exception {
+ logger.info(
+ "Getting shared memory for RocksDB: shareScope={}, managed={}",
+ shareScope,
+ managed);
+ return createInternal(
+ jobMemoryConfig,
+ managed ? MANAGED_MEMORY_RESOURCE_ID : UNMANAGED_MEMORY_RESOURCE_ID,
+ env,
+ memoryFraction,
+ createAllocator(shareScope.getConfiguration(jobMemoryConfig, env)));
+ }
+
+ protected abstract OpaqueMemoryResource<RocksDBSharedResources> createInternal(
+ RocksDBMemoryConfiguration jobMemoryConfig,
+ String resourceId,
+ Environment env,
+ double memoryFraction,
+ LongFunctionWithException<RocksDBSharedResources, Exception> allocator)
+ throws Exception;
+
+ private static long getTmSharedMemorySize(Environment env) {
+ return env.getTaskManagerInfo()
+ .getConfiguration()
+ .getOptional(FIX_PER_TM_MEMORY_SIZE)
+ .orElse(MemorySize.ZERO)
+ .getBytes();
+ }
+
+ private static final String MANAGED_MEMORY_RESOURCE_ID = "state-rocks-managed-memory";
+
+ private static final String UNMANAGED_MEMORY_RESOURCE_ID = "state-rocks-fixed-slot-memory";
+
+ private static LongFunctionWithException<RocksDBSharedResources, Exception> createAllocator(
+ RocksDBMemoryConfiguration config) {
+ return size ->
+ RocksDBMemoryControllerUtils.allocateRocksDBSharedResources(
+ size,
+ config.getWriteBufferRatio(),
+ config.getHighPriorityPoolRatio(),
+ config.isUsingPartitionedIndexFilters());
+ }
+}
+
+enum MemoryShareScope {
+ TM {
+ @Override
+ public RocksDBMemoryConfiguration getConfiguration(
+ RocksDBMemoryConfiguration jobMemoryConfig, Environment env) {
+ return RocksDBMemoryConfiguration.fromConfiguration(
+ env.getTaskManagerInfo().getConfiguration());
+ }
+ },
+ SLOT {
+ @Override
+ public RocksDBMemoryConfiguration getConfiguration(
+ RocksDBMemoryConfiguration jobMemoryConfig, Environment env) {
+ return jobMemoryConfig;
+ }
+ };
+
+ public abstract RocksDBMemoryConfiguration getConfiguration(
+ RocksDBMemoryConfiguration jobMemoryConfig, Environment env);
+}
diff --git a/flink-state-backends/flink-statebackend-rocksdb/src/test/java/org/apache/flink/contrib/streaming/state/RocksDBSharedResourcesFactoryTest.java b/flink-state-backends/flink-statebackend-rocksdb/src/test/java/org/apache/flink/contrib/streaming/state/RocksDBSharedResourcesFactoryTest.java
new file mode 100644
index 00000000000..e28eebe82d3
--- /dev/null
+++ b/flink-state-backends/flink-statebackend-rocksdb/src/test/java/org/apache/flink/contrib/streaming/state/RocksDBSharedResourcesFactoryTest.java
@@ -0,0 +1,162 @@
+/*
+ * 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.contrib.streaming.state;
+
+import org.apache.flink.configuration.ConfigOption;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.MemorySize;
+import org.apache.flink.runtime.execution.Environment;
+import org.apache.flink.runtime.memory.OpaqueMemoryResource;
+import org.apache.flink.runtime.operators.testutils.MockEnvironment;
+import org.apache.flink.runtime.taskexecutor.TaskManagerConfiguration;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Map;
+import java.util.stream.Stream;
+
+import static java.util.Collections.emptyMap;
+import static java.util.Collections.singletonMap;
+import static org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend.ensureRocksDBIsLoaded;
+import static org.apache.flink.contrib.streaming.state.RocksDBMemoryControllerUtils.calculateWriteBufferManagerCapacity;
+import static org.apache.flink.contrib.streaming.state.RocksDBOptions.FIX_PER_SLOT_MEMORY_SIZE;
+import static org.apache.flink.contrib.streaming.state.RocksDBOptions.FIX_PER_TM_MEMORY_SIZE;
+import static org.apache.flink.contrib.streaming.state.RocksDBOptions.USE_MANAGED_MEMORY;
+import static org.apache.flink.contrib.streaming.state.RocksDBOptions.WRITE_BUFFER_RATIO;
+import static org.apache.flink.contrib.streaming.state.RocksDBSharedResourcesFactory.SLOT_SHARED_MANAGED;
+import static org.apache.flink.contrib.streaming.state.RocksDBSharedResourcesFactory.SLOT_SHARED_UNMANAGED;
+import static org.apache.flink.contrib.streaming.state.RocksDBSharedResourcesFactory.TM_SHARED_UNMANAGED;
+import static org.apache.flink.runtime.taskexecutor.TaskExecutorResourceUtils.resourceSpecFromConfigForLocalExecution;
+import static org.apache.flink.util.CollectionUtil.entry;
+import static org.apache.flink.util.CollectionUtil.map;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.params.provider.Arguments.arguments;
+
+/** {@link RocksDBSharedResourcesFactory} test. */
+public class RocksDBSharedResourcesFactoryTest {
+ private static final Logger LOG =
+ LoggerFactory.getLogger(RocksDBSharedResourcesFactoryTest.class);
+
+ @TempDir static Path tempDir;
+
+ @BeforeAll
+ static void init() throws IOException {
+ ensureRocksDBIsLoaded(tempDir.toAbsolutePath().toString());
+ }
+
+ private static Stream<Arguments> getSelectionStrategyParams() {
+ Map<Object, Object> defaults = emptyMap();
+
+ // format: job options, tm options, expected factory type
+ return Stream.of(
+ // default: per slot, managed
+ arguments(defaults, defaults, SLOT_SHARED_MANAGED),
+ // no sharing (allocate per column family), unmanaged
+ arguments(singletonMap(USE_MANAGED_MEMORY, false), defaults, null),
+ // prioritize managed (set explicitly)
+ arguments(
+ singletonMap(USE_MANAGED_MEMORY, true),
+ singletonMap(FIX_PER_TM_MEMORY_SIZE, MemorySize.ofMebiBytes(1)),
+ SLOT_SHARED_MANAGED),
+ // prioritize managed (job default)
+ arguments(
+ defaults,
+ singletonMap(FIX_PER_TM_MEMORY_SIZE, MemorySize.ofMebiBytes(1)),
+ SLOT_SHARED_MANAGED),
+ // prioritize fixed-per-slot over fixed-per-tm
+ arguments(
+ singletonMap(FIX_PER_SLOT_MEMORY_SIZE, MemorySize.ofMebiBytes(1)),
+ singletonMap(FIX_PER_TM_MEMORY_SIZE, MemorySize.ofMebiBytes(1)),
+ SLOT_SHARED_UNMANAGED),
+ // prioritize fixed-per-slot over managed
+ arguments(
+ map(
+ entry(FIX_PER_SLOT_MEMORY_SIZE, MemorySize.ofMebiBytes(1)),
+ entry(USE_MANAGED_MEMORY, true)),
+ singletonMap(FIX_PER_TM_MEMORY_SIZE, MemorySize.ofMebiBytes(1)),
+ SLOT_SHARED_UNMANAGED),
+ // use fixed-per-tm - when not managed and not fixed-per-slot
+ arguments(
+ singletonMap(USE_MANAGED_MEMORY, false),
+ singletonMap(FIX_PER_TM_MEMORY_SIZE, MemorySize.ofMebiBytes(1)),
+ TM_SHARED_UNMANAGED));
+ }
+
+ @ParameterizedTest(name = "jobConfig: {0}, tmConfig: {1}")
+ @MethodSource("getSelectionStrategyParams")
+ @SuppressWarnings("rawtypes")
+ public void testSelectionStrategy(
+ Map<ConfigOption, Object> jobOptions,
+ Map<ConfigOption, Object> tmOptions,
+ RocksDBSharedResourcesFactory expected)
+ throws IOException {
+
+ Configuration jobConfig = new Configuration();
+ jobOptions.forEach(jobConfig::set);
+
+ Configuration tmConfig = new Configuration();
+ tmOptions.forEach(tmConfig::set);
+
+ assertEquals(
+ expected,
+ RocksDBSharedResourcesFactory.from(
+ RocksDBMemoryConfiguration.fromConfiguration(jobConfig), getEnv(tmConfig)));
+ }
+
+ @Test
+ public void testTmSharedMemorySize() throws Exception {
+ long size = 123L;
+ double writeBufferRatio = .5;
+ Configuration tmConfig = new Configuration();
+ tmConfig.set(FIX_PER_TM_MEMORY_SIZE, new MemorySize(size));
+ tmConfig.set(WRITE_BUFFER_RATIO, writeBufferRatio);
+
+ OpaqueMemoryResource<RocksDBSharedResources> resource =
+ TM_SHARED_UNMANAGED.create(
+ RocksDBMemoryConfiguration.fromConfiguration(new Configuration()),
+ getEnv(tmConfig),
+ 0, // managed memory fraction must be ignored
+ LOG);
+
+ assertEquals(size, resource.getSize());
+ assertEquals(
+ calculateWriteBufferManagerCapacity(size, writeBufferRatio),
+ resource.getResourceHandle().getWriteBufferManagerCapacity());
+ }
+
+ private static Environment getEnv(Configuration tmConfig) throws IOException {
+ return MockEnvironment.builder()
+ .setTaskManagerRuntimeInfo(
+ TaskManagerConfiguration.fromConfiguration(
+ tmConfig,
+ resourceSpecFromConfigForLocalExecution(tmConfig),
+ "localhost",
+ File.createTempFile("prefix", "suffix")))
+ .build();
+ }
+}
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/InterruptSensitiveRestoreTest.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/InterruptSensitiveRestoreTest.java
index 2ec4989d1b2..5ddaaa0229e 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/InterruptSensitiveRestoreTest.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/InterruptSensitiveRestoreTest.java
@@ -46,6 +46,7 @@ import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.query.KvStateRegistry;
import org.apache.flink.runtime.shuffle.ShuffleEnvironment;
@@ -272,6 +273,7 @@ public class InterruptSensitiveRestoreTest {
Collections.<ResultPartitionDeploymentDescriptor>emptyList(),
Collections.<InputGateDeploymentDescriptor>emptyList(),
mock(MemoryManager.class),
+ new SharedResources(),
mock(IOManager.class),
shuffleEnvironment,
new KvStateService(new KvStateRegistry(), null, null),
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamMockEnvironment.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamMockEnvironment.java
index 219676d0ce0..567af50d5b1 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamMockEnvironment.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamMockEnvironment.java
@@ -44,6 +44,7 @@ import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.jobgraph.tasks.TaskOperatorEventGateway;
import org.apache.flink.runtime.memory.MemoryManager;
import org.apache.flink.runtime.memory.MemoryManagerBuilder;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.TaskMetricGroup;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.operators.testutils.MockInputSplitProvider;
@@ -82,6 +83,8 @@ public class StreamMockEnvironment implements Environment {
private final MemoryManager memManager;
+ private final SharedResources sharedResources;
+
private final IOManager ioManager;
private final InputSplitProvider inputSplitProvider;
@@ -178,6 +181,7 @@ public class StreamMockEnvironment implements Environment {
this.outputs = new LinkedList<ResultPartitionWriter>();
this.memManager =
MemoryManagerBuilder.newBuilder().setMemorySize(offHeapMemorySize).build();
+ this.sharedResources = new SharedResources();
this.ioManager = new IOManagerAsync();
this.taskStateManager = Preconditions.checkNotNull(taskStateManager);
this.aggregateManager = new TestGlobalAggregateManager();
@@ -246,6 +250,11 @@ public class StreamMockEnvironment implements Environment {
return this.memManager;
}
+ @Override
+ public SharedResources getSharedResources() {
+ return this.sharedResources;
+ }
+
@Override
public IOManager getIOManager() {
return this.ioManager;
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskSystemExitTest.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskSystemExitTest.java
index 346452d6506..578cd953509 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskSystemExitTest.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskSystemExitTest.java
@@ -41,6 +41,7 @@ import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.memory.MemoryManagerBuilder;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.operators.testutils.MockEnvironmentBuilder;
import org.apache.flink.runtime.query.KvStateRegistry;
@@ -186,6 +187,7 @@ public class StreamTaskSystemExitTest extends TestLogger {
Collections.<ResultPartitionDeploymentDescriptor>emptyList(),
Collections.<InputGateDeploymentDescriptor>emptyList(),
MemoryManagerBuilder.newBuilder().setMemorySize(32L * 1024L).build(),
+ new SharedResources(),
new IOManagerAsync(),
shuffleEnvironment,
new KvStateService(new KvStateRegistry(), null, null),
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskTerminationTest.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskTerminationTest.java
index 6796d594bee..a81888a5ffc 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskTerminationTest.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskTerminationTest.java
@@ -44,6 +44,7 @@ import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.memory.MemoryManagerBuilder;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.query.KvStateRegistry;
import org.apache.flink.runtime.query.TaskKvStateRegistry;
@@ -170,6 +171,7 @@ public class StreamTaskTerminationTest extends TestLogger {
Collections.<ResultPartitionDeploymentDescriptor>emptyList(),
Collections.<InputGateDeploymentDescriptor>emptyList(),
MemoryManagerBuilder.newBuilder().setMemorySize(32L * 1024L).build(),
+ new SharedResources(),
new IOManagerAsync(),
shuffleEnvironment,
new KvStateService(new KvStateRegistry(), null, null),
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/SynchronousCheckpointITCase.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/SynchronousCheckpointITCase.java
index fd44a2a45af..0e18799404e 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/SynchronousCheckpointITCase.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/SynchronousCheckpointITCase.java
@@ -45,6 +45,7 @@ import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.jobgraph.tasks.TaskInvokable;
import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.TaskMetricGroup;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.query.KvStateRegistry;
@@ -256,6 +257,7 @@ public class SynchronousCheckpointITCase {
Collections.<ResultPartitionDeploymentDescriptor>emptyList(),
Collections.<InputGateDeploymentDescriptor>emptyList(),
mock(MemoryManager.class),
+ new SharedResources(),
mock(IOManager.class),
shuffleEnvironment,
new KvStateService(new KvStateRegistry(), null, null),
diff --git a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/TaskCheckpointingBehaviourTest.java b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/TaskCheckpointingBehaviourTest.java
index 6a2a8efcbd8..f936b1f65db 100644
--- a/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/TaskCheckpointingBehaviourTest.java
+++ b/flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/TaskCheckpointingBehaviourTest.java
@@ -51,6 +51,7 @@ import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.memory.SharedResources;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.query.KvStateRegistry;
import org.apache.flink.runtime.shuffle.ShuffleEnvironment;
@@ -223,6 +224,7 @@ public class TaskCheckpointingBehaviourTest extends TestLogger {
Collections.<ResultPartitionDeploymentDescriptor>emptyList(),
Collections.<InputGateDeploymentDescriptor>emptyList(),
mock(MemoryManager.class),
+ new SharedResources(),
mock(IOManager.class),
shuffleEnvironment,
new KvStateService(new KvStateRegistry(), null, null),
diff --git a/flink-tests/src/test/java/org/apache/flink/test/state/TaskManagerWideRocksDbMemorySharingITCase.java b/flink-tests/src/test/java/org/apache/flink/test/state/TaskManagerWideRocksDbMemorySharingITCase.java
new file mode 100644
index 00000000000..9f10d02e37d
--- /dev/null
+++ b/flink-tests/src/test/java/org/apache/flink/test/state/TaskManagerWideRocksDbMemorySharingITCase.java
@@ -0,0 +1,249 @@
+/*
+ * 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.test.state;
+
+import org.apache.flink.api.common.JobID;
+import org.apache.flink.api.common.functions.RichMapFunction;
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.api.common.time.Deadline;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.MemorySize;
+import org.apache.flink.configuration.StateBackendOptions;
+import org.apache.flink.contrib.streaming.state.RocksDBNativeMetricOptions;
+import org.apache.flink.contrib.streaming.state.RocksDBOptions;
+import org.apache.flink.metrics.Gauge;
+import org.apache.flink.runtime.jobgraph.JobGraph;
+import org.apache.flink.runtime.testutils.InMemoryReporter;
+import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
+import org.apache.flink.streaming.api.CheckpointingMode;
+import org.apache.flink.streaming.api.datastream.DataStreamSource;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.sink.DiscardingSink;
+import org.apache.flink.test.util.MiniClusterWithClientResource;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.math.BigInteger;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.DoubleSummaryStatistics;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.apache.flink.api.common.restartstrategy.RestartStrategies.noRestart;
+import static org.apache.flink.contrib.streaming.state.RocksDBMemoryControllerUtils.calculateActualCacheCapacity;
+import static org.apache.flink.runtime.testutils.CommonTestUtils.waitForAllTaskRunning;
+import static org.apache.flink.util.Preconditions.checkState;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Tests that {@link RocksDBOptions#FIX_PER_TM_MEMORY_SIZE} works as expected, i.e. make RocksDB use
+ * the same BlockCache and WriteBufferManager objects. It does so using RocksDB metrics.
+ */
+public class TaskManagerWideRocksDbMemorySharingITCase {
+ private static final int PARALLELISM = 4;
+ private static final int NUMBER_OF_JOBS = 5;
+ private static final int NUMBER_OF_TASKS = NUMBER_OF_JOBS * PARALLELISM;
+
+ private static final MemorySize SHARED_MEMORY = MemorySize.ofMebiBytes(NUMBER_OF_TASKS * 25);
+ private static final double WRITE_BUFFER_RATIO = 0.5;
+ private static final double EXPECTED_BLOCK_CACHE_SIZE =
+ calculateActualCacheCapacity(SHARED_MEMORY.getBytes(), WRITE_BUFFER_RATIO);
+ // try to check that the memory usage is limited
+ // however, there is no hard limit actually
+ // because of https://issues.apache.org/jira/browse/FLINK-15532
+ private static final double EFFECTIVE_LIMIT = EXPECTED_BLOCK_CACHE_SIZE * 1.5;
+
+ private InMemoryReporter metricsReporter;
+ private MiniClusterWithClientResource cluster;
+
+ @Before
+ public void init() throws Exception {
+ metricsReporter = InMemoryReporter.create();
+ cluster =
+ new MiniClusterWithClientResource(
+ new MiniClusterResourceConfiguration.Builder()
+ .setConfiguration(getConfiguration(metricsReporter))
+ .setNumberTaskManagers(1)
+ .setNumberSlotsPerTaskManager(NUMBER_OF_TASKS)
+ .build());
+ cluster.before();
+ }
+
+ @After
+ public void destroy() {
+ cluster.after();
+ metricsReporter.close();
+ }
+
+ @Test
+ public void testBlockCache() throws Exception {
+ List<JobID> jobIDs = new ArrayList<>(NUMBER_OF_JOBS);
+ try {
+ // launch jobs
+ for (int i = 0; i < NUMBER_OF_JOBS; i++) {
+ jobIDs.add(cluster.getRestClusterClient().submitJob(dag()).get());
+ }
+
+ // wait for init
+ Deadline initDeadline = Deadline.fromNow(Duration.ofMinutes(1));
+ for (JobID jid : jobIDs) {
+ waitForAllTaskRunning(cluster.getMiniCluster(), jid, false);
+ waitForAllMetricsReported(jid, initDeadline);
+ }
+
+ // check declared capacity
+ collectGaugeValues(jobIDs, "rocksdb.block-cache-capacity")
+ .forEach(
+ size ->
+ assertEquals(
+ "Unexpected rocksdb block cache capacity",
+ EXPECTED_BLOCK_CACHE_SIZE,
+ size,
+ 0));
+
+ // do some work and check the actual usage of memory
+ for (int i = 0; i < 10; i++) {
+ Thread.sleep(50L);
+ DoubleSummaryStatistics stats =
+ collectGaugeValues(jobIDs, "rocksdb.block-cache-usage")
+ .collect(Collectors.summarizingDouble((Double::doubleValue)));
+ assertEquals(
+ String.format(
+ "Block cache usage reported by different tasks varies too much: %s\n"
+ + "That likely mean that they use different cache objects",
+ stats),
+ stats.getMax(),
+ stats.getMin(),
+ // some deviation is possible because:
+ // 1. records are being processed in parallel with requesting metrics
+ // 2. reporting metrics is not synchronized
+ 500_000d);
+ assertTrue(
+ String.format(
+ "total block cache usage is too high: %s (limit: %s, effective limit: %s)",
+ stats, EXPECTED_BLOCK_CACHE_SIZE, EFFECTIVE_LIMIT),
+ stats.getMax() <= EFFECTIVE_LIMIT);
+ }
+
+ } finally {
+ for (JobID jobID : jobIDs) {
+ cluster.getRestClusterClient().cancel(jobID).get();
+ }
+ }
+ }
+
+ private void waitForAllMetricsReported(JobID jid, Deadline deadline)
+ throws InterruptedException {
+ List<Double> gaugeValues = collectGaugeValues(jid, "rocksdb.block-cache-capacity");
+ while (deadline.hasTimeLeft() && isEmptyOrHasZeroes(gaugeValues)) {
+ Thread.sleep(100);
+ gaugeValues = collectGaugeValues(jid, "rocksdb.block-cache-capacity");
+ }
+ if (isEmptyOrHasZeroes(gaugeValues)) {
+ Assert.fail(
+ String.format(
+ "some tasks are still reporting zero cache capacity: %s", gaugeValues));
+ }
+ }
+
+ private boolean isEmptyOrHasZeroes(List<Double> gaugeValues) {
+ return gaugeValues.isEmpty() || gaugeValues.stream().anyMatch(x -> x == 0);
+ }
+
+ // collect at least one metric according to the given pattern
+ // then convert it to double and return
+ private List<Double> collectGaugeValues(JobID jobID, String metricPattern) {
+ //noinspection unchecked
+ List<Double> list =
+ metricsReporter.findJobMetricGroups(jobID, metricPattern).stream()
+ .map(triple -> ((Gauge<BigInteger>) triple.f2).getValue().doubleValue())
+ .collect(Collectors.toList());
+ checkState(!list.isEmpty());
+ return list;
+ }
+
+ private Stream<Double> collectGaugeValues(List<JobID> jobIDs, String metricPattern) {
+ return jobIDs.stream().flatMap(jobID -> collectGaugeValues(jobID, metricPattern).stream());
+ }
+
+ private JobGraph dag() {
+ Configuration configuration = new Configuration();
+ StreamExecutionEnvironment env =
+ StreamExecutionEnvironment.getExecutionEnvironment(configuration);
+ env.setParallelism(PARALLELISM);
+
+ // don't flush memtables by checkpoints
+ env.enableCheckpointing(24 * 60 * 60 * 1000, CheckpointingMode.EXACTLY_ONCE);
+ env.setRestartStrategy(noRestart());
+
+ DataStreamSource<Long> src = env.fromSequence(Long.MIN_VALUE, Long.MAX_VALUE);
+ src.keyBy(number -> number)
+ .map(
+ new RichMapFunction<Long, Long>() {
+ private ListState<byte[]> state;
+ private int payloadSize;
+
+ @Override
+ public void open(Configuration parameters) throws Exception {
+ super.open(parameters);
+ this.state =
+ getRuntimeContext()
+ .getListState(
+ new ListStateDescriptor<>(
+ "state", byte[].class));
+ // let each task to grow its state at a different speed
+ // to increase the probability of reporting different memory usages
+ // among different tasks
+ this.payloadSize = 4 + new Random().nextInt(7);
+ }
+
+ @Override
+ public Long map(Long value) throws Exception {
+ state.add(new byte[payloadSize]);
+ Thread.sleep(1L);
+ return value;
+ }
+ })
+ .addSink(new DiscardingSink<>());
+ return env.getStreamGraph().getJobGraph();
+ }
+
+ private static Configuration getConfiguration(InMemoryReporter metricsReporter) {
+ Configuration configuration = new Configuration();
+
+ configuration.set(RocksDBOptions.FIX_PER_TM_MEMORY_SIZE, SHARED_MEMORY);
+
+ configuration.set(StateBackendOptions.STATE_BACKEND, "rocksdb");
+ configuration.set(RocksDBOptions.USE_MANAGED_MEMORY, false);
+ configuration.setDouble(RocksDBOptions.WRITE_BUFFER_RATIO, WRITE_BUFFER_RATIO);
+
+ metricsReporter.addToConfiguration(configuration);
+ configuration.set(RocksDBNativeMetricOptions.BLOCK_CACHE_CAPACITY, true);
+ configuration.set(RocksDBNativeMetricOptions.BLOCK_CACHE_USAGE, true);
+
+ return configuration;
+ }
+}