You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by vp...@apache.org on 2023/03/09 14:49:39 UTC
[ignite-3] branch main updated: IGNITE-18741 Implement PD-side logic for an initialization phase of group lease management (#1726)
This is an automated email from the ASF dual-hosted git repository.
vpyatkov pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/ignite-3.git
The following commit(s) were added to refs/heads/main by this push:
new 62e6788a1e IGNITE-18741 Implement PD-side logic for an initialization phase of group lease management (#1726)
62e6788a1e is described below
commit 62e6788a1e6ea089ce1a4d3efa1f1463af8109da
Author: Vladislav Pyatkov <vl...@gmail.com>
AuthorDate: Thu Mar 9 18:46:57 2023 +0400
IGNITE-18741 Implement PD-side logic for an initialization phase of group lease management (#1726)
---
.../internal/cluster/management/ClusterState.java | 4 +-
.../metastorage/impl/MetaStorageManagerImpl.java | 10 +-
.../metastorage/server/KeyValueStorage.java | 2 +-
modules/placement-driver/build.gradle | 13 +
.../internal/placementdriver/ActiveActorTest.java | 25 +-
.../PlacementDriverManagerTest.java | 370 +++++++++++++++++++++
.../placementdriver/AssignmentsTracker.java | 226 +++++++++++++
.../ignite/internal/placementdriver/Lease.java | 81 +++++
.../internal/placementdriver/LeaseTracker.java | 150 +++++++++
.../internal/placementdriver/LeaseUpdater.java | 269 +++++++++++++++
.../placementdriver/PlacementDriverManager.java | 77 ++++-
.../internal/placementdriver/TopologyTracker.java | 149 +++++++++
.../org/apache/ignite/internal/app/IgniteImpl.java | 37 ++-
.../internal/table/distributed/TableManager.java | 10 +-
.../distributed/replicator/TablePartitionId.java | 12 +
15 files changed, 1387 insertions(+), 48 deletions(-)
diff --git a/modules/cluster-management/src/main/java/org/apache/ignite/internal/cluster/management/ClusterState.java b/modules/cluster-management/src/main/java/org/apache/ignite/internal/cluster/management/ClusterState.java
index a46b63e537..1003a64313 100644
--- a/modules/cluster-management/src/main/java/org/apache/ignite/internal/cluster/management/ClusterState.java
+++ b/modules/cluster-management/src/main/java/org/apache/ignite/internal/cluster/management/ClusterState.java
@@ -28,7 +28,7 @@ import org.apache.ignite.network.annotations.Transferable;
/**
* Represents the state of the CMG. It contains:
* <ol>
- * <li>Names of the nodes that host the Meta Storage.</li>
+ * <li>Names of the nodes that host Meta storage.</li>
* <li>Names of the nodes that host the CMG.</li>
* <li>Ignite version of the nodes that comprise the cluster.</li>
* <li>Cluster tag, unique for a particular Ignite cluster.</li>
@@ -42,7 +42,7 @@ public interface ClusterState extends NetworkMessage, Serializable {
Set<String> cmgNodes();
/**
- * Returns node names that host the Meta Storage.
+ * Returns node names that host Meta storage.
*/
Set<String> metaStorageNodes();
diff --git a/modules/metastorage/src/main/java/org/apache/ignite/internal/metastorage/impl/MetaStorageManagerImpl.java b/modules/metastorage/src/main/java/org/apache/ignite/internal/metastorage/impl/MetaStorageManagerImpl.java
index 7a0921e64b..897444d14c 100644
--- a/modules/metastorage/src/main/java/org/apache/ignite/internal/metastorage/impl/MetaStorageManagerImpl.java
+++ b/modules/metastorage/src/main/java/org/apache/ignite/internal/metastorage/impl/MetaStorageManagerImpl.java
@@ -67,8 +67,8 @@ import org.jetbrains.annotations.TestOnly;
* <p>Responsible for:
* <ul>
* <li>Handling cluster init message.</li>
- * <li>Managing meta storage lifecycle including instantiation meta storage raft group.</li>
- * <li>Providing corresponding meta storage service proxy interface</li>
+ * <li>Managing Meta storage lifecycle including instantiation Meta storage raft group.</li>
+ * <li>Providing corresponding Meta storage service proxy interface</li>
* </ul>
*/
public class MetaStorageManagerImpl implements MetaStorageManager {
@@ -94,7 +94,7 @@ public class MetaStorageManagerImpl implements MetaStorageManager {
/** Meta storage service. */
private final CompletableFuture<MetaStorageServiceImpl> metaStorageSvcFut = new CompletableFuture<>();
- /** Actual storage for the Metastorage. */
+ /** Actual storage for Meta storage. */
private final KeyValueStorage storage;
/** Busy lock to stop synchronously. */
@@ -104,7 +104,7 @@ public class MetaStorageManagerImpl implements MetaStorageManager {
private final AtomicBoolean isStopped = new AtomicBoolean();
/**
- * Applied revision of the Meta Storage, that is, the most recent revision that has been processed on this node.
+ * Applied revision of Meta storage, that is, the most recent revision that has been processed on this node.
*/
private volatile long appliedRevision;
@@ -571,7 +571,7 @@ public class MetaStorageManagerImpl implements MetaStorageManager {
}
/**
- * Compacts meta storage (removes all tombstone entries and old entries except of entries with latest revision).
+ * Compacts Meta storage (removes all tombstone entries and old entries except of entries with latest revision).
*
* @see MetaStorageService#compact()
*/
diff --git a/modules/metastorage/src/main/java/org/apache/ignite/internal/metastorage/server/KeyValueStorage.java b/modules/metastorage/src/main/java/org/apache/ignite/internal/metastorage/server/KeyValueStorage.java
index 89fdfda657..a1f3c8511b 100644
--- a/modules/metastorage/src/main/java/org/apache/ignite/internal/metastorage/server/KeyValueStorage.java
+++ b/modules/metastorage/src/main/java/org/apache/ignite/internal/metastorage/server/KeyValueStorage.java
@@ -268,7 +268,7 @@ public interface KeyValueStorage extends ManuallyCloseable {
/**
* Compacts storage (removes tombstones).
- * TODO: IGNITE-16444 Correct compaction for Metastorage.
+ * TODO: IGNITE-16444 Correct compaction for Meta storage.
*/
void compact();
diff --git a/modules/placement-driver/build.gradle b/modules/placement-driver/build.gradle
index d415e9dd93..d87beac7b6 100644
--- a/modules/placement-driver/build.gradle
+++ b/modules/placement-driver/build.gradle
@@ -28,18 +28,31 @@ dependencies {
implementation project(':ignite-raft-api')
implementation project(':ignite-raft')
implementation project(':ignite-cluster-management')
+ implementation project(':ignite-schema')
+ implementation project(':ignite-table')
+ implementation project(':ignite-affinity')
+ implementation project(':ignite-vault')
+ implementation project(':ignite-rocksdb-common:')
implementation libs.jetbrains.annotations
testFixturesImplementation project(':ignite-core')
+
integrationTestImplementation project(':ignite-network')
integrationTestImplementation project(':ignite-raft')
integrationTestImplementation project(':ignite-raft-api')
integrationTestImplementation project(':ignite-cluster-management')
+ integrationTestImplementation project(':ignite-metastorage')
+ integrationTestImplementation project(':ignite-vault')
+ integrationTestImplementation project(':ignite-schema')
+ integrationTestImplementation project(':ignite-table')
+ integrationTestImplementation project(':ignite-affinity')
integrationTestImplementation(testFixtures(project(':ignite-core')))
integrationTestImplementation(testFixtures(project(':ignite-network')))
integrationTestImplementation(testFixtures(project(':ignite-configuration')))
+ integrationTestImplementation(testFixtures(project(':ignite-vault')))
+ integrationTestImplementation(testFixtures(project(':ignite-metastorage')))
}
description = 'ignite-placement-driver'
diff --git a/modules/placement-driver/src/integrationTest/java/org/apache/ignite/internal/placementdriver/ActiveActorTest.java b/modules/placement-driver/src/integrationTest/java/org/apache/ignite/internal/placementdriver/ActiveActorTest.java
index 4eb18b7e85..03feef5b70 100644
--- a/modules/placement-driver/src/integrationTest/java/org/apache/ignite/internal/placementdriver/ActiveActorTest.java
+++ b/modules/placement-driver/src/integrationTest/java/org/apache/ignite/internal/placementdriver/ActiveActorTest.java
@@ -25,16 +25,35 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.apache.ignite.internal.configuration.testframework.InjectConfiguration;
+import org.apache.ignite.internal.hlc.HybridClockImpl;
+import org.apache.ignite.internal.metastorage.MetaStorageManager;
import org.apache.ignite.internal.raft.client.TopologyAwareRaftGroupServiceTest;
+import org.apache.ignite.internal.schema.configuration.TablesConfiguration;
+import org.apache.ignite.internal.vault.VaultManager;
+import org.apache.ignite.internal.vault.inmemory.InMemoryVaultService;
import org.apache.ignite.network.ClusterService;
import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
/**
* Placement driver active actor test.
*/
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
public class ActiveActorTest extends TopologyAwareRaftGroupServiceTest {
private Map<String, PlacementDriverManager> placementDriverManagers = new HashMap<>();
+ @Mock
+ MetaStorageManager msm;
+
+ @InjectConfiguration()
+ private TablesConfiguration tblsCfg;
+
@AfterEach
@Override
protected void afterTest() throws Exception {
@@ -51,12 +70,16 @@ public class ActiveActorTest extends TopologyAwareRaftGroupServiceTest {
@Override
protected void afterNodeStart(String nodeName, ClusterService clusterService, Set<String> placementDriverNodesNames) {
PlacementDriverManager placementDriverManager = new PlacementDriverManager(
+ msm,
+ new VaultManager(new InMemoryVaultService()),
TestReplicationGroup.GROUP_ID,
clusterService,
raftConfiguration,
() -> completedFuture(placementDriverNodesNames),
new LogicalTopologyServiceTestImpl(clusterService),
- executor
+ executor,
+ tblsCfg,
+ new HybridClockImpl()
);
placementDriverManager.start();
diff --git a/modules/placement-driver/src/integrationTest/java/org/apache/ignite/internal/placementdriver/PlacementDriverManagerTest.java b/modules/placement-driver/src/integrationTest/java/org/apache/ignite/internal/placementdriver/PlacementDriverManagerTest.java
new file mode 100644
index 0000000000..245fd2b56d
--- /dev/null
+++ b/modules/placement-driver/src/integrationTest/java/org/apache/ignite/internal/placementdriver/PlacementDriverManagerTest.java
@@ -0,0 +1,370 @@
+/*
+ * 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.ignite.internal.placementdriver;
+
+import static java.util.concurrent.CompletableFuture.completedFuture;
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.affinity.AffinityUtils.calculateAssignmentForPartition;
+import static org.apache.ignite.internal.placementdriver.PlacementDriverManager.PLACEMENTDRIVER_PREFIX;
+import static org.apache.ignite.internal.raft.Loza.CLIENT_POOL_NAME;
+import static org.apache.ignite.internal.raft.Loza.CLIENT_POOL_SIZE;
+import static org.apache.ignite.internal.testframework.IgniteTestUtils.testNodeName;
+import static org.apache.ignite.internal.testframework.IgniteTestUtils.waitForCondition;
+import static org.apache.ignite.internal.utils.RebalanceUtil.STABLE_ASSIGNMENTS_PREFIX;
+import static org.apache.ignite.lang.ByteArray.fromString;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import org.apache.ignite.internal.affinity.AffinityUtils;
+import org.apache.ignite.internal.affinity.Assignment;
+import org.apache.ignite.internal.cluster.management.ClusterManagementGroupManager;
+import org.apache.ignite.internal.cluster.management.topology.api.LogicalTopologyEventListener;
+import org.apache.ignite.internal.cluster.management.topology.api.LogicalTopologyService;
+import org.apache.ignite.internal.cluster.management.topology.api.LogicalTopologySnapshot;
+import org.apache.ignite.internal.configuration.testframework.ConfigurationExtension;
+import org.apache.ignite.internal.configuration.testframework.InjectConfiguration;
+import org.apache.ignite.internal.hlc.HybridClock;
+import org.apache.ignite.internal.hlc.HybridClockImpl;
+import org.apache.ignite.internal.metastorage.impl.MetaStorageManagerImpl;
+import org.apache.ignite.internal.metastorage.server.SimpleInMemoryKeyValueStorage;
+import org.apache.ignite.internal.metastorage.server.raft.MetastorageGroupId;
+import org.apache.ignite.internal.raft.Loza;
+import org.apache.ignite.internal.raft.Peer;
+import org.apache.ignite.internal.raft.PeersAndLearners;
+import org.apache.ignite.internal.raft.configuration.RaftConfiguration;
+import org.apache.ignite.internal.schema.configuration.ExtendedTableChange;
+import org.apache.ignite.internal.schema.configuration.TablesConfiguration;
+import org.apache.ignite.internal.table.distributed.replicator.TablePartitionId;
+import org.apache.ignite.internal.testframework.IgniteAbstractTest;
+import org.apache.ignite.internal.thread.NamedThreadFactory;
+import org.apache.ignite.internal.util.ByteUtils;
+import org.apache.ignite.internal.vault.VaultManager;
+import org.apache.ignite.internal.vault.persistence.PersistentVaultService;
+import org.apache.ignite.lang.NodeStoppingException;
+import org.apache.ignite.network.ClusterNode;
+import org.apache.ignite.network.ClusterService;
+import org.apache.ignite.network.NetworkAddress;
+import org.apache.ignite.network.StaticNodeFinder;
+import org.apache.ignite.utils.ClusterServiceTestUtils;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInfo;
+import org.junit.jupiter.api.extension.ExtendWith;
+
+/**
+ * There are tests for Placement driver manager.
+ */
+@ExtendWith(ConfigurationExtension.class)
+public class PlacementDriverManagerTest extends IgniteAbstractTest {
+ public static final int PORT = 1234;
+ private String nodeName;
+
+ HybridClock clock = new HybridClockImpl();
+ private VaultManager vaultManager;
+
+ private ClusterService clusterService;
+
+ private Loza raftManager;
+
+ @InjectConfiguration
+ private RaftConfiguration raftConfiguration;
+
+ @InjectConfiguration
+ private TablesConfiguration tblsCfg;
+
+ private MetaStorageManagerImpl metaStorageManager;
+
+ private PlacementDriverManager placementDriverManager;
+
+ private ScheduledExecutorService raftExecutorService;
+
+ private TestInfo testInfo;
+
+ @BeforeEach
+ public void beforeTest(TestInfo testInfo) throws NodeStoppingException {
+ this.nodeName = testNodeName(testInfo, PORT);
+ this.testInfo = testInfo;
+
+ startPlacementDriverManager();
+ }
+
+ private void startPlacementDriverManager() throws NodeStoppingException {
+ vaultManager = new VaultManager(new PersistentVaultService(workDir.resolve("vault")));
+
+ var nodeFinder = new StaticNodeFinder(Collections.singletonList(new NetworkAddress("localhost", PORT)));
+
+ clusterService = ClusterServiceTestUtils.clusterService(testInfo, PORT, nodeFinder);
+
+ ClusterManagementGroupManager cmgManager = mock(ClusterManagementGroupManager.class);
+
+ when(cmgManager.metaStorageNodes())
+ .thenReturn(completedFuture(Set.of(clusterService.localConfiguration().getName())));
+
+ raftManager = new Loza(clusterService, raftConfiguration, workDir.resolve("loza"), new HybridClockImpl());
+
+ var storage = new SimpleInMemoryKeyValueStorage(nodeName);
+
+ metaStorageManager = new MetaStorageManagerImpl(
+ vaultManager,
+ clusterService,
+ cmgManager,
+ mock(LogicalTopologyService.class),
+ raftManager,
+ storage
+ );
+
+ raftExecutorService = new ScheduledThreadPoolExecutor(CLIENT_POOL_SIZE,
+ new NamedThreadFactory(NamedThreadFactory.threadPrefix(clusterService.localConfiguration().getName(),
+ CLIENT_POOL_NAME), log
+ ));
+
+ placementDriverManager = new PlacementDriverManager(
+ metaStorageManager,
+ vaultManager,
+ MetastorageGroupId.INSTANCE,
+ clusterService,
+ raftConfiguration,
+ () -> completedFuture(peersAndLearners(
+ new HashMap<>(Map.of(new NetworkAddress("localhost", PORT), clusterService)),
+ addr -> true,
+ 1)
+ .peers().stream().map(Peer::consistentId).collect(toSet())),
+ new LogicalTopologyServiceTestImpl(clusterService),
+ raftExecutorService,
+ tblsCfg,
+ clock);
+
+ vaultManager.start();
+ clusterService.start();
+ raftManager.start();
+ metaStorageManager.start();
+ placementDriverManager.start();
+
+ metaStorageManager.deployWatches();
+ }
+
+ @AfterEach
+ public void afterEach() throws Exception {
+ stopPlacementDriverManager();
+ }
+
+ private void stopPlacementDriverManager() throws Exception {
+ placementDriverManager.beforeNodeStop();
+ metaStorageManager.beforeNodeStop();
+ raftManager.beforeNodeStop();
+ clusterService.beforeNodeStop();
+ vaultManager.beforeNodeStop();
+
+ placementDriverManager.stop();
+ metaStorageManager.stop();
+ raftManager.stop();
+ clusterService.stop();
+ vaultManager.stop();
+ raftExecutorService.shutdown();
+ }
+
+ private static PeersAndLearners peersAndLearners(
+ HashMap<NetworkAddress, ClusterService> clusterServices,
+ Predicate<NetworkAddress> isServerAddress,
+ int nodes
+ ) {
+ return PeersAndLearners.fromConsistentIds(
+ getNetworkAddresses(nodes).stream().filter(isServerAddress)
+ .map(netAddr -> clusterServices.get(netAddr).topologyService().localMember().name()).collect(
+ toSet()));
+ }
+
+ /**
+ * Generates a node address for each node.
+ *
+ * @param nodes Node count.
+ * @return List on network addresses.
+ */
+ private static List<NetworkAddress> getNetworkAddresses(int nodes) {
+ List<NetworkAddress> addresses = IntStream.range(PORT, PORT + nodes)
+ .mapToObj(port -> new NetworkAddress("localhost", port))
+ .collect(Collectors.toList());
+ return addresses;
+ }
+
+ @Test
+ public void testLeaseCreate() throws Exception {
+ TablePartitionId grpPart0 = createTableAssignment();
+
+ checkLeaseCreated(grpPart0);
+ }
+
+ @Test
+ public void testLeaseRenew() throws Exception {
+ TablePartitionId grpPart0 = createTableAssignment();
+
+ checkLeaseCreated(grpPart0);
+
+ var leaseFut = metaStorageManager.get(fromString(PLACEMENTDRIVER_PREFIX + grpPart0));
+
+ Lease lease = ByteUtils.fromBytes(leaseFut.join().value());
+
+ assertNotNull(lease);
+
+ assertTrue(waitForCondition(() -> {
+ var fut = metaStorageManager.get(fromString(PLACEMENTDRIVER_PREFIX + grpPart0));
+
+ Lease leaseRenew = ByteUtils.fromBytes(fut.join().value());
+
+ return lease.getLeaseExpirationTime().compareTo(leaseRenew.getLeaseExpirationTime()) < 0;
+
+ }, 10_000));
+ }
+
+ @Test
+ public void testLeaseholderUpdate() throws Exception {
+ TablePartitionId grpPart0 = createTableAssignment();
+
+ checkLeaseCreated(grpPart0);
+
+ Set<Assignment> assignments = Set.of();
+
+ metaStorageManager.put(fromString(STABLE_ASSIGNMENTS_PREFIX + grpPart0), ByteUtils.toBytes(assignments));
+
+ assertTrue(waitForCondition(() -> {
+ var fut = metaStorageManager.get(fromString(PLACEMENTDRIVER_PREFIX + grpPart0));
+
+ Lease lease = ByteUtils.fromBytes(fut.join().value());
+
+ return lease.getLeaseExpirationTime().compareTo(clock.now()) < 0;
+
+ }, 10_000));
+
+ assignments = calculateAssignmentForPartition(Collections.singleton(nodeName), 1, 1);
+
+ metaStorageManager.put(fromString(STABLE_ASSIGNMENTS_PREFIX + grpPart0), ByteUtils.toBytes(assignments));
+
+ assertTrue(waitForCondition(() -> {
+ var fut = metaStorageManager.get(fromString(PLACEMENTDRIVER_PREFIX + grpPart0));
+
+ Lease lease = ByteUtils.fromBytes(fut.join().value());
+
+ return lease.getLeaseExpirationTime().compareTo(clock.now()) > 0;
+
+ }, 10_000));
+ }
+
+ @Test
+ public void testLeaseRestore() throws Exception {
+ TablePartitionId grpPart0 = createTableAssignment();
+
+ checkLeaseCreated(grpPart0);
+
+ stopPlacementDriverManager();
+ startPlacementDriverManager();
+
+ checkLeaseCreated(grpPart0);
+ }
+
+ /**
+ * Checks if a group lease is created during the timeout.
+ *
+ * @param grpPartId Replication group id.
+ * @throws InterruptedException If the waiting is interrupted.
+ */
+ private void checkLeaseCreated(TablePartitionId grpPartId) throws InterruptedException {
+ assertTrue(waitForCondition(() -> {
+ var leaseFut = metaStorageManager.get(fromString(PLACEMENTDRIVER_PREFIX + grpPartId));
+
+ var leaseEntry = leaseFut.join();
+
+ return leaseEntry != null && !leaseEntry.empty();
+ }, 10_000));
+ }
+
+ /**
+ * Creates an assignment for the fake table.
+ *
+ * @return Replication group id.
+ * @throws Exception If failed.
+ */
+ private TablePartitionId createTableAssignment() throws Exception {
+ AtomicReference<UUID> tblIdRef = new AtomicReference<>();
+
+ List<Set<Assignment>> assignments = AffinityUtils.calculateAssignments(Collections.singleton(nodeName), 1, 1);
+
+ tblsCfg.tables().change(tableViewTableChangeNamedListChange -> {
+ tableViewTableChangeNamedListChange.create("test-table", tableChange -> {
+ var extConfCh = ((ExtendedTableChange) tableChange);
+ extConfCh.changePartitions(1);
+ extConfCh.changeReplicas(1);
+
+ tblIdRef.set(extConfCh.id());
+
+ extConfCh.changeAssignments(ByteUtils.toBytes(assignments));
+ });
+ }).get();
+
+ var grpPart0 = new TablePartitionId(tblIdRef.get(), 0);
+
+ log.info("Fake table created [id={}, repGrp={}]", tblIdRef.get(), grpPart0);
+ return grpPart0;
+ }
+
+ /**
+ * Test implementation of {@link LogicalTopologyService}.
+ */
+ protected static class LogicalTopologyServiceTestImpl implements LogicalTopologyService {
+ private final ClusterService clusterService;
+
+ public LogicalTopologyServiceTestImpl(ClusterService clusterService) {
+ this.clusterService = clusterService;
+ }
+
+ @Override
+ public void addEventListener(LogicalTopologyEventListener listener) {
+
+ }
+
+ @Override
+ public void removeEventListener(LogicalTopologyEventListener listener) {
+
+ }
+
+ @Override
+ public CompletableFuture<LogicalTopologySnapshot> logicalTopologyOnLeader() {
+ return completedFuture(new LogicalTopologySnapshot(1, clusterService.topologyService().allMembers()));
+ }
+
+ @Override
+ public CompletableFuture<Set<ClusterNode>> validatedNodesOnLeader() {
+ return completedFuture(Set.copyOf(clusterService.topologyService().allMembers()));
+ }
+ }
+}
diff --git a/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/AssignmentsTracker.java b/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/AssignmentsTracker.java
new file mode 100644
index 0000000000..72c8aaa867
--- /dev/null
+++ b/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/AssignmentsTracker.java
@@ -0,0 +1,226 @@
+/*
+ * 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.ignite.internal.placementdriver;
+
+import static java.util.concurrent.CompletableFuture.completedFuture;
+import static org.apache.ignite.internal.utils.RebalanceUtil.STABLE_ASSIGNMENTS_PREFIX;
+
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.ignite.configuration.notifications.ConfigurationListener;
+import org.apache.ignite.configuration.notifications.ConfigurationNotificationEvent;
+import org.apache.ignite.internal.affinity.Assignment;
+import org.apache.ignite.internal.logger.IgniteLogger;
+import org.apache.ignite.internal.logger.Loggers;
+import org.apache.ignite.internal.metastorage.EntryEvent;
+import org.apache.ignite.internal.metastorage.MetaStorageManager;
+import org.apache.ignite.internal.metastorage.WatchEvent;
+import org.apache.ignite.internal.metastorage.WatchListener;
+import org.apache.ignite.internal.replicator.ReplicationGroupId;
+import org.apache.ignite.internal.schema.configuration.ExtendedTableConfiguration;
+import org.apache.ignite.internal.schema.configuration.TablesConfiguration;
+import org.apache.ignite.internal.table.distributed.replicator.TablePartitionId;
+import org.apache.ignite.internal.util.ByteUtils;
+import org.apache.ignite.internal.util.CollectionUtils;
+import org.apache.ignite.internal.util.Cursor;
+import org.apache.ignite.internal.vault.VaultEntry;
+import org.apache.ignite.internal.vault.VaultManager;
+import org.apache.ignite.lang.ByteArray;
+
+/**
+ * The class tracks assignment of all replication groups.
+ */
+public class AssignmentsTracker {
+ /** Ignite logger. */
+ private static final IgniteLogger LOG = Loggers.forClass(AssignmentsTracker.class);
+
+ /** Vault manager. */
+ private final VaultManager vaultManager;
+
+ /** Meta storage manager. */
+ private final MetaStorageManager msManager;
+
+ /** Tables configuration. */
+ private final TablesConfiguration tablesCfg;
+
+ /** Map replication group id to assignment nodes. */
+ private Map<ReplicationGroupId, Set<Assignment>> groupAssignments;
+
+ /** Assignment configuration listener. */
+ private final AssignmentsCfgListener assignmentsCfgListener;
+
+ /** Assignment Meta storage watch listener. */
+ private final AssignmentsListener assignmentsListener;
+
+ /**
+ * The constructor.
+ *
+ * @param vaultManager Vault manager.
+ * @param msManager Metastorage manager.
+ * @param tablesCfg Table configuration.
+ */
+ public AssignmentsTracker(VaultManager vaultManager, MetaStorageManager msManager, TablesConfiguration tablesCfg) {
+ this.vaultManager = vaultManager;
+ this.msManager = msManager;
+ this.tablesCfg = tablesCfg;
+
+ this.groupAssignments = new ConcurrentHashMap<>();
+ this.assignmentsCfgListener = new AssignmentsCfgListener();
+ this.assignmentsListener = new AssignmentsListener();
+ }
+
+ /**
+ * Restores assignments form Vault and subscribers on further updates.
+ */
+ public void startTrack() {
+ ((ExtendedTableConfiguration) tablesCfg.tables().any()).assignments().listen(assignmentsCfgListener);
+ msManager.registerPrefixWatch(ByteArray.fromString(STABLE_ASSIGNMENTS_PREFIX), assignmentsListener);
+
+ try (Cursor<VaultEntry> cursor = vaultManager.range(
+ ByteArray.fromString(STABLE_ASSIGNMENTS_PREFIX),
+ ByteArray.fromString(incrementLastChar(STABLE_ASSIGNMENTS_PREFIX))
+ )) {
+ for (VaultEntry entry : cursor) {
+ String key = entry.key().toString();
+
+ key = key.replace(STABLE_ASSIGNMENTS_PREFIX, "");
+
+ TablePartitionId grpId = TablePartitionId.fromString(key);
+
+ Set<Assignment> assignments = ByteUtils.fromBytes(entry.value());
+
+ groupAssignments.put(grpId, assignments);
+ }
+ }
+
+ LOG.info("Assignment cache initialized for placement driver [groupAssignments={}]", groupAssignments);
+ }
+
+ private static String incrementLastChar(String str) {
+ char lastChar = str.charAt(str.length() - 1);
+
+ return str.substring(0, str.length() - 1) + (char) (lastChar + 1);
+ }
+
+ /**
+ * Stops the tracker.
+ */
+ public void stopTrack() {
+ msManager.unregisterWatch(assignmentsListener);
+ ((ExtendedTableConfiguration) tablesCfg.tables().any()).assignments().stopListen(assignmentsCfgListener);
+ }
+
+ /**
+ * Gets assignments.
+ *
+ * @return Map replication group id to its assignment.
+ */
+ public Map<ReplicationGroupId, Set<Assignment>> assignments() {
+ return groupAssignments;
+ }
+
+ /**
+ * Configuration assignments listener.
+ */
+ private class AssignmentsCfgListener implements ConfigurationListener<byte[]> {
+ @Override
+ public CompletableFuture<?> onUpdate(ConfigurationNotificationEvent<byte[]> assignmentsCtx) {
+ ExtendedTableConfiguration tblCfg = assignmentsCtx.config(ExtendedTableConfiguration.class);
+
+ UUID tblId = tblCfg.id().value();
+
+ LOG.debug("Table assignments configuration update for placement driver [revision={}, tblId={}]",
+ assignmentsCtx.storageRevision(), tblId);
+
+ List<Set<Assignment>> tableAssignments =
+ assignmentsCtx.newValue() == null ? null : ByteUtils.fromBytes(assignmentsCtx.newValue());
+
+ boolean leaseRenewalRequired = false;
+
+ for (int part = 0; part < tblCfg.partitions().value(); part++) {
+ var replicationGrpId = new TablePartitionId(tblId, part);
+
+ if (tableAssignments == null) {
+ groupAssignments.remove(replicationGrpId);
+ } else {
+ Set<Assignment> prevAssignment = groupAssignments.put(replicationGrpId, tableAssignments.get(part));
+
+ if (CollectionUtils.nullOrEmpty(prevAssignment)) {
+ leaseRenewalRequired = true;
+ }
+ }
+ }
+
+ if (leaseRenewalRequired) {
+ triggerToRenewLeases();
+ }
+
+ return completedFuture(null);
+ }
+ }
+
+ /**
+ * Meta storage assignments watch.
+ */
+ private class AssignmentsListener implements WatchListener {
+ @Override
+ public void onUpdate(WatchEvent event) {
+ assert !event.entryEvent().newEntry().empty() : "New assignments are empty";
+
+ LOG.debug("Assignment update [revision={}, key={}]", event.revision(),
+ new ByteArray(event.entryEvent().newEntry().key()));
+
+ boolean leaseRenewalRequired = false;
+
+ for (EntryEvent evt : event.entryEvents()) {
+ var replicationGrpId = TablePartitionId.fromString(
+ new String(evt.newEntry().key(), StandardCharsets.UTF_8).replace(STABLE_ASSIGNMENTS_PREFIX, ""));
+
+ if (evt.newEntry().empty()) {
+ groupAssignments.remove(replicationGrpId);
+ } else {
+ Set<Assignment> prevAssignment = groupAssignments.put(replicationGrpId, ByteUtils.fromBytes(evt.newEntry().value()));
+
+ if (CollectionUtils.nullOrEmpty(prevAssignment)) {
+ leaseRenewalRequired = true;
+ }
+ }
+ }
+
+ if (leaseRenewalRequired) {
+ triggerToRenewLeases();
+ }
+ }
+
+ @Override
+ public void onError(Throwable e) {
+ }
+ }
+
+ /**
+ * Triggers to renew leases forcibly. The method wakes up the monitor of {@link LeaseUpdater}.
+ */
+ private void triggerToRenewLeases() {
+ //TODO: IGNITE-18879 Implement lease maintenance.
+ }
+}
diff --git a/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/Lease.java b/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/Lease.java
new file mode 100644
index 0000000000..e53428983b
--- /dev/null
+++ b/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/Lease.java
@@ -0,0 +1,81 @@
+/*
+ * 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.ignite.internal.placementdriver;
+
+import java.io.Serializable;
+import org.apache.ignite.internal.hlc.HybridTimestamp;
+import org.apache.ignite.network.ClusterNode;
+
+/**
+ * A lease representation in memory.
+ * The real lease is stored in Meta storage.
+ */
+public class Lease implements Serializable {
+ /** The object is used when nothing holds the lease. */
+ public static Lease EMPTY_LEASE = new Lease(null, null);
+
+ /** A node that holds a lease until {@code stopLeas}. */
+ private final ClusterNode leaseholder;
+
+ /** Timestamp to expiration the lease. */
+ private final HybridTimestamp leaseExpirationTime;
+
+ /**
+ * Default constructor.
+ */
+ public Lease() {
+ this(null, null);
+ }
+
+ /**
+ * The constructor.
+ *
+ * @param leaseholder Lease holder.
+ * @param leaseExpirationTime Lease expiration timestamp.
+ */
+ public Lease(ClusterNode leaseholder, HybridTimestamp leaseExpirationTime) {
+ this.leaseholder = leaseholder;
+ this.leaseExpirationTime = leaseExpirationTime;
+ }
+
+ /**
+ * Get a leaseholder node.
+ *
+ * @return Leaseholder or {@code null} if nothing holds the lease.
+ */
+ public ClusterNode getLeaseholder() {
+ return leaseholder;
+ }
+
+ /**
+ * Gets a lease expiration timestamp.
+ *
+ * @return Lease expiration timestamp or {@code null} if nothing holds the lease.
+ */
+ public HybridTimestamp getLeaseExpirationTime() {
+ return leaseExpirationTime;
+ }
+
+ @Override
+ public String toString() {
+ return "Lease {"
+ + "leaseholder=" + leaseholder
+ + ", leaseExpirationTime=" + leaseExpirationTime
+ + '}';
+ }
+}
diff --git a/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/LeaseTracker.java b/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/LeaseTracker.java
new file mode 100644
index 0000000000..4feb632178
--- /dev/null
+++ b/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/LeaseTracker.java
@@ -0,0 +1,150 @@
+/*
+ * 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.ignite.internal.placementdriver;
+
+import static org.apache.ignite.internal.placementdriver.PlacementDriverManager.PLACEMENTDRIVER_PREFIX;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.ignite.internal.logger.IgniteLogger;
+import org.apache.ignite.internal.logger.Loggers;
+import org.apache.ignite.internal.metastorage.Entry;
+import org.apache.ignite.internal.metastorage.EntryEvent;
+import org.apache.ignite.internal.metastorage.MetaStorageManager;
+import org.apache.ignite.internal.metastorage.WatchEvent;
+import org.apache.ignite.internal.metastorage.WatchListener;
+import org.apache.ignite.internal.replicator.ReplicationGroupId;
+import org.apache.ignite.internal.table.distributed.replicator.TablePartitionId;
+import org.apache.ignite.internal.util.ByteUtils;
+import org.apache.ignite.internal.util.Cursor;
+import org.apache.ignite.internal.vault.VaultEntry;
+import org.apache.ignite.internal.vault.VaultManager;
+import org.apache.ignite.lang.ByteArray;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Class tracks cluster leases in memory.
+ * At first, the class state recoveries from Vault, then updates on watch's listener.
+ */
+public class LeaseTracker {
+ /** Ignite logger. */
+ private static final IgniteLogger LOG = Loggers.forClass(LeaseTracker.class);
+
+ /** Vault manager. */
+ private final VaultManager vaultManager;
+
+ /** Meta storage manager. */
+ private final MetaStorageManager msManager;
+
+ /** Leases cache. */
+ private final Map<ReplicationGroupId, Lease> leases;
+
+ /** Listener to update a leases cache. */
+ private final UpdateListener updateListener = new UpdateListener();
+
+ /**
+ * The constructor.
+ *
+ * @param vaultManager Vault manager.
+ * @param msManager Meta storage manager.
+ */
+ public LeaseTracker(VaultManager vaultManager, MetaStorageManager msManager) {
+ this.vaultManager = vaultManager;
+ this.msManager = msManager;
+
+ this.leases = new ConcurrentHashMap<>();
+ }
+
+ /**
+ * Recoveries state from Vault and subscribers on further updates.
+ */
+ public void startTrack() {
+ msManager.registerPrefixWatch(ByteArray.fromString(PLACEMENTDRIVER_PREFIX), updateListener);
+
+ try (Cursor<VaultEntry> cursor = vaultManager.range(
+ ByteArray.fromString(PLACEMENTDRIVER_PREFIX),
+ ByteArray.fromString(incrementLastChar(PLACEMENTDRIVER_PREFIX))
+ )) {
+ for (VaultEntry entry : cursor) {
+ String key = entry.key().toString();
+
+ key = key.replace(PLACEMENTDRIVER_PREFIX, "");
+
+ TablePartitionId grpId = TablePartitionId.fromString(key);
+ Lease lease = ByteUtils.fromBytes(entry.value());
+
+ leases.put(grpId, lease);
+ }
+ }
+
+ LOG.info("Leases cache recovered [leases={}]", leases);
+ }
+
+ /**
+ * Stops the tracker.
+ */
+ public void stopTrack() {
+ msManager.unregisterWatch(updateListener);
+ }
+
+ /**
+ * Gets a lease for a particular group.
+ *
+ * @param grpId Replication group id.
+ * @return A lease is associated with the group.
+ */
+ public @NotNull Lease getLease(ReplicationGroupId grpId) {
+ return leases.getOrDefault(grpId, Lease.EMPTY_LEASE);
+ }
+
+ private static String incrementLastChar(String str) {
+ char lastChar = str.charAt(str.length() - 1);
+
+ return str.substring(0, str.length() - 1) + (char) (lastChar + 1);
+ }
+
+ /**
+ * Listen lease holder updates.
+ */
+ private class UpdateListener implements WatchListener {
+ @Override
+ public void onUpdate(WatchEvent event) {
+ for (EntryEvent entry : event.entryEvents()) {
+ Entry msEntry = entry.newEntry();
+
+ String key = new ByteArray(msEntry.key()).toString();
+
+ key = key.replace(PLACEMENTDRIVER_PREFIX, "");
+
+ TablePartitionId grpId = TablePartitionId.fromString(key);
+
+ if (msEntry.empty()) {
+ leases.remove(grpId);
+ } else {
+ Lease lease = ByteUtils.fromBytes(msEntry.value());
+
+ leases.put(grpId, lease);
+ }
+ }
+ }
+
+ @Override
+ public void onError(Throwable e) {
+ }
+ }
+}
diff --git a/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/LeaseUpdater.java b/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/LeaseUpdater.java
new file mode 100644
index 0000000000..fad4e9b8a8
--- /dev/null
+++ b/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/LeaseUpdater.java
@@ -0,0 +1,269 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.placementdriver;
+
+import static org.apache.ignite.internal.metastorage.dsl.Conditions.notExists;
+import static org.apache.ignite.internal.metastorage.dsl.Conditions.or;
+import static org.apache.ignite.internal.metastorage.dsl.Conditions.value;
+import static org.apache.ignite.internal.metastorage.dsl.Operations.noop;
+import static org.apache.ignite.internal.metastorage.dsl.Operations.put;
+import static org.apache.ignite.internal.placementdriver.Lease.EMPTY_LEASE;
+import static org.apache.ignite.internal.placementdriver.PlacementDriverManager.PLACEMENTDRIVER_PREFIX;
+
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.internal.affinity.Assignment;
+import org.apache.ignite.internal.cluster.management.topology.api.LogicalTopologyService;
+import org.apache.ignite.internal.hlc.HybridClock;
+import org.apache.ignite.internal.hlc.HybridTimestamp;
+import org.apache.ignite.internal.logger.IgniteLogger;
+import org.apache.ignite.internal.logger.Loggers;
+import org.apache.ignite.internal.metastorage.MetaStorageManager;
+import org.apache.ignite.internal.replicator.ReplicationGroupId;
+import org.apache.ignite.internal.schema.configuration.TablesConfiguration;
+import org.apache.ignite.internal.thread.NamedThreadFactory;
+import org.apache.ignite.internal.util.ByteUtils;
+import org.apache.ignite.internal.vault.VaultManager;
+import org.apache.ignite.lang.ByteArray;
+import org.apache.ignite.network.ClusterNode;
+
+/**
+ * A processor to manger leases. The process is started when placement driver activates and stopped when it deactivates.
+ */
+public class LeaseUpdater {
+ /** Ignite logger. */
+ private static final IgniteLogger LOG = Loggers.forClass(LeaseUpdater.class);
+
+ /**
+ * Cluster cLock skew. The constant determines the undefined inclusive interval to compares timestamp from various nodes.
+ * TODO: IGNITE-18978 Method to comparison timestamps with clock skew.
+ */
+ private static final long CLOCK_SKEW = 7L;
+
+ /** Update attempts interval in milliseconds. */
+ private static final long UPDATE_LEASE_MS = 200L;
+
+ /** Lease holding interval. */
+ private static final long LEASE_PERIOD = 10 * UPDATE_LEASE_MS;
+
+ /** Meta storage manager. */
+ private final MetaStorageManager msManager;
+
+ /** Assignments tracker. */
+ private final AssignmentsTracker assignmentsTracker;
+
+ /** Topology tracker. */
+ private final TopologyTracker topologyTracker;
+
+ /** Lease tracker. */
+ private final LeaseTracker leaseTracker;
+
+ /** Cluster clock. */
+ private final HybridClock clock;
+
+ /** Closure to update leases. */
+ private final Updater updater;
+
+ /** Dedicated thread to update leases. */
+ private volatile Thread updaterTread;
+
+ /** Node name. */
+ private String nodeName;
+
+ /**
+ * The constructor.
+ *
+ * @param vaultManager Vault manager.
+ * @param msManager Metastorage manager.
+ * @param topologyService Topology service.
+ * @param tablesConfiguration Tables configuration.
+ * @param leaseTracker Lease tracker.
+ * @param clock Cluster clock.
+ */
+ public LeaseUpdater(
+ VaultManager vaultManager,
+ MetaStorageManager msManager,
+ LogicalTopologyService topologyService,
+ TablesConfiguration tablesConfiguration,
+ LeaseTracker leaseTracker,
+ HybridClock clock
+ ) {
+ this.msManager = msManager;
+ this.leaseTracker = leaseTracker;
+ this.clock = clock;
+
+ this.assignmentsTracker = new AssignmentsTracker(vaultManager, msManager, tablesConfiguration);
+ this.topologyTracker = new TopologyTracker(topologyService);
+ this.updater = new Updater();
+ }
+
+ /**
+ * Initializes the class.
+ */
+ public void init(String nodeName) {
+ this.nodeName = nodeName;
+
+ topologyTracker.startTrack();
+ assignmentsTracker.startTrack();
+ }
+
+ /**
+ * De-initializes the class.
+ */
+ public void deInit() {
+ topologyTracker.stopTrack();
+ assignmentsTracker.stopTrack();
+ }
+
+ /**
+ * Activates a lease updater to renew leases.
+ */
+ public void activate() {
+ //TODO: IGNITE-18879 Implement lease maintenance.
+ updaterTread = new Thread(updater, NamedThreadFactory.threadPrefix(nodeName, "lease-updater"));
+
+ updaterTread.start();
+ }
+
+ /**
+ * Stops a dedicated thread to renew or assign leases.
+ */
+ public void deactivate() {
+ //TODO: IGNITE-18879 Implement lease maintenance.
+ if (updaterTread != null) {
+ updaterTread.interrupt();
+
+ updaterTread = null;
+ }
+ }
+
+ /**
+ * Compares two timestamps with the clock skew.
+ * t1, t2 comparable if t1 is not contained on [t2 - CLOCK_SKEW; t2 + CLOCK_SKEW].
+ * TODO: IGNITE-18978 Method to comparison timestamps with clock skew.
+ *
+ * @param ts1 First timestamp.
+ * @param ts2 Second timestamp.
+ * @return Result of comparison can be positive or negative, or {@code 0} if timestamps are not comparable.
+ */
+ private static int compareWithClockSkew(HybridTimestamp ts1, HybridTimestamp ts2) {
+ if (ts1.getPhysical() - CLOCK_SKEW <= ts2.getPhysical() && ts1.getPhysical() + CLOCK_SKEW >= ts2.getPhysical()) {
+ return 0;
+ }
+
+ return ts1.compareTo(ts2);
+ }
+
+ /**
+ * Finds a node that can be the leaseholder.
+ *
+ * @param assignments Replication group assignment.
+ * @return Cluster node, or {@code null} if no node in assignments can be the leaseholder.
+ */
+ private ClusterNode nextLeaseHolder(Set<Assignment> assignments) {
+ //TODO: IGNITE-18879 Implement more intellectual algorithm to choose a node.
+ for (Assignment assignment : assignments) {
+ ClusterNode candidate = topologyTracker.nodeByConsistentId(assignment.consistentId());
+
+ if (candidate != null) {
+ return candidate;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Runnable to update lease in Meta storage.
+ */
+ private class Updater implements Runnable {
+ @Override
+ public void run() {
+ while (!updaterTread.isInterrupted()) {
+ for (Map.Entry<ReplicationGroupId, Set<Assignment>> entry : assignmentsTracker.assignments().entrySet()) {
+ ReplicationGroupId grpId = entry.getKey();
+
+ Lease lease = leaseTracker.getLease(grpId);
+
+ HybridTimestamp now = clock.now();
+
+ // Nothing holds the lease.
+ if (lease == EMPTY_LEASE
+ // The lease is near to expiration.
+ || now.getPhysical() > (lease.getLeaseExpirationTime().getPhysical() - LEASE_PERIOD / 2)) {
+ ClusterNode candidate = nextLeaseHolder(entry.getValue());
+
+ if (candidate == null) {
+ continue;
+ }
+
+ if (isReplicationGroupUpdateLeaseholder(lease, candidate)) {
+ updateLeaseInMetaStorage(grpId, lease, candidate);
+ // New lease is granting.
+ } else if (candidate.equals(lease.getLeaseholder())) {
+ updateLeaseInMetaStorage(grpId, lease, candidate);
+ // Old lease is renewing.
+ }
+ }
+ }
+
+ try {
+ Thread.sleep(UPDATE_LEASE_MS);
+ } catch (InterruptedException e) {
+ LOG.warn("Lease updater is interrupted");
+ }
+ }
+ }
+
+ /**
+ * Writes a lease in Meta storage.
+ *
+ * @param grpId Replication group id.
+ * @param lease Old lease to apply CAS in Meta storage.
+ * @param candidate Lease candidate.
+ */
+ private void updateLeaseInMetaStorage(ReplicationGroupId grpId, Lease lease, ClusterNode candidate) {
+ var leaseKey = ByteArray.fromString(PLACEMENTDRIVER_PREFIX + grpId);
+ var newTs = new HybridTimestamp(clock.now().getPhysical() + LEASE_PERIOD, 0);
+
+ byte[] leaseRaw = ByteUtils.toBytes(lease);
+
+ Lease renewedLease = new Lease(candidate, newTs);
+
+ msManager.invoke(
+ or(notExists(leaseKey), value(leaseKey).eq(leaseRaw)),
+ put(leaseKey, ByteUtils.toBytes(renewedLease)),
+ noop()
+ );
+ }
+
+ /**
+ * Checks that a leaseholder candidate can take a lease on the replication group.
+ *
+ * @param lease Lease.
+ * @param candidate The node is a leaseholder candidate.
+ * @return True when the candidate can be a leaseholder, otherwise false.
+ */
+ private boolean isReplicationGroupUpdateLeaseholder(Lease lease, ClusterNode candidate) {
+ HybridTimestamp now = clock.now();
+
+ return lease == EMPTY_LEASE
+ || (!candidate.equals(lease.getLeaseholder()) && compareWithClockSkew(now, lease.getLeaseExpirationTime()) > 0);
+ }
+ }
+}
diff --git a/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/PlacementDriverManager.java b/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/PlacementDriverManager.java
index cbf07def6e..5c8c321f13 100644
--- a/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/PlacementDriverManager.java
+++ b/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/PlacementDriverManager.java
@@ -26,12 +26,16 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.apache.ignite.internal.cluster.management.topology.api.LogicalTopologyService;
+import org.apache.ignite.internal.hlc.HybridClock;
import org.apache.ignite.internal.manager.IgniteComponent;
+import org.apache.ignite.internal.metastorage.MetaStorageManager;
import org.apache.ignite.internal.raft.PeersAndLearners;
import org.apache.ignite.internal.raft.client.TopologyAwareRaftGroupService;
import org.apache.ignite.internal.raft.configuration.RaftConfiguration;
import org.apache.ignite.internal.replicator.ReplicationGroupId;
+import org.apache.ignite.internal.schema.configuration.TablesConfiguration;
import org.apache.ignite.internal.util.IgniteSpinBusyLock;
+import org.apache.ignite.internal.vault.VaultManager;
import org.apache.ignite.network.ClusterNode;
import org.apache.ignite.network.ClusterService;
import org.apache.ignite.raft.jraft.RaftMessagesFactory;
@@ -43,6 +47,7 @@ import org.jetbrains.annotations.TestOnly;
* The another role of the manager is providing a node, which is leaseholder at the moment, for a particular replication group.
*/
public class PlacementDriverManager implements IgniteComponent {
+ static final String PLACEMENTDRIVER_PREFIX = "placementdriver.lease.";
/** Busy lock to stop synchronously. */
private final IgniteSpinBusyLock busyLock = new IgniteSpinBusyLock();
@@ -51,44 +56,61 @@ public class PlacementDriverManager implements IgniteComponent {
/** Prevents double stopping of the component. */
private final AtomicBoolean isStopped = new AtomicBoolean();
- private final ReplicationGroupId replicationGroupId;
-
+ /** Cluster service. */
private final ClusterService clusterService;
+ /** Replication group id to store placement driver data. */
+ private final ReplicationGroupId replicationGroupId;
+
+ /** The closure determines nodes where are participants of placement driver. */
private final Supplier<CompletableFuture<Set<String>>> placementDriverNodesNamesProvider;
- /**
- * Raft client future. Can contain null, if this node is not in placement driver group.
- */
+ /** Raft client future. Can contain null, if this node is not in placement driver group. */
private final CompletableFuture<TopologyAwareRaftGroupService> raftClientFuture;
+ /** Executor sends a raft requests and receives response. */
private final ScheduledExecutorService raftClientExecutor;
+ /** Logical topology service. */
private final LogicalTopologyService logicalTopologyService;
+ /** Raft configuration. */
private final RaftConfiguration raftConfiguration;
- private volatile boolean isActiveActor;
+ /** Lease tracker. */
+ private final LeaseTracker leaseTracker;
- private volatile long lastTermSeen = -1;
+ /** Lease updater. */
+ private final LeaseUpdater leaseUpdater;
+
+ /** The flag is true when the instance of placement driver renews leases, false when the instance only tracks leases. */
+ private volatile boolean isActiveActor;
/**
* The constructor.
*
+ * @param metaStorageMgr Meta Storage manager.
+ * @param vaultManager Vault manager.
* @param replicationGroupId Id of placement driver group.
* @param clusterService Cluster service.
* @param raftConfiguration Raft configuration.
* @param placementDriverNodesNamesProvider Provider of the set of placement driver nodes' names.
* @param logicalTopologyService Logical topology service.
* @param raftClientExecutor Raft client executor.
+ * @param tablesCfg Table configuration.
+ * @param clock Hybrid clock.
*/
public PlacementDriverManager(
+ MetaStorageManager metaStorageMgr,
+ VaultManager vaultManager,
ReplicationGroupId replicationGroupId,
ClusterService clusterService,
RaftConfiguration raftConfiguration,
Supplier<CompletableFuture<Set<String>>> placementDriverNodesNamesProvider,
LogicalTopologyService logicalTopologyService,
- ScheduledExecutorService raftClientExecutor
+ ScheduledExecutorService raftClientExecutor,
+ TablesConfiguration tablesCfg,
+ HybridClock clock
) {
this.replicationGroupId = replicationGroupId;
this.clusterService = clusterService;
@@ -97,7 +119,16 @@ public class PlacementDriverManager implements IgniteComponent {
this.logicalTopologyService = logicalTopologyService;
this.raftClientExecutor = raftClientExecutor;
- raftClientFuture = new CompletableFuture<>();
+ this.raftClientFuture = new CompletableFuture<>();
+ this.leaseTracker = new LeaseTracker(vaultManager, metaStorageMgr);
+ this.leaseUpdater = new LeaseUpdater(
+ vaultManager,
+ metaStorageMgr,
+ logicalTopologyService,
+ tablesCfg,
+ leaseTracker,
+ clock
+ );
}
/** {@inheritDoc} */
@@ -108,6 +139,8 @@ public class PlacementDriverManager implements IgniteComponent {
String thisNodeName = clusterService.topologyService().localMember().name();
if (placementDriverNodes.contains(thisNodeName)) {
+ leaseUpdater.init(thisNodeName);
+
return TopologyAwareRaftGroupService.start(
replicationGroupId,
clusterService,
@@ -134,12 +167,20 @@ public class PlacementDriverManager implements IgniteComponent {
raftClientFuture.completeExceptionally(ex);
}
});
+
+ leaseTracker.startTrack();
}
/** {@inheritDoc} */
@Override
public void beforeNodeStop() {
- withRaftClientIfPresent(c -> c.unsubscribeLeader().join());
+ withRaftClientIfPresent(c -> {
+ c.unsubscribeLeader().join();
+
+ leaseUpdater.deInit();
+ });
+
+ leaseTracker.stopTrack();
}
/** {@inheritDoc} */
@@ -163,14 +204,10 @@ public class PlacementDriverManager implements IgniteComponent {
}
private void onLeaderChange(ClusterNode leader, Long term) {
- if (term > lastTermSeen) {
- if (leader.equals(clusterService.topologyService().localMember())) {
- takeOverActiveActor();
- } else {
- stepDownActiveActor();
- }
-
- lastTermSeen = term;
+ if (leader.equals(clusterService.topologyService().localMember())) {
+ takeOverActiveActor();
+ } else {
+ stepDownActiveActor();
}
}
@@ -179,6 +216,8 @@ public class PlacementDriverManager implements IgniteComponent {
*/
private void takeOverActiveActor() {
isActiveActor = true;
+
+ leaseUpdater.activate();
}
@@ -187,6 +226,8 @@ public class PlacementDriverManager implements IgniteComponent {
*/
private void stepDownActiveActor() {
isActiveActor = false;
+
+ leaseUpdater.deactivate();
}
@TestOnly
diff --git a/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/TopologyTracker.java b/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/TopologyTracker.java
new file mode 100644
index 0000000000..b0444a8312
--- /dev/null
+++ b/modules/placement-driver/src/main/java/org/apache/ignite/internal/placementdriver/TopologyTracker.java
@@ -0,0 +1,149 @@
+/*
+ * 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.ignite.internal.placementdriver;
+
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.ignite.internal.cluster.management.topology.api.LogicalTopologyEventListener;
+import org.apache.ignite.internal.cluster.management.topology.api.LogicalTopologyService;
+import org.apache.ignite.internal.cluster.management.topology.api.LogicalTopologySnapshot;
+import org.apache.ignite.internal.logger.IgniteLogger;
+import org.apache.ignite.internal.logger.Loggers;
+import org.apache.ignite.internal.util.CollectionUtils;
+import org.apache.ignite.network.ClusterNode;
+
+/**
+ * The class tracks a logical topology.
+ */
+public class TopologyTracker {
+ /** Ignite logger. */
+ private static final IgniteLogger LOG = Loggers.forClass(TopologyTracker.class);
+
+ /** Topology service. */
+ private final LogicalTopologyService topologyService;
+
+ /** Logical topology snapshot. */
+ private AtomicReference<LogicalTopologySnapshot> topologySnapRef;
+
+ /** Listener to track topology updates. */
+ private final TopologyListener topologyListener;
+
+ /**
+ * The constructor.
+ *
+ * @param topologyService Topology service.
+ */
+ public TopologyTracker(LogicalTopologyService topologyService) {
+ this.topologyService = topologyService;
+
+ this.topologySnapRef = new AtomicReference<>();
+ this.topologyListener = new TopologyListener();
+ }
+
+ /**
+ * Initializes topology on start.
+ */
+ public void startTrack() {
+ topologyService.addEventListener(topologyListener);
+
+ topologyService.logicalTopologyOnLeader().thenAccept(topologySnap -> {
+ LogicalTopologySnapshot logicalTopologySnap0;
+
+ do {
+ logicalTopologySnap0 = topologySnapRef.get();
+
+ if (logicalTopologySnap0 != null && logicalTopologySnap0.version() >= topologySnap.version()) {
+ break;
+ }
+ } while (!topologySnapRef.compareAndSet(logicalTopologySnap0, topologySnap));
+
+ LOG.info("Logical topology initialized for placement driver [topologySnap={}]", topologySnap);
+ });
+ }
+
+ /**
+ * Stops the tracker.
+ */
+ public void stopTrack() {
+ topologyService.removeEventListener(topologyListener);
+ }
+
+ /**
+ * Gets a node by consistent id from the logical topology snapshot.
+ *
+ * @param consistentId Node consistent id.
+ * @return Cluster node or {@code null} if topology has no a node with the consistent id.
+ */
+ public ClusterNode nodeByConsistentId(String consistentId) {
+ LogicalTopologySnapshot logicalTopologySnap0 = topologySnapRef.get();
+
+ if (logicalTopologySnap0 == null || CollectionUtils.nullOrEmpty(logicalTopologySnap0.nodes())) {
+ return null;
+ }
+
+ for (ClusterNode node : logicalTopologySnap0.nodes()) {
+ if (node.name().equals(consistentId)) {
+ return node;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Topology listener.
+ */
+ private class TopologyListener implements LogicalTopologyEventListener {
+ @Override
+ public void onNodeJoined(ClusterNode joinedNode, LogicalTopologySnapshot newTopology) {
+ onUpdate(newTopology);
+ }
+
+ @Override
+ public void onNodeLeft(ClusterNode leftNode, LogicalTopologySnapshot newTopology) {
+ onUpdate(newTopology);
+ }
+
+ /**
+ * Updates local topology cache.
+ *
+ * @param topologySnap Topology snasphot.
+ */
+ public void onUpdate(LogicalTopologySnapshot topologySnap) {
+ LogicalTopologySnapshot logicalTopologySnap0;
+
+ do {
+ logicalTopologySnap0 = topologySnapRef.get();
+
+ if (logicalTopologySnap0 != null && logicalTopologySnap0.version() >= topologySnap.version()) {
+ break;
+ }
+ } while (!topologySnapRef.compareAndSet(logicalTopologySnap0, topologySnap));
+
+ LOG.debug("Logical topology updated for placement driver [topologySnap={}]", topologySnap);
+
+ triggerToRenewLeases();
+ }
+ }
+
+ /**
+ * Triggers to renew leases forcibly. The method wakes up the monitor of {@link LeaseUpdater}.
+ */
+ private void triggerToRenewLeases() {
+ //TODO: IGNITE-18879 Implement lease maintenance.
+ }
+}
diff --git a/modules/runner/src/main/java/org/apache/ignite/internal/app/IgniteImpl.java b/modules/runner/src/main/java/org/apache/ignite/internal/app/IgniteImpl.java
index 714198a2eb..87c3779524 100644
--- a/modules/runner/src/main/java/org/apache/ignite/internal/app/IgniteImpl.java
+++ b/modules/runner/src/main/java/org/apache/ignite/internal/app/IgniteImpl.java
@@ -84,13 +84,11 @@ import org.apache.ignite.internal.manager.IgniteComponent;
import org.apache.ignite.internal.metastorage.MetaStorageManager;
import org.apache.ignite.internal.metastorage.impl.MetaStorageManagerImpl;
import org.apache.ignite.internal.metastorage.server.persistence.RocksDbKeyValueStorage;
-import org.apache.ignite.internal.metastorage.server.raft.MetastorageGroupId;
import org.apache.ignite.internal.metrics.MetricManager;
import org.apache.ignite.internal.metrics.configuration.MetricConfiguration;
import org.apache.ignite.internal.metrics.sources.JvmMetricSource;
import org.apache.ignite.internal.network.configuration.NetworkConfiguration;
import org.apache.ignite.internal.network.configuration.NetworkConfigurationSchema;
-import org.apache.ignite.internal.placementdriver.PlacementDriverManager;
import org.apache.ignite.internal.raft.Loza;
import org.apache.ignite.internal.raft.configuration.RaftConfiguration;
import org.apache.ignite.internal.raft.storage.impl.VolatileLogStorageFactoryCreator;
@@ -210,8 +208,9 @@ public class IgniteImpl implements Ignite {
/** Meta storage manager. */
private final MetaStorageManager metaStorageMgr;
- /** Placement driver manager. */
- private final PlacementDriverManager placementDriverMgr;
+ // TODO: IGNITE-16985 Design table management flow
+ // /** Placement driver manager. */
+ //private final PlacementDriverManager placementDriverMgr;
/** Configuration manager that handles cluster (distributed) configuration. */
private final ConfigurationManager clusterCfgMgr;
@@ -390,15 +389,6 @@ public class IgniteImpl implements Ignite {
new RocksDbKeyValueStorage(name, workDir.resolve(METASTORAGE_DB_PATH))
);
- placementDriverMgr = new PlacementDriverManager(
- MetastorageGroupId.INSTANCE,
- clusterSvc,
- raftConfiguration,
- cmgMgr::metaStorageNodes,
- logicalTopologyService,
- raftExecutorService
- );
-
this.cfgStorage = new DistributedConfigurationStorage(metaStorageMgr, vaultMgr);
clusterCfgMgr = new ConfigurationManager(
@@ -411,6 +401,22 @@ public class IgniteImpl implements Ignite {
ConfigurationRegistry clusterConfigRegistry = clusterCfgMgr.configurationRegistry();
+ TablesConfiguration tablesConfiguration = clusterConfigRegistry.getConfiguration(TablesConfiguration.KEY);
+
+ // TODO: IGNITE-16985 Design table management flow
+ // placementDriverMgr = new PlacementDriverManager(
+ // metaStorageMgr,
+ // vaultMgr,
+ // MetastorageGroupId.INSTANCE,
+ // clusterSvc,
+ // raftConfiguration,
+ // cmgMgr::metaStorageNodes,
+ // logicalTopologyService,
+ // raftExecutorService,
+ // tablesConfiguration,
+ // clock
+ // );
+
metricManager.configure(clusterConfigRegistry.getConfiguration(MetricConfiguration.KEY));
DistributionZonesConfiguration zonesConfiguration = clusterConfigRegistry
@@ -433,8 +439,6 @@ public class IgniteImpl implements Ignite {
Path storagePath = getPartitionsStorePath(workDir);
- TablesConfiguration tablesConfiguration = clusterConfigRegistry.getConfiguration(TablesConfiguration.KEY);
-
dataStorageMgr = new DataStorageManager(
tablesConfiguration,
dataStorageModules.createStorageEngines(
@@ -644,8 +648,9 @@ public class IgniteImpl implements Ignite {
try {
lifecycleManager.startComponents(
metaStorageMgr,
- placementDriverMgr,
clusterCfgMgr,
+ // TODO: IGNITE-16985 Design table management flow
+ // placementDriverMgr,
metricManager,
distributionZoneManager,
computeComponent,
diff --git a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/TableManager.java b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/TableManager.java
index a6b4cf639d..7315fa3a12 100644
--- a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/TableManager.java
+++ b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/TableManager.java
@@ -196,9 +196,9 @@ public class TableManager extends Producer<TableEvent, TableEventParameters> imp
private static final IntSupplier TX_STATE_STORAGE_FLUSH_DELAY_SUPPLIER = () -> TX_STATE_STORAGE_FLUSH_DELAY;
/**
- * If this property is set to {@code true} then an attempt to get the configuration property directly from the meta storage will be
+ * If this property is set to {@code true} then an attempt to get the configuration property directly from Meta storage will be
* skipped, and the local property will be returned.
- * TODO: IGNITE-16774 This property and overall approach, access configuration directly through the Metastorage,
+ * TODO: IGNITE-16774 This property and overall approach, access configuration directly through Meta storage,
* TODO: will be removed after fix of the issue.
*/
private final boolean getMetadataLocallyOnly = IgniteSystemProperties.getBoolean("IGNITE_GET_METADATA_LOCALLY_ONLY");
@@ -1955,7 +1955,7 @@ public class TableManager extends Producer<TableEvent, TableEventParameters> imp
assert pendingAssignmentsWatchEvent.revision() <= pendingAssignmentsEntry.revision()
: "Meta Storage watch cannot notify about an event with the revision that is more than the actual revision.";
- // Assignments of the pending rebalance that we received through the meta storage watch mechanism.
+ // Assignments of the pending rebalance that we received through Meta storage watch mechanism.
Set<Assignment> pendingAssignments = ByteUtils.fromBytes(pendingAssignmentsWatchEvent.value());
PeersAndLearners pendingConfiguration = configurationFromAssignments(pendingAssignments);
@@ -2106,7 +2106,7 @@ public class TableManager extends Producer<TableEvent, TableEventParameters> imp
}
/**
- * Creates meta storage listener for stable assignments updates.
+ * Creates Meta storage listener for stable assignments updates.
*
* @return The watch listener.
*/
@@ -2125,7 +2125,7 @@ public class TableManager extends Producer<TableEvent, TableEventParameters> imp
}
/**
- * Creates meta storage listener for switch reduce assignments updates.
+ * Creates Meta storage listener for switch reduce assignments updates.
*
* @return The watch listener.
*/
diff --git a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/TablePartitionId.java b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/TablePartitionId.java
index cac005f024..590bdb1586 100644
--- a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/TablePartitionId.java
+++ b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/TablePartitionId.java
@@ -43,6 +43,18 @@ public class TablePartitionId implements ReplicationGroupId {
this.partId = partId;
}
+ /**
+ * Converts a string representation of table partition id to the object.
+ *
+ * @param str String representation.
+ * @return An table partition id.
+ */
+ public static TablePartitionId fromString(String str) {
+ String[] parts = str.split("_part_");
+
+ return new TablePartitionId(UUID.fromString(parts[0]), Integer.valueOf(parts[1]));
+ }
+
/**
* Get the partition id.
*