You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by sk...@apache.org on 2025/03/06 07:22:24 UTC
(ignite-3) branch main updated: IGNITE-24388 Implement BuildIndexReplicaRequest processing for zone replica (#5276)
This is an automated email from the ASF dual-hosted git repository.
sk0x50 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 69b948af26a IGNITE-24388 Implement BuildIndexReplicaRequest processing for zone replica (#5276)
69b948af26a is described below
commit 69b948af26a44473b62ce97844ecdbcb0f88595a
Author: Slava Koptilin <sl...@gmail.com>
AuthorDate: Thu Mar 6 09:22:20 2025 +0200
IGNITE-24388 Implement BuildIndexReplicaRequest processing for zone replica (#5276)
---
.../apache/ignite/internal/catalog/Catalog.java | 31 ++-
.../ignite/internal/catalog/CatalogTableTest.java | 57 ++++
.../internal/index/ChangeIndexStatusTask.java | 17 +-
.../index/ChangeIndexStatusTaskController.java | 84 ++++--
.../internal/index/IndexBuildController.java | 291 ++++++++++++++-------
.../ignite/internal/index/IndexBuildTask.java | 15 +-
.../ignite/internal/index/IndexBuildTaskId.java | 22 +-
.../apache/ignite/internal/index/IndexBuilder.java | 30 +--
.../apache/ignite/internal/index/IndexManager.java | 30 ++-
.../index/IndexAvailabilityControllerTest.java | 5 +
.../internal/index/IndexBuildControllerTest.java | 68 +++--
.../ignite/internal/index/IndexBuilderTest.java | 26 +-
.../ignite/internal/index/TestPlacementDriver.java | 3 +-
.../partition/replicator/ItBuildIndexTest.java | 137 ++++++++++
.../partition/replicator/fixtures/Node.java | 18 ++
.../network/command/BuildIndexCommand.java | 2 +-
.../replication/BuildIndexReplicaRequest.java | 3 +-
.../table/distributed/index/IndexMeta.java | 2 +-
.../table/distributed/raft/PartitionListener.java | 131 +---------
.../raft/handlers/BuildIndexCommandHandler.java | 185 +++++++++++++
.../BuildIndexRowVersionChooser.java | 2 +-
.../IndexBuilderTxRwOperationTracker.java | 4 +-
.../replicator/PartitionReplicaListener.java | 45 +---
.../handlers/BuildIndexReplicaRequestHandler.java | 107 ++++++++
.../replicator/handlers/package-info.java | 22 ++
.../raft/PartitionCommandListenerTest.java | 7 +-
.../BuildIndexRowVersionChooserTest.java | 2 +-
.../ignite/internal/table/TableTestUtils.java | 12 +
28 files changed, 1002 insertions(+), 356 deletions(-)
diff --git a/modules/catalog/src/main/java/org/apache/ignite/internal/catalog/Catalog.java b/modules/catalog/src/main/java/org/apache/ignite/internal/catalog/Catalog.java
index b80078c11c7..956230bff46 100644
--- a/modules/catalog/src/main/java/org/apache/ignite/internal/catalog/Catalog.java
+++ b/modules/catalog/src/main/java/org/apache/ignite/internal/catalog/Catalog.java
@@ -18,7 +18,6 @@
package org.apache.ignite.internal.catalog;
import static it.unimi.dsi.fastutil.ints.Int2ObjectMaps.unmodifiable;
-import static java.util.Collections.unmodifiableList;
import static java.util.Comparator.comparingInt;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.collectingAndThen;
@@ -85,6 +84,9 @@ public class Catalog {
@IgniteToStringExclude
private final Int2ObjectMap<CatalogZoneDescriptor> zonesById;
+ @IgniteToStringExclude
+ private final Int2ObjectMap<List<CatalogTableDescriptor>> tablesByZoneId;
+
/**
* Constructor.
*
@@ -119,6 +121,7 @@ public class Catalog {
indexesById = schemas.stream().flatMap(s -> Arrays.stream(s.indexes())).collect(toMapById());
indexesByTableId = unmodifiable(toIndexesByTableId(schemas));
zonesById = zones.stream().collect(toMapById());
+ tablesByZoneId = unmodifiable(toTablesByZoneId(schemas));
if (defaultZoneId != null) {
defaultZone = zonesById.get((int) defaultZoneId);
@@ -219,6 +222,14 @@ public class Catalog {
return tablesById.values();
}
+ /**
+ * Returns all tables that belong to the specified zone.
+ *
+ * @return A collection of table descriptors.
+ */
+ public Collection<CatalogTableDescriptor> tables(int zoneId) {
+ return tablesByZoneId.getOrDefault(zoneId, List.of());
+ }
/**
* Returns an index descriptor by the given index name and schema name, that is an index that has not been dropped yet.
@@ -322,9 +333,25 @@ public class Catalog {
}
for (Entry<List<CatalogIndexDescriptor>> entry : indexesByTableId.int2ObjectEntrySet()) {
- entry.setValue(unmodifiableList(entry.getValue()));
+ entry.setValue(List.copyOf(entry.getValue()));
}
return indexesByTableId;
}
+
+ private static Int2ObjectMap<List<CatalogTableDescriptor>> toTablesByZoneId(Collection<CatalogSchemaDescriptor> schemas) {
+ var tablesByZoneId = new Int2ObjectOpenHashMap<List<CatalogTableDescriptor>>();
+
+ for (CatalogSchemaDescriptor schema : schemas) {
+ for (CatalogTableDescriptor table : schema.tables()) {
+ tablesByZoneId.computeIfAbsent(table.zoneId(), tables -> new ArrayList<>()).add(table);
+ }
+ }
+
+ for (Entry<List<CatalogTableDescriptor>> entry : tablesByZoneId.int2ObjectEntrySet()) {
+ entry.setValue(List.copyOf(entry.getValue()));
+ }
+
+ return tablesByZoneId;
+ }
}
diff --git a/modules/catalog/src/test/java/org/apache/ignite/internal/catalog/CatalogTableTest.java b/modules/catalog/src/test/java/org/apache/ignite/internal/catalog/CatalogTableTest.java
index cfa04ad3460..f7fc0493c0c 100644
--- a/modules/catalog/src/test/java/org/apache/ignite/internal/catalog/CatalogTableTest.java
+++ b/modules/catalog/src/test/java/org/apache/ignite/internal/catalog/CatalogTableTest.java
@@ -18,6 +18,7 @@
package org.apache.ignite.internal.catalog;
import static java.util.stream.Collectors.toList;
+import static org.apache.ignite.internal.catalog.CatalogManagerImpl.DEFAULT_ZONE_NAME;
import static org.apache.ignite.internal.catalog.CatalogTestUtils.addColumnParams;
import static org.apache.ignite.internal.catalog.CatalogTestUtils.applyNecessaryLength;
import static org.apache.ignite.internal.catalog.CatalogTestUtils.applyNecessaryPrecision;
@@ -46,7 +47,9 @@ import static org.apache.ignite.sql.ColumnType.PERIOD;
import static org.apache.ignite.sql.ColumnType.STRING;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
+import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
+import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@@ -78,14 +81,17 @@ import org.apache.ignite.internal.catalog.commands.ColumnParams;
import org.apache.ignite.internal.catalog.commands.ColumnParams.Builder;
import org.apache.ignite.internal.catalog.commands.CreateTableCommand;
import org.apache.ignite.internal.catalog.commands.CreateTableCommandBuilder;
+import org.apache.ignite.internal.catalog.commands.CreateZoneCommand;
import org.apache.ignite.internal.catalog.commands.DefaultValue;
import org.apache.ignite.internal.catalog.commands.RenameTableCommand;
+import org.apache.ignite.internal.catalog.commands.StorageProfileParams;
import org.apache.ignite.internal.catalog.commands.TableHashPrimaryKey;
import org.apache.ignite.internal.catalog.descriptors.CatalogHashIndexDescriptor;
import org.apache.ignite.internal.catalog.descriptors.CatalogIndexDescriptor;
import org.apache.ignite.internal.catalog.descriptors.CatalogSchemaDescriptor;
import org.apache.ignite.internal.catalog.descriptors.CatalogTableColumnDescriptor;
import org.apache.ignite.internal.catalog.descriptors.CatalogTableDescriptor;
+import org.apache.ignite.internal.catalog.descriptors.CatalogZoneDescriptor;
import org.apache.ignite.internal.catalog.events.AddColumnEventParameters;
import org.apache.ignite.internal.catalog.events.CatalogEvent;
import org.apache.ignite.internal.catalog.events.CatalogEventParameters;
@@ -94,6 +100,7 @@ import org.apache.ignite.internal.catalog.events.DropColumnEventParameters;
import org.apache.ignite.internal.catalog.events.DropTableEventParameters;
import org.apache.ignite.internal.catalog.events.RenameTableEventParameters;
import org.apache.ignite.internal.event.EventListener;
+import org.apache.ignite.internal.sql.SqlCommon;
import org.apache.ignite.sql.ColumnType;
import org.hamcrest.TypeSafeMatcher;
import org.jetbrains.annotations.Nullable;
@@ -1126,6 +1133,56 @@ public class CatalogTableTest extends BaseCatalogManagerTest {
assertThrows(CatalogValidationException.class, commandBuilder::build, error);
}
+ @Test
+ public void testCreateTablesWithinDifferentZones() {
+ // Create a new table in the default distribution zone.
+ tryApplyAndExpectApplied(simpleTable(TABLE_NAME));
+
+ // Create an additional distribution zone.
+ String customZoneName = "TEST_ZONE_NAME";
+
+ CatalogCommand cmd = CreateZoneCommand.builder()
+ .zoneName(customZoneName)
+ .partitions(42)
+ .replicas(15)
+ .dataNodesAutoAdjust(73)
+ .filter("expression")
+ .storageProfilesParams(List.of(StorageProfileParams.builder().storageProfile("test_profile").build()))
+ .build();
+
+ tryApplyAndExpectApplied(cmd);
+
+ String customTableName = "test_table_zone";
+ CatalogCommand createTableCmd = createTableCommandBuilder(
+ SqlCommon.DEFAULT_SCHEMA_NAME,
+ customTableName,
+ List.of(columnParams("ID", INT32), columnParams("VAL", INT32)),
+ List.of("ID"),
+ null)
+ .zone(customZoneName)
+ .build();
+
+ tryApplyAndExpectApplied(createTableCmd);
+
+ Catalog catalog = manager.catalog(manager.latestCatalogVersion());
+
+ CatalogZoneDescriptor defaultZoneDescriptor = catalog.zone(DEFAULT_ZONE_NAME);
+ CatalogZoneDescriptor zoneDescriptor = catalog.zone(customZoneName);
+ assertNotNull(defaultZoneDescriptor);
+ assertNotNull(zoneDescriptor);
+
+ assertThat(catalog.tables(), hasSize(2));
+
+ int tableId = catalog.table(SqlCommon.DEFAULT_SCHEMA_NAME, TABLE_NAME).id();
+ int customTableId = catalog.table(SqlCommon.DEFAULT_SCHEMA_NAME, customTableName).id();
+
+ assertThat(catalog.tables(defaultZoneDescriptor.id()), hasSize(1));
+ assertThat(catalog.tables(defaultZoneDescriptor.id()).stream().map(d -> d.id()).collect(toList()), hasItem(tableId));
+
+ assertThat(catalog.tables(zoneDescriptor.id()), hasSize(1));
+ assertThat(catalog.tables(zoneDescriptor.id()).stream().map(d -> d.id()).collect(toList()), hasItem(customTableId));
+ }
+
private CompletableFuture<CatalogApplyResult> changeColumn(
String tab,
String col,
diff --git a/modules/index/src/main/java/org/apache/ignite/internal/index/ChangeIndexStatusTask.java b/modules/index/src/main/java/org/apache/ignite/internal/index/ChangeIndexStatusTask.java
index 15d0e731f2e..9817b2d3bfa 100644
--- a/modules/index/src/main/java/org/apache/ignite/internal/index/ChangeIndexStatusTask.java
+++ b/modules/index/src/main/java/org/apache/ignite/internal/index/ChangeIndexStatusTask.java
@@ -28,6 +28,7 @@ import static org.apache.ignite.internal.catalog.commands.CatalogUtils.clusterWi
import static org.apache.ignite.internal.index.IndexManagementUtils.AWAIT_PRIMARY_REPLICA_TIMEOUT_SEC;
import static org.apache.ignite.internal.index.IndexManagementUtils.isPrimaryReplica;
import static org.apache.ignite.internal.index.IndexManagementUtils.localNode;
+import static org.apache.ignite.internal.lang.IgniteSystemProperties.enabledColocation;
import static org.apache.ignite.internal.util.CompletableFutures.nullCompletedFuture;
import static org.apache.ignite.internal.util.ExceptionUtils.unwrapCause;
@@ -44,6 +45,7 @@ import org.apache.ignite.internal.catalog.CatalogCommand;
import org.apache.ignite.internal.catalog.CatalogManager;
import org.apache.ignite.internal.catalog.descriptors.CatalogIndexDescriptor;
import org.apache.ignite.internal.catalog.descriptors.CatalogIndexStatus;
+import org.apache.ignite.internal.catalog.descriptors.CatalogTableDescriptor;
import org.apache.ignite.internal.cluster.management.topology.api.LogicalNode;
import org.apache.ignite.internal.cluster.management.topology.api.LogicalTopologyService;
import org.apache.ignite.internal.cluster.management.topology.api.LogicalTopologySnapshot;
@@ -61,7 +63,9 @@ import org.apache.ignite.internal.network.RecipientLeftException;
import org.apache.ignite.internal.placementdriver.PlacementDriver;
import org.apache.ignite.internal.placementdriver.PrimaryReplicaAwaitTimeoutException;
import org.apache.ignite.internal.placementdriver.ReplicaMeta;
+import org.apache.ignite.internal.replicator.ReplicationGroupId;
import org.apache.ignite.internal.replicator.TablePartitionId;
+import org.apache.ignite.internal.replicator.ZonePartitionId;
import org.apache.ignite.internal.table.distributed.index.IndexMeta;
import org.apache.ignite.internal.table.distributed.index.IndexMetaStorage;
import org.apache.ignite.internal.table.distributed.index.MetaIndexStatus;
@@ -237,7 +241,18 @@ abstract class ChangeIndexStatusTask {
private CompletableFuture<ReplicaMeta> awaitPrimaryReplica() {
return inBusyLocks(() -> {
- TablePartitionId groupId = new TablePartitionId(indexDescriptor.tableId(), 0);
+ IndexMeta indexMeta = indexMetaStorage.indexMeta(indexDescriptor.id());
+
+ if (indexMeta == null) {
+ // Index was destroyed under a low watermark, well, we not need to build it.
+ throw new IndexTaskStoppingException();
+ }
+
+ CatalogTableDescriptor tableDescriptor = catalogManager.catalog(indexMeta.catalogVersion()).table(indexDescriptor.tableId());
+
+ ReplicationGroupId groupId = enabledColocation()
+ ? new ZonePartitionId(tableDescriptor.zoneId(), 0)
+ : new TablePartitionId(indexDescriptor.tableId(), 0);
return placementDriver.awaitPrimaryReplica(groupId, clockService.now(), AWAIT_PRIMARY_REPLICA_TIMEOUT_SEC, SECONDS)
.handle((replicaMeta, throwable) -> {
diff --git a/modules/index/src/main/java/org/apache/ignite/internal/index/ChangeIndexStatusTaskController.java b/modules/index/src/main/java/org/apache/ignite/internal/index/ChangeIndexStatusTaskController.java
index 2bd6665cc65..f187b40ff31 100644
--- a/modules/index/src/main/java/org/apache/ignite/internal/index/ChangeIndexStatusTaskController.java
+++ b/modules/index/src/main/java/org/apache/ignite/internal/index/ChangeIndexStatusTaskController.java
@@ -18,8 +18,11 @@
package org.apache.ignite.internal.index;
import static org.apache.ignite.internal.index.IndexManagementUtils.isLocalNode;
+import static org.apache.ignite.internal.lang.IgniteSystemProperties.enabledColocation;
import static org.apache.ignite.internal.util.IgniteUtils.inBusyLock;
+import it.unimi.dsi.fastutil.ints.IntArrayList;
+import it.unimi.dsi.fastutil.ints.IntPredicate;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -28,6 +31,7 @@ import org.apache.ignite.internal.catalog.CatalogManager;
import org.apache.ignite.internal.catalog.CatalogService;
import org.apache.ignite.internal.catalog.descriptors.CatalogIndexDescriptor;
import org.apache.ignite.internal.catalog.descriptors.CatalogIndexStatus;
+import org.apache.ignite.internal.catalog.descriptors.CatalogTableDescriptor;
import org.apache.ignite.internal.catalog.events.CatalogEvent;
import org.apache.ignite.internal.catalog.events.CreateIndexEventParameters;
import org.apache.ignite.internal.catalog.events.RemoveIndexEventParameters;
@@ -39,7 +43,9 @@ import org.apache.ignite.internal.placementdriver.PlacementDriver;
import org.apache.ignite.internal.placementdriver.ReplicaMeta;
import org.apache.ignite.internal.placementdriver.event.PrimaryReplicaEvent;
import org.apache.ignite.internal.placementdriver.event.PrimaryReplicaEventParameters;
+import org.apache.ignite.internal.replicator.PartitionGroupId;
import org.apache.ignite.internal.replicator.TablePartitionId;
+import org.apache.ignite.internal.replicator.ZonePartitionId;
import org.apache.ignite.internal.util.IgniteSpinBusyLock;
/**
@@ -153,46 +159,86 @@ class ChangeIndexStatusTaskController implements ManuallyCloseable {
private void onPrimaryReplicaElected(PrimaryReplicaEventParameters parameters) {
inBusyLock(busyLock, () -> {
- TablePartitionId primaryReplicaId = (TablePartitionId) parameters.groupId();
+
+ PartitionGroupId primaryReplicaId = (PartitionGroupId) parameters.groupId();
if (primaryReplicaId.partitionId() != 0) {
// We are only interested in the 0 partition.
return;
}
- int tableId = primaryReplicaId.tableId();
-
if (isLocalNode(clusterService, parameters.leaseholderId())) {
- if (localNodeIsPrimaryReplicaForTableIds.add(tableId)) {
- scheduleTasksOnPrimaryReplicaElectedBusy(tableId);
- }
+ scheduleTasksOnPrimaryReplicaElectedBusy(primaryReplicaId);
} else {
- if (localNodeIsPrimaryReplicaForTableIds.remove(tableId)) {
- changeIndexStatusTaskScheduler.stopTasksForTable(tableId);
+ scheduleStopTasksOnPrimaryReplicaElected(primaryReplicaId);
+ }
+ });
+ }
+
+ private void scheduleTasksOnPrimaryReplicaElectedBusy(PartitionGroupId partitionGroupId) {
+ // It is safe to get the latest version of the catalog because the PRIMARY_REPLICA_ELECTED event is handled on the metastore thread.
+ Catalog catalog = catalogService.catalog(catalogService.latestCatalogVersion());
+
+ IntArrayList tableIds =
+ getTableIdsForPrimaryReplicaElected(catalog, partitionGroupId, id -> !localNodeIsPrimaryReplicaForTableIds.contains(id));
+
+ localNodeIsPrimaryReplicaForTableIds.addAll(tableIds);
+
+ tableIds.forEach(tableId -> {
+ for (CatalogIndexDescriptor indexDescriptor : catalog.indexes(tableId)) {
+ switch (indexDescriptor.status()) {
+ case REGISTERED:
+ changeIndexStatusTaskScheduler.scheduleStartBuildingTask(indexDescriptor);
+
+ break;
+
+ case STOPPING:
+ changeIndexStatusTaskScheduler.scheduleRemoveIndexTask(indexDescriptor);
+
+ break;
+
+ default:
+ break;
}
}
});
}
- private void scheduleTasksOnPrimaryReplicaElectedBusy(int tableId) {
+ private void scheduleStopTasksOnPrimaryReplicaElected(PartitionGroupId partitionGroupId) {
// It is safe to get the latest version of the catalog because the PRIMARY_REPLICA_ELECTED event is handled on the metastore thread.
Catalog catalog = catalogService.catalog(catalogService.latestCatalogVersion());
- for (CatalogIndexDescriptor indexDescriptor : catalog.indexes(tableId)) {
- switch (indexDescriptor.status()) {
- case REGISTERED:
- changeIndexStatusTaskScheduler.scheduleStartBuildingTask(indexDescriptor);
+ IntArrayList tableIds =
+ getTableIdsForPrimaryReplicaElected(catalog, partitionGroupId, localNodeIsPrimaryReplicaForTableIds::contains);
- break;
+ localNodeIsPrimaryReplicaForTableIds.removeAll(tableIds);
- case STOPPING:
- changeIndexStatusTaskScheduler.scheduleRemoveIndexTask(indexDescriptor);
+ tableIds.forEach(changeIndexStatusTaskScheduler::stopTasksForTable);
+ }
- break;
+ private static IntArrayList getTableIdsForPrimaryReplicaElected(
+ Catalog catalog,
+ PartitionGroupId partitionGroupId,
+ IntPredicate predicate
+ ) {
+ var tableIds = new IntArrayList();
- default:
- break;
+ if (enabledColocation()) {
+ ZonePartitionId zonePartitionId = (ZonePartitionId) partitionGroupId;
+
+ for (CatalogTableDescriptor table : catalog.tables(zonePartitionId.zoneId())) {
+ if (predicate.test(table.id())) {
+ tableIds.add(table.id());
+ }
+ }
+ } else {
+ TablePartitionId tablePartitionId = (TablePartitionId) partitionGroupId;
+
+ if (predicate.test(tablePartitionId.tableId())) {
+ tableIds.add(tablePartitionId.tableId());
}
}
+
+ return tableIds;
}
}
diff --git a/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuildController.java b/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuildController.java
index 0851fe0d205..125ede70cae 100644
--- a/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuildController.java
+++ b/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuildController.java
@@ -17,18 +17,20 @@
package org.apache.ignite.internal.index;
-import static java.util.concurrent.CompletableFuture.allOf;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.apache.ignite.internal.catalog.descriptors.CatalogIndexStatus.AVAILABLE;
import static org.apache.ignite.internal.catalog.descriptors.CatalogIndexStatus.BUILDING;
+import static org.apache.ignite.internal.catalog.events.CatalogEvent.INDEX_BUILDING;
+import static org.apache.ignite.internal.catalog.events.CatalogEvent.INDEX_REMOVED;
import static org.apache.ignite.internal.index.IndexManagementUtils.AWAIT_PRIMARY_REPLICA_TIMEOUT_SEC;
import static org.apache.ignite.internal.index.IndexManagementUtils.isLocalNode;
import static org.apache.ignite.internal.index.IndexManagementUtils.isPrimaryReplica;
+import static org.apache.ignite.internal.lang.IgniteSystemProperties.enabledColocation;
+import static org.apache.ignite.internal.placementdriver.event.PrimaryReplicaEvent.PRIMARY_REPLICA_ELECTED;
import static org.apache.ignite.internal.util.CompletableFutures.nullCompletedFuture;
import static org.apache.ignite.internal.util.IgniteUtils.inBusyLock;
import static org.apache.ignite.internal.util.IgniteUtils.inBusyLockAsync;
-import static org.apache.ignite.lang.ErrorGroups.Common.INTERNAL_ERR;
import java.util.ArrayList;
import java.util.Set;
@@ -40,27 +42,32 @@ import org.apache.ignite.internal.catalog.Catalog;
import org.apache.ignite.internal.catalog.CatalogService;
import org.apache.ignite.internal.catalog.descriptors.CatalogIndexDescriptor;
import org.apache.ignite.internal.catalog.descriptors.CatalogIndexStatus;
+import org.apache.ignite.internal.catalog.descriptors.CatalogTableDescriptor;
+import org.apache.ignite.internal.catalog.descriptors.CatalogZoneDescriptor;
import org.apache.ignite.internal.catalog.events.CatalogEvent;
import org.apache.ignite.internal.catalog.events.RemoveIndexEventParameters;
import org.apache.ignite.internal.catalog.events.StartBuildingIndexEventParameters;
import org.apache.ignite.internal.close.ManuallyCloseable;
+import org.apache.ignite.internal.event.EventListener;
import org.apache.ignite.internal.hlc.ClockService;
import org.apache.ignite.internal.hlc.HybridTimestamp;
-import org.apache.ignite.internal.lang.IgniteInternalException;
import org.apache.ignite.internal.network.ClusterService;
import org.apache.ignite.internal.placementdriver.PlacementDriver;
import org.apache.ignite.internal.placementdriver.PrimaryReplicaAwaitTimeoutException;
import org.apache.ignite.internal.placementdriver.ReplicaMeta;
import org.apache.ignite.internal.placementdriver.event.PrimaryReplicaEvent;
import org.apache.ignite.internal.placementdriver.event.PrimaryReplicaEventParameters;
+import org.apache.ignite.internal.replicator.PartitionGroupId;
+import org.apache.ignite.internal.replicator.ReplicationGroupId;
import org.apache.ignite.internal.replicator.TablePartitionId;
+import org.apache.ignite.internal.replicator.ZonePartitionId;
import org.apache.ignite.internal.storage.MvPartitionStorage;
import org.apache.ignite.internal.storage.engine.MvTableStorage;
import org.apache.ignite.internal.storage.index.IndexStorage;
+import org.apache.ignite.internal.util.CompletableFutures;
import org.apache.ignite.internal.util.ExceptionUtils;
import org.apache.ignite.internal.util.IgniteSpinBusyLock;
import org.apache.ignite.network.ClusterNode;
-import org.jetbrains.annotations.Nullable;
/**
* Component is responsible for starting and stopping the building of indexes on primary replicas.
@@ -95,7 +102,9 @@ class IndexBuildController implements ManuallyCloseable {
private final AtomicBoolean closeGuard = new AtomicBoolean();
- private final Set<TablePartitionId> primaryReplicaIds = ConcurrentHashMap.newKeySet();
+ // TODO https://issues.apache.org/jira/browse/IGNITE-22522
+ // It makes sense to change ReplicationGroupId to ZonePartitionId.
+ private final Set<ReplicationGroupId> primaryReplicaIds = ConcurrentHashMap.newKeySet();
/** Constructor. */
IndexBuildController(
@@ -131,46 +140,82 @@ class IndexBuildController implements ManuallyCloseable {
}
private void addListeners() {
- catalogService.listen(CatalogEvent.INDEX_BUILDING, (StartBuildingIndexEventParameters parameters) -> {
- return onIndexBuilding(parameters).thenApply(unused -> false);
- });
+ catalogService.listen(INDEX_BUILDING, EventListener.fromConsumer(this::onIndexBuilding));
- catalogService.listen(CatalogEvent.INDEX_REMOVED, (RemoveIndexEventParameters parameters) -> {
- return onIndexRemoved(parameters).thenApply(unused -> false);
- });
+ catalogService.listen(INDEX_REMOVED, EventListener.fromConsumer(this::onIndexRemoved));
- placementDriver.listen(PrimaryReplicaEvent.PRIMARY_REPLICA_ELECTED, parameters -> {
- return onPrimaryReplicaElected(parameters).thenApply(unused -> false);
- });
+ placementDriver.listen(PRIMARY_REPLICA_ELECTED, EventListener.fromConsumer(this::onPrimaryReplicaElected));
}
private CompletableFuture<?> onIndexBuilding(StartBuildingIndexEventParameters parameters) {
return inBusyLockAsync(busyLock, () -> {
Catalog catalog = catalogService.catalog(parameters.catalogVersion());
- assert catalog != null : "Not found catalog for version " + parameters.catalogVersion();
+ assert catalog != null : "Failed to find a catalog for the specified version [version=" + parameters.catalogVersion()
+ + ", earliestVersion=" + catalogService.earliestCatalogVersion()
+ + ", latestVersion=" + catalogService.latestCatalogVersion()
+ + "].";
CatalogIndexDescriptor indexDescriptor = catalog.index(parameters.indexId());
+ assert indexDescriptor != null : "Failed to find an index descriptor for the specified index [indexId="
+ + parameters.indexId() + ", catalogVersion=" + parameters.catalogVersion() + "].";
+
+ assert catalog.table(indexDescriptor.tableId()) != null : "Failed to find a table descriptor for the specified index [indexId="
+ + parameters.indexId() + ", tableId=" + indexDescriptor.tableId()
+ + ", catalogVersion=" + parameters.catalogVersion() + "].";
+
+ CatalogZoneDescriptor zoneDescriptor = catalog.zone(catalog.table(indexDescriptor.tableId()).zoneId());
+
+ assert zoneDescriptor != null : "Failed to find a zone descriptor for the specified table [indexId="
+ + parameters.indexId() + ", tableId=" + indexDescriptor.tableId()
+ + ", catalogVersion=" + parameters.catalogVersion() + "].";
+
var startBuildIndexFutures = new ArrayList<CompletableFuture<?>>();
- for (TablePartitionId primaryReplicaId : primaryReplicaIds) {
- if (primaryReplicaId.tableId() == indexDescriptor.tableId()) {
- CompletableFuture<?> startBuildIndexFuture = getMvTableStorageFuture(parameters.causalityToken(), primaryReplicaId)
- .thenCompose(mvTableStorage -> awaitPrimaryReplica(primaryReplicaId, clockService.now())
+ for (ReplicationGroupId primaryReplicationGroupId : primaryReplicaIds) {
+ int zoneId;
+ int partitionId;
+ boolean needToProcessPartition;
+
+ // TODO https://issues.apache.org/jira/browse/IGNITE-22522
+ // Remove TablePartitionId check.
+ if (primaryReplicationGroupId instanceof ZonePartitionId) {
+ ZonePartitionId zoneReplicaId = (ZonePartitionId) primaryReplicationGroupId;
+ zoneId = zoneReplicaId.zoneId();
+ partitionId = zoneReplicaId.partitionId();
+
+ needToProcessPartition = zoneReplicaId.zoneId() == zoneDescriptor.id();
+ } else {
+ TablePartitionId partitionReplicaId = (TablePartitionId) primaryReplicationGroupId;
+ needToProcessPartition = partitionReplicaId.tableId() == indexDescriptor.tableId();
+
+ if (needToProcessPartition) {
+ zoneId = catalog.table(partitionReplicaId.tableId()).zoneId();
+ partitionId = partitionReplicaId.partitionId();
+ } else {
+ continue;
+ }
+ }
+
+ if (needToProcessPartition) {
+ CompletableFuture<?> startBuildIndexFuture = indexManager
+ .getMvTableStorage(parameters.causalityToken(), indexDescriptor.tableId())
+ .thenCompose(mvTableStorage -> awaitPrimaryReplica(primaryReplicationGroupId, clockService.now())
.thenAccept(replicaMeta -> tryScheduleBuildIndex(
- primaryReplicaId,
+ zoneId,
+ indexDescriptor.tableId(),
+ partitionId,
+ primaryReplicationGroupId,
indexDescriptor,
mvTableStorage,
- replicaMeta
- ))
- );
+ replicaMeta)));
startBuildIndexFutures.add(startBuildIndexFuture);
}
}
- return allOf(startBuildIndexFutures.toArray(CompletableFuture[]::new));
+ return CompletableFutures.allOf(startBuildIndexFutures);
});
}
@@ -184,31 +229,70 @@ class IndexBuildController implements ManuallyCloseable {
private CompletableFuture<?> onPrimaryReplicaElected(PrimaryReplicaEventParameters parameters) {
return inBusyLockAsync(busyLock, () -> {
- TablePartitionId primaryReplicaId = (TablePartitionId) parameters.groupId();
-
if (isLocalNode(clusterService, parameters.leaseholderId())) {
- primaryReplicaIds.add(primaryReplicaId);
+ // TODO https://issues.apache.org/jira/browse/IGNITE-22522
+ // Need to remove TablePartitionId check here and below.
+ assert parameters.groupId() instanceof ZonePartitionId || parameters.groupId() instanceof TablePartitionId :
+ "Primary replica ID must be of type ZonePartitionId or TablePartitionId [groupId="
+ + parameters.groupId() + ", class=" + parameters.groupId().getClass().getSimpleName() + "].";
+
+ primaryReplicaIds.add(parameters.groupId());
// It is safe to get the latest version of the catalog because the PRIMARY_REPLICA_ELECTED event is handled on the
// metastore thread.
Catalog catalog = catalogService.catalog(catalogService.latestCatalogVersion());
- // TODO: IGNITE-22656 It is necessary not to generate an event for a destroyed table by LWM
- if (catalog == null || catalog.table(primaryReplicaId.tableId()) == null) {
- return nullCompletedFuture();
- }
+ if (parameters.groupId() instanceof ZonePartitionId) {
+ assert enabledColocation() : "Primary replica ID must be of type ZonePartitionId";
+
+ ZonePartitionId primaryReplicaId = (ZonePartitionId) parameters.groupId();
+
+ CatalogZoneDescriptor zoneDescriptor = catalog.zone(primaryReplicaId.zoneId());
+ // TODO: IGNITE-22656 It is necessary not to generate an event for a destroyed zone by LWM
+ if (zoneDescriptor == null) {
+ return nullCompletedFuture();
+ }
+
+ var indexFutures = new ArrayList<CompletableFuture<?>>();
+ for (CatalogTableDescriptor tableDescriptor : catalog.tables(zoneDescriptor.id())) {
+ // Perhaps, it makes sense to get primary replica future first and then get table storage future,
+ // because, it will be the same for all tables in the zone for the given partition.
+ CompletableFuture<?> future =
+ indexManager.getMvTableStorage(parameters.causalityToken(), tableDescriptor.id())
+ .thenCompose(mvTableStorage -> awaitPrimaryReplica(primaryReplicaId, parameters.startTime())
+ .thenAccept(replicaMeta -> tryScheduleBuildIndexesForNewPrimaryReplica(
+ catalog,
+ tableDescriptor,
+ primaryReplicaId,
+ mvTableStorage,
+ replicaMeta)));
+
+ indexFutures.add(future);
+ }
+
+ return CompletableFutures.allOf(indexFutures);
+ } else {
+ TablePartitionId primaryReplicaId = (TablePartitionId) parameters.groupId();
+
+ // TODO: IGNITE-22656 It is necessary not to generate an event for a destroyed table by LWM
+ CatalogTableDescriptor tableDescriptor = catalog.table(primaryReplicaId.tableId());
+ if (tableDescriptor == null) {
+ return nullCompletedFuture();
+ }
- return getMvTableStorageFuture(parameters.causalityToken(), primaryReplicaId)
- .thenCompose(mvTableStorage -> awaitPrimaryReplica(primaryReplicaId, parameters.startTime())
- .thenAccept(replicaMeta -> tryScheduleBuildIndexesForNewPrimaryReplica(
- catalog.version(),
- primaryReplicaId,
- mvTableStorage,
- replicaMeta
- ))
- );
+ return indexManager.getMvTableStorage(parameters.causalityToken(), primaryReplicaId.tableId())
+ .thenCompose(mvTableStorage -> awaitPrimaryReplica(primaryReplicaId, parameters.startTime())
+ .thenAccept(replicaMeta -> tryScheduleBuildIndexesForNewPrimaryReplica(
+ catalog,
+ tableDescriptor,
+ primaryReplicaId,
+ mvTableStorage,
+ replicaMeta
+ ))
+ );
+ }
} else {
- stopBuildingIndexesIfPrimaryExpired(primaryReplicaId);
+ stopBuildingIndexesIfPrimaryExpired(parameters.groupId());
return nullCompletedFuture();
}
@@ -216,28 +300,33 @@ class IndexBuildController implements ManuallyCloseable {
}
private void tryScheduleBuildIndexesForNewPrimaryReplica(
- int catalogVersion,
- TablePartitionId primaryReplicaId,
+ Catalog catalog,
+ CatalogTableDescriptor tableDescriptor,
+ ReplicationGroupId primaryReplicaId,
MvTableStorage mvTableStorage,
ReplicaMeta replicaMeta
) {
inBusyLock(busyLock, () -> {
- if (isLeaseExpire(replicaMeta)) {
+ if (isLeaseExpired(replicaMeta)) {
stopBuildingIndexesIfPrimaryExpired(primaryReplicaId);
return;
}
- Catalog catalog = catalogService.catalog(catalogVersion);
-
- assert catalog != null : "Not found catalog for version " + catalogVersion;
-
- for (CatalogIndexDescriptor indexDescriptor : catalog.indexes(primaryReplicaId.tableId())) {
+ for (CatalogIndexDescriptor indexDescriptor : catalog.indexes(tableDescriptor.id())) {
if (indexDescriptor.status() == BUILDING) {
- scheduleBuildIndex(primaryReplicaId, indexDescriptor, mvTableStorage, enlistmentConsistencyToken(replicaMeta));
+ scheduleBuildIndex(
+ tableDescriptor.zoneId(),
+ tableDescriptor.id(),
+ ((PartitionGroupId) primaryReplicaId).partitionId(),
+ indexDescriptor,
+ mvTableStorage,
+ enlistmentConsistencyToken(replicaMeta));
} else if (indexDescriptor.status() == AVAILABLE) {
scheduleBuildIndexAfterDisasterRecovery(
- primaryReplicaId,
+ tableDescriptor.zoneId(),
+ tableDescriptor.id(),
+ ((PartitionGroupId) primaryReplicaId).partitionId(),
indexDescriptor,
mvTableStorage,
enlistmentConsistencyToken(replicaMeta)
@@ -248,19 +337,33 @@ class IndexBuildController implements ManuallyCloseable {
}
private void tryScheduleBuildIndex(
- TablePartitionId primaryReplicaId,
+ int zoneId,
+ int tableId,
+ int partitionId,
+ ReplicationGroupId primaryReplicaId,
CatalogIndexDescriptor indexDescriptor,
MvTableStorage mvTableStorage,
ReplicaMeta replicaMeta
) {
+ // TODO https://issues.apache.org/jira/browse/IGNITE-22522
+ // Remove TablePartitionId check.
+ assert primaryReplicaId instanceof ZonePartitionId
+ ? ((ZonePartitionId) primaryReplicaId).zoneId() == zoneId
+ && ((ZonePartitionId) primaryReplicaId).partitionId() == partitionId
+ : ((TablePartitionId) primaryReplicaId).tableId() == tableId
+ && ((TablePartitionId) primaryReplicaId).partitionId() == partitionId
+ : "Primary replica identifier mismatched [zoneId=" + zoneId + ", tableId=" + tableId
+ + ", partitionId=" + partitionId + ", primaryReplicaId=" + primaryReplicaId
+ + ", primaryReplicaCls=" + primaryReplicaId.getClass().getSimpleName() + "].";
+
inBusyLock(busyLock, () -> {
- if (isLeaseExpire(replicaMeta)) {
+ if (isLeaseExpired(replicaMeta)) {
stopBuildingIndexesIfPrimaryExpired(primaryReplicaId);
return;
}
- scheduleBuildIndex(primaryReplicaId, indexDescriptor, mvTableStorage, enlistmentConsistencyToken(replicaMeta));
+ scheduleBuildIndex(zoneId, tableId, partitionId, indexDescriptor, mvTableStorage, enlistmentConsistencyToken(replicaMeta));
});
}
@@ -272,31 +375,23 @@ class IndexBuildController implements ManuallyCloseable {
*
* @param replicaId Replica ID.
*/
- private void stopBuildingIndexesIfPrimaryExpired(TablePartitionId replicaId) {
+ private void stopBuildingIndexesIfPrimaryExpired(ReplicationGroupId replicaId) {
if (primaryReplicaIds.remove(replicaId)) {
// Primary replica is no longer current, we need to stop building indexes for it.
- indexBuilder.stopBuildingIndexes(replicaId.tableId(), replicaId.partitionId());
- }
- }
- private CompletableFuture<MvTableStorage> getMvTableStorageFuture(long causalityToken, TablePartitionId replicaId) {
- return indexManager.getMvTableStorage(causalityToken, replicaId.tableId())
- .thenApply(mvTableStorage -> requireMvTableStorageNonNull(mvTableStorage, replicaId.tableId()));
- }
-
- private static MvTableStorage requireMvTableStorageNonNull(@Nullable MvTableStorage mvTableStorage, int tableId) {
- if (mvTableStorage == null) {
- throw new IgniteInternalException(
- INTERNAL_ERR,
- "Table storage for the specified table cannot be null [tableId = {}]",
- tableId
- );
+ // TODO https://issues.apache.org/jira/browse/IGNITE-22522
+ // Remove TablePartitionId check.
+ if (replicaId instanceof ZonePartitionId) {
+ ZonePartitionId zoneId = (ZonePartitionId) replicaId;
+ indexBuilder.stopBuildingZoneIndexes(zoneId.zoneId(), zoneId.partitionId());
+ } else {
+ TablePartitionId partitionId = (TablePartitionId) replicaId;
+ indexBuilder.stopBuildingTableIndexes(partitionId.tableId(), partitionId.partitionId());
+ }
}
-
- return mvTableStorage;
}
- private CompletableFuture<ReplicaMeta> awaitPrimaryReplica(TablePartitionId replicaId, HybridTimestamp timestamp) {
+ private CompletableFuture<ReplicaMeta> awaitPrimaryReplica(ReplicationGroupId replicaId, HybridTimestamp timestamp) {
return placementDriver
.awaitPrimaryReplica(replicaId, timestamp, AWAIT_PRIMARY_REPLICA_TIMEOUT_SEC, SECONDS)
.handle((replicaMeta, throwable) -> {
@@ -316,20 +411,21 @@ class IndexBuildController implements ManuallyCloseable {
/** Shortcut to schedule index building. */
private void scheduleBuildIndex(
- TablePartitionId replicaId,
+ int zoneId,
+ int tableId,
+ int partitionId,
CatalogIndexDescriptor indexDescriptor,
MvTableStorage mvTableStorage,
long enlistmentConsistencyToken
) {
- MvPartitionStorage mvPartition = mvPartitionStorage(mvTableStorage, replicaId);
-
- assert mvPartition != null : "Partition storage is missing, replicaId=" + replicaId;
+ MvPartitionStorage mvPartition = mvPartitionStorage(mvTableStorage, zoneId, tableId, partitionId);
- IndexStorage indexStorage = indexStorage(mvTableStorage, replicaId, indexDescriptor);
+ IndexStorage indexStorage = indexStorage(mvTableStorage, partitionId, indexDescriptor);
indexBuilder.scheduleBuildIndex(
- replicaId.tableId(),
- replicaId.partitionId(),
+ zoneId,
+ tableId,
+ partitionId,
indexDescriptor.id(),
indexStorage,
mvPartition,
@@ -340,20 +436,21 @@ class IndexBuildController implements ManuallyCloseable {
/** Shortcut to schedule {@link CatalogIndexStatus#AVAILABLE available} index building after disaster recovery. */
private void scheduleBuildIndexAfterDisasterRecovery(
- TablePartitionId replicaId,
+ int zoneId,
+ int tableId,
+ int partitionId,
CatalogIndexDescriptor indexDescriptor,
MvTableStorage mvTableStorage,
long enlistmentConsistencyToken
) {
- MvPartitionStorage mvPartition = mvPartitionStorage(mvTableStorage, replicaId);
+ MvPartitionStorage mvPartition = mvPartitionStorage(mvTableStorage, zoneId, tableId, partitionId);
- assert mvPartition != null : "Partition storage is missing, replicaId=" + replicaId;
-
- IndexStorage indexStorage = indexStorage(mvTableStorage, replicaId, indexDescriptor);
+ IndexStorage indexStorage = indexStorage(mvTableStorage, partitionId, indexDescriptor);
indexBuilder.scheduleBuildIndexAfterDisasterRecovery(
- replicaId.tableId(),
- replicaId.partitionId(),
+ zoneId,
+ tableId,
+ partitionId,
indexDescriptor.id(),
indexStorage,
mvPartition,
@@ -366,7 +463,7 @@ class IndexBuildController implements ManuallyCloseable {
return IndexManagementUtils.localNode(clusterService);
}
- private boolean isLeaseExpire(ReplicaMeta replicaMeta) {
+ private boolean isLeaseExpired(ReplicaMeta replicaMeta) {
return !isPrimaryReplica(replicaMeta, localNode(), clockService.now());
}
@@ -374,22 +471,28 @@ class IndexBuildController implements ManuallyCloseable {
return replicaMeta.getStartTime().longValue();
}
- private static MvPartitionStorage mvPartitionStorage(MvTableStorage mvTableStorage, TablePartitionId replicaId) {
- MvPartitionStorage mvPartition = mvTableStorage.getMvPartition(replicaId.partitionId());
+ private static MvPartitionStorage mvPartitionStorage(
+ MvTableStorage mvTableStorage,
+ int zoneId,
+ int tableId,
+ int partitionId
+ ) {
+ MvPartitionStorage mvPartition = mvTableStorage.getMvPartition(partitionId);
- assert mvPartition != null : "Partition storage is missing, replicaId=" + replicaId;
+ assert mvPartition != null : "Partition storage is missing [zoneId=" + zoneId
+ + ", tableId=" + tableId + ", partitionId=" + partitionId + "].";
return mvPartition;
}
private static IndexStorage indexStorage(
MvTableStorage mvTableStorage,
- TablePartitionId replicaId,
+ int partitionId,
CatalogIndexDescriptor indexDescriptor
) {
- IndexStorage indexStorage = mvTableStorage.getIndex(replicaId.partitionId(), indexDescriptor.id());
+ IndexStorage indexStorage = mvTableStorage.getIndex(partitionId, indexDescriptor.id());
- assert indexStorage != null : "replicaId=" + replicaId + ", indexId=" + indexDescriptor.id();
+ assert indexStorage != null : "Index storage is missing [partitionId=" + partitionId + ", indexId=" + indexDescriptor.id() + "].";
return indexStorage;
}
diff --git a/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuildTask.java b/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuildTask.java
index aaaefe210b0..bca1fc16f14 100644
--- a/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuildTask.java
+++ b/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuildTask.java
@@ -20,7 +20,9 @@ package org.apache.ignite.internal.index;
import static java.util.concurrent.CompletableFuture.failedFuture;
import static java.util.concurrent.CompletableFuture.supplyAsync;
import static java.util.stream.Collectors.toList;
+import static org.apache.ignite.internal.lang.IgniteSystemProperties.enabledColocation;
import static org.apache.ignite.internal.replicator.message.ReplicaMessageUtils.toTablePartitionIdMessage;
+import static org.apache.ignite.internal.replicator.message.ReplicaMessageUtils.toZonePartitionIdMessage;
import static org.apache.ignite.internal.util.CompletableFutures.nullCompletedFuture;
import static org.apache.ignite.internal.util.ExceptionUtils.unwrapCause;
@@ -37,9 +39,11 @@ import org.apache.ignite.internal.partition.replicator.network.PartitionReplicat
import org.apache.ignite.internal.partition.replicator.network.replication.BuildIndexReplicaRequest;
import org.apache.ignite.internal.replicator.ReplicaService;
import org.apache.ignite.internal.replicator.TablePartitionId;
+import org.apache.ignite.internal.replicator.ZonePartitionId;
import org.apache.ignite.internal.replicator.exception.PrimaryReplicaMissException;
import org.apache.ignite.internal.replicator.exception.ReplicationTimeoutException;
import org.apache.ignite.internal.replicator.message.ReplicaMessagesFactory;
+import org.apache.ignite.internal.replicator.message.ReplicationGroupIdMessage;
import org.apache.ignite.internal.storage.MvPartitionStorage;
import org.apache.ignite.internal.storage.RowId;
import org.apache.ignite.internal.storage.index.IndexStorage;
@@ -219,10 +223,13 @@ class IndexBuildTask {
private BuildIndexReplicaRequest createBuildIndexReplicaRequest(List<RowId> rowIds) {
boolean finish = rowIds.size() < batchSize;
- TablePartitionId tablePartitionId = new TablePartitionId(taskId.getTableId(), taskId.getPartitionId());
+ ReplicationGroupIdMessage groupIdMessage = enabledColocation()
+ ? toZonePartitionIdMessage(REPLICA_MESSAGES_FACTORY, new ZonePartitionId(taskId.getZoneId(), taskId.getPartitionId()))
+ : toTablePartitionIdMessage(REPLICA_MESSAGES_FACTORY, new TablePartitionId(taskId.getTableId(), taskId.getPartitionId()));
return PARTITION_REPLICATION_MESSAGES_FACTORY.buildIndexReplicaRequest()
- .groupId(toTablePartitionIdMessage(REPLICA_MESSAGES_FACTORY, tablePartitionId))
+ .groupId(groupIdMessage)
+ .tableId(taskId.getTableId())
.indexId(taskId.getIndexId())
.rowIds(rowIds.stream().map(RowId::uuid).collect(toList()))
.finish(finish)
@@ -240,8 +247,8 @@ class IndexBuildTask {
private String createCommonIndexInfo() {
return IgniteStringFormatter.format(
- "tableId={}, partitionId={}, indexId={}",
- taskId.getTableId(), taskId.getPartitionId(), taskId.getIndexId()
+ "zoneId = {}, tableId={}, partitionId={}, indexId={}",
+ taskId.getZoneId(), taskId.getTableId(), taskId.getPartitionId(), taskId.getIndexId()
);
}
diff --git a/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuildTaskId.java b/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuildTaskId.java
index 85961371605..45862c0bc3d 100644
--- a/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuildTaskId.java
+++ b/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuildTaskId.java
@@ -23,18 +23,33 @@ import org.apache.ignite.internal.tostring.S;
* {@link IndexBuildTask} ID.
*/
class IndexBuildTaskId {
+ private final int zoneId;
+
private final int tableId;
private final int partitionId;
private final int indexId;
- IndexBuildTaskId(int tableId, int partitionId, int indexId) {
+ /**
+ * Creates a new index building task.
+ *
+ * @param zoneId Distribution zone ID.
+ * @param tableId Table ID.
+ * @param partitionId Partition ID.
+ * @param indexId Index ID.
+ */
+ IndexBuildTaskId(int zoneId, int tableId, int partitionId, int indexId) {
+ this.zoneId = zoneId;
this.tableId = tableId;
this.partitionId = partitionId;
this.indexId = indexId;
}
+ public int getZoneId() {
+ return zoneId;
+ }
+
public int getTableId() {
return tableId;
}
@@ -58,12 +73,13 @@ class IndexBuildTaskId {
IndexBuildTaskId that = (IndexBuildTaskId) o;
- return partitionId == that.partitionId && tableId == that.tableId && indexId == that.indexId;
+ return partitionId == that.partitionId && tableId == that.tableId && zoneId == that.zoneId && indexId == that.indexId;
}
@Override
public int hashCode() {
- int result = tableId;
+ int result = zoneId;
+ result = 31 * result + tableId;
result = 31 * result + partitionId;
result = 31 * result + indexId;
return result;
diff --git a/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuilder.java b/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuilder.java
index 64370461217..0265c1dd3ba 100644
--- a/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuilder.java
+++ b/modules/index/src/main/java/org/apache/ignite/internal/index/IndexBuilder.java
@@ -90,6 +90,7 @@ class IndexBuilder implements ManuallyCloseable {
* will be notified.</li>
* </ul>
*
+ * @param zoneId Distribution zone ID.
* @param tableId Table ID.
* @param partitionId Partition ID.
* @param indexId Index ID.
@@ -100,6 +101,7 @@ class IndexBuilder implements ManuallyCloseable {
* to the replica.
*/
public void scheduleBuildIndex(
+ int zoneId,
int tableId,
int partitionId,
int indexId,
@@ -117,7 +119,7 @@ class IndexBuilder implements ManuallyCloseable {
return;
}
- IndexBuildTaskId taskId = new IndexBuildTaskId(tableId, partitionId, indexId);
+ var taskId = new IndexBuildTaskId(zoneId, tableId, partitionId, indexId);
IndexBuildTask newTask = new IndexBuildTask(
taskId,
@@ -151,6 +153,7 @@ class IndexBuilder implements ManuallyCloseable {
* notified.</li>
* </ul>
*
+ * @param zoneId Distribution zone ID.
* @param tableId Table ID.
* @param partitionId Partition ID.
* @param indexId Index ID.
@@ -161,6 +164,7 @@ class IndexBuilder implements ManuallyCloseable {
* message goes to the replica.
*/
public void scheduleBuildIndexAfterDisasterRecovery(
+ int zoneId,
int tableId,
int partitionId,
int indexId,
@@ -174,7 +178,7 @@ class IndexBuilder implements ManuallyCloseable {
return;
}
- IndexBuildTaskId taskId = new IndexBuildTaskId(tableId, partitionId, indexId);
+ var taskId = new IndexBuildTaskId(zoneId, tableId, partitionId, indexId);
IndexBuildTask newTask = new IndexBuildTask(
taskId,
@@ -195,30 +199,24 @@ class IndexBuilder implements ManuallyCloseable {
}
/**
- * Stops index building if it is in progress.
+ * Stops building all indexes (for a table partition) if they are in progress.
*
* @param tableId Table ID.
* @param partitionId Partition ID.
- * @param indexId Index ID.
*/
- public void stopBuildIndex(int tableId, int partitionId, int indexId) {
- inBusyLockSafe(busyLock, () -> {
- IndexBuildTask removed = indexBuildTaskById.remove(new IndexBuildTaskId(tableId, partitionId, indexId));
-
- if (removed != null) {
- removed.stop();
- }
- });
+ // TODO https://issues.apache.org/jira/browse/IGNITE-22522 Remove.
+ public void stopBuildingTableIndexes(int tableId, int partitionId) {
+ stopBuildingIndexes(taskId -> tableId == taskId.getTableId() && partitionId == taskId.getPartitionId());
}
/**
- * Stops building all indexes (for a table partition) if they are in progress.
+ * Stops building indexes for the given distribution zone and partition if they are in progress.
*
- * @param tableId Table ID.
+ * @param zoneId Zone ID.
* @param partitionId Partition ID.
*/
- public void stopBuildingIndexes(int tableId, int partitionId) {
- stopBuildingIndexes(taskId -> tableId == taskId.getTableId() && partitionId == taskId.getPartitionId());
+ public void stopBuildingZoneIndexes(int zoneId, int partitionId) {
+ stopBuildingIndexes(taskId -> zoneId == taskId.getZoneId() && partitionId == taskId.getPartitionId());
}
/**
diff --git a/modules/index/src/main/java/org/apache/ignite/internal/index/IndexManager.java b/modules/index/src/main/java/org/apache/ignite/internal/index/IndexManager.java
index 822e88ddd2b..3f4b291534a 100644
--- a/modules/index/src/main/java/org/apache/ignite/internal/index/IndexManager.java
+++ b/modules/index/src/main/java/org/apache/ignite/internal/index/IndexManager.java
@@ -27,6 +27,7 @@ import static org.apache.ignite.internal.table.distributed.index.IndexUtils.regi
import static org.apache.ignite.internal.util.CompletableFutures.nullCompletedFuture;
import static org.apache.ignite.internal.util.IgniteUtils.inBusyLock;
import static org.apache.ignite.internal.util.IgniteUtils.inBusyLockAsync;
+import static org.apache.ignite.lang.ErrorGroups.Common.INTERNAL_ERR;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@@ -44,6 +45,7 @@ import org.apache.ignite.internal.catalog.events.RemoveIndexEventParameters;
import org.apache.ignite.internal.causality.IncrementalVersionedValue;
import org.apache.ignite.internal.causality.RevisionListenerRegistry;
import org.apache.ignite.internal.hlc.HybridTimestamp;
+import org.apache.ignite.internal.lang.IgniteInternalException;
import org.apache.ignite.internal.lang.NodeStoppingException;
import org.apache.ignite.internal.logger.IgniteLogger;
import org.apache.ignite.internal.logger.Loggers;
@@ -61,7 +63,6 @@ import org.apache.ignite.internal.table.TableViewInternal;
import org.apache.ignite.internal.table.distributed.PartitionSet;
import org.apache.ignite.internal.table.distributed.TableManager;
import org.apache.ignite.internal.util.IgniteSpinBusyLock;
-import org.jetbrains.annotations.Nullable;
/**
* An Ignite component that is responsible for handling index-related commands like CREATE or DROP
@@ -169,11 +170,30 @@ public class IndexManager implements IgniteComponent {
*
* @param causalityToken Causality token.
* @param tableId Table ID.
- * @return Future with multi-version table storage, completes with {@code null} if the table does not exist according to the passed
- * parameters.
+ * @return Future with multi-version table storage, completes with an exception if the table or storage does not exist
+ * according to the passed parameters.
*/
- CompletableFuture<@Nullable MvTableStorage> getMvTableStorage(long causalityToken, int tableId) {
- return tableManager.tableAsync(causalityToken, tableId).thenApply(table -> table == null ? null : table.internalTable().storage());
+ CompletableFuture<MvTableStorage> getMvTableStorage(long causalityToken, int tableId) {
+ return tableManager
+ .tableAsync(causalityToken, tableId)
+ .thenApply(table -> {
+ if (table == null) {
+ throw new IgniteInternalException(
+ INTERNAL_ERR,
+ "Table does not exist [tableId = {}]",
+ tableId);
+ }
+
+ MvTableStorage storage = table.internalTable().storage();
+ if (storage == null) {
+ throw new IgniteInternalException(
+ INTERNAL_ERR,
+ "Table storage for the specified table cannot be null [tableId = {}]",
+ tableId);
+ }
+
+ return storage;
+ });
}
private CompletableFuture<Boolean> onIndexCreate(CreateIndexEventParameters parameters) {
diff --git a/modules/index/src/test/java/org/apache/ignite/internal/index/IndexAvailabilityControllerTest.java b/modules/index/src/test/java/org/apache/ignite/internal/index/IndexAvailabilityControllerTest.java
index a7ee4f11b35..2ca13a50dee 100644
--- a/modules/index/src/test/java/org/apache/ignite/internal/index/IndexAvailabilityControllerTest.java
+++ b/modules/index/src/test/java/org/apache/ignite/internal/index/IndexAvailabilityControllerTest.java
@@ -362,6 +362,10 @@ public class IndexAvailabilityControllerTest extends BaseIgniteAbstractTest {
return TableTestUtils.getTableIdStrict(catalogManager, tableName, clock.nowLong());
}
+ private int zoneIdByTableName(String tableName) {
+ return TableTestUtils.getZoneIdByTableNameStrict(catalogManager, tableName, clock.nowLong());
+ }
+
private boolean isIndexAvailable(String indexName) {
return TableTestUtils.getIndexStrict(catalogManager, indexName, clock.nowLong()).status() == AVAILABLE;
}
@@ -399,6 +403,7 @@ public class IndexAvailabilityControllerTest extends BaseIgniteAbstractTest {
});
indexBuilder.scheduleBuildIndex(
+ zoneIdByTableName(TABLE_NAME),
tableId(TABLE_NAME),
partitionId,
indexId,
diff --git a/modules/index/src/test/java/org/apache/ignite/internal/index/IndexBuildControllerTest.java b/modules/index/src/test/java/org/apache/ignite/internal/index/IndexBuildControllerTest.java
index dd7c51c0ef2..713b66aaea8 100644
--- a/modules/index/src/test/java/org/apache/ignite/internal/index/IndexBuildControllerTest.java
+++ b/modules/index/src/test/java/org/apache/ignite/internal/index/IndexBuildControllerTest.java
@@ -29,12 +29,12 @@ import static org.apache.ignite.internal.index.TestIndexManagementUtils.NODE_NAM
import static org.apache.ignite.internal.index.TestIndexManagementUtils.PK_INDEX_NAME;
import static org.apache.ignite.internal.index.TestIndexManagementUtils.TABLE_NAME;
import static org.apache.ignite.internal.index.TestIndexManagementUtils.createTable;
+import static org.apache.ignite.internal.lang.IgniteSystemProperties.enabledColocation;
import static org.apache.ignite.internal.table.TableTestUtils.createHashIndex;
import static org.apache.ignite.internal.table.TableTestUtils.getIndexIdStrict;
import static org.apache.ignite.internal.table.TableTestUtils.getTableIdStrict;
-import static org.apache.ignite.internal.testframework.IgniteTestUtils.assertThrows;
+import static org.apache.ignite.internal.table.TableTestUtils.getZoneIdByTableNameStrict;
import static org.apache.ignite.internal.testframework.matchers.CompletableFutureMatcher.willCompleteSuccessfully;
-import static org.apache.ignite.internal.util.CompletableFutures.nullCompletedFuture;
import static org.apache.ignite.internal.util.IgniteUtils.closeAll;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
@@ -50,8 +50,6 @@ import static org.mockito.Mockito.when;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
import org.apache.ignite.internal.catalog.CatalogManager;
import org.apache.ignite.internal.catalog.commands.MakeIndexAvailableCommand;
import org.apache.ignite.internal.catalog.commands.StartBuildingIndexCommand;
@@ -65,7 +63,9 @@ import org.apache.ignite.internal.network.ClusterService;
import org.apache.ignite.internal.network.TopologyService;
import org.apache.ignite.internal.placementdriver.ReplicaMeta;
import org.apache.ignite.internal.placementdriver.leases.Lease;
+import org.apache.ignite.internal.replicator.ReplicationGroupId;
import org.apache.ignite.internal.replicator.TablePartitionId;
+import org.apache.ignite.internal.replicator.ZonePartitionId;
import org.apache.ignite.internal.sql.SqlCommon;
import org.apache.ignite.internal.storage.MvPartitionStorage;
import org.apache.ignite.internal.storage.engine.MvTableStorage;
@@ -146,6 +146,7 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
createIndex(INDEX_NAME);
verify(indexBuilder, never()).scheduleBuildIndex(
+ eq(zoneId()),
eq(tableId()),
eq(PARTITION_ID),
eq(indexId(INDEX_NAME)),
@@ -156,6 +157,7 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
);
verify(indexBuilder, never()).scheduleBuildIndexAfterDisasterRecovery(
+ eq(zoneId()),
eq(tableId()),
eq(PARTITION_ID),
eq(indexId(INDEX_NAME)),
@@ -177,6 +179,7 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
startBuildingIndex(indexId(INDEX_NAME));
verify(indexBuilder).scheduleBuildIndex(
+ eq(zoneId()),
eq(tableId()),
eq(PARTITION_ID),
eq(indexId(INDEX_NAME)),
@@ -187,6 +190,7 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
);
verify(indexBuilder, never()).scheduleBuildIndexAfterDisasterRecovery(
+ eq(zoneId()),
eq(tableId()),
eq(PARTITION_ID),
eq(indexId(INDEX_NAME)),
@@ -197,22 +201,6 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
);
}
- @Test
- void testExceptionIsThrownOnIndexBuildingWhenStorageIsNull() {
- setPrimaryReplicaWhichExpiresInOneSecond(PARTITION_ID, NODE_NAME, NODE_ID, clock.now());
-
- createIndex(INDEX_NAME);
-
- when(indexManager.getMvTableStorage(anyLong(), anyInt())).thenReturn(nullCompletedFuture());
-
- assertThrows(
- ExecutionException.class,
- () -> catalogManager.execute(StartBuildingIndexCommand.builder().indexId(indexId(INDEX_NAME)).build())
- .get(10_000, TimeUnit.MILLISECONDS),
- "Table storage for the specified table cannot be null"
- );
- }
-
@Test
void testStartBuildIndexesOnPrimaryReplicaElected() {
createIndex(INDEX_NAME);
@@ -222,6 +210,7 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
setPrimaryReplicaWhichExpiresInOneSecond(PARTITION_ID, NODE_NAME, NODE_ID, clock.now());
verify(indexBuilder).scheduleBuildIndex(
+ eq(zoneId()),
eq(tableId()),
eq(PARTITION_ID),
eq(indexId(INDEX_NAME)),
@@ -232,6 +221,7 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
);
verify(indexBuilder).scheduleBuildIndexAfterDisasterRecovery(
+ eq(zoneId()),
eq(tableId()),
eq(PARTITION_ID),
eq(indexId(PK_INDEX_NAME)),
@@ -242,20 +232,6 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
);
}
- @Test
- void testExceptionIsThrownOnPrimaryReplicaElectedWhenStorageIsNull() {
- when(indexManager.getMvTableStorage(anyLong(), anyInt())).thenReturn(nullCompletedFuture());
-
- CompletableFuture<ReplicaMeta> replicaMetaFuture = completedFuture(replicaMetaForOneSecond(NODE_NAME, NODE_ID, clock.now()));
-
- assertThrows(
- ExecutionException.class,
- () -> placementDriver.setPrimaryReplicaMeta(0, replicaId(PARTITION_ID), replicaMetaFuture)
- .get(10_000, TimeUnit.MILLISECONDS),
- "Table storage for the specified table cannot be null"
- );
- }
-
@Test
void testNotStartBuildPkIndexesForNewTable() {
setPrimaryReplicaWhichExpiresInOneSecond(PARTITION_ID, NODE_NAME, NODE_ID, clock.now());
@@ -265,6 +241,7 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
createTable(catalogManager, tableName, COLUMN_NAME);
verify(indexBuilder, never()).scheduleBuildIndex(
+ eq(zoneId()),
eq(tableId(tableName)),
eq(PARTITION_ID),
eq(indexId(pkIndexName(tableName))),
@@ -275,6 +252,7 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
);
verify(indexBuilder, never()).scheduleBuildIndexAfterDisasterRecovery(
+ eq(zoneId()),
eq(tableId(tableName)),
eq(PARTITION_ID),
eq(indexId(pkIndexName(tableName))),
@@ -301,7 +279,11 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
setPrimaryReplicaWhichExpiresInOneSecond(PARTITION_ID, NODE_NAME, NODE_ID, clock.now());
setPrimaryReplicaWhichExpiresInOneSecond(PARTITION_ID, NODE_NAME + "_other", randomUUID(), clock.now());
- verify(indexBuilder).stopBuildingIndexes(tableId(), PARTITION_ID);
+ if (enabledColocation()) {
+ verify(indexBuilder).stopBuildingZoneIndexes(zoneId(), PARTITION_ID);
+ } else {
+ verify(indexBuilder).stopBuildingTableIndexes(tableId(), PARTITION_ID);
+ }
}
@Test
@@ -317,6 +299,7 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
setPrimaryReplicaWhichExpiresInOneSecond(PARTITION_ID, NODE_NAME, NODE_ID, clock.now());
verify(indexBuilder, never()).scheduleBuildIndex(
+ eq(zoneId()),
eq(tableId()),
eq(PARTITION_ID),
anyInt(),
@@ -327,6 +310,7 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
);
verify(indexBuilder).scheduleBuildIndexAfterDisasterRecovery(
+ eq(zoneId()),
eq(tableId()),
eq(PARTITION_ID),
eq(indexId0),
@@ -372,12 +356,20 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
return getTableIdStrict(catalogManager, tableName, clock.nowLong());
}
+ private int zoneId() {
+ return getZoneIdByTableNameStrict(catalogManager, TABLE_NAME, clock.nowLong());
+ }
+
private int indexId(String indexName) {
return getIndexIdStrict(catalogManager, indexName, clock.nowLong());
}
- private TablePartitionId replicaId(int partitionId) {
- return new TablePartitionId(tableId(), partitionId);
+ private ReplicationGroupId replicaId(int partitionId) {
+ if (enabledColocation()) {
+ return new ZonePartitionId(zoneId(), partitionId);
+ } else {
+ return new TablePartitionId(tableId(), partitionId);
+ }
}
private ReplicaMeta replicaMetaForOneSecond(String leaseholder, UUID leaseholderId, HybridTimestamp startTime) {
@@ -386,7 +378,7 @@ public class IndexBuildControllerTest extends BaseIgniteAbstractTest {
leaseholderId,
startTime,
startTime.addPhysicalTime(1_000),
- new TablePartitionId(tableId(), PARTITION_ID)
+ enabledColocation() ? new ZonePartitionId(zoneId(), PARTITION_ID) : new TablePartitionId(tableId(), PARTITION_ID)
);
}
}
diff --git a/modules/index/src/test/java/org/apache/ignite/internal/index/IndexBuilderTest.java b/modules/index/src/test/java/org/apache/ignite/internal/index/IndexBuilderTest.java
index e25dcdf964d..2066f04a8af 100644
--- a/modules/index/src/test/java/org/apache/ignite/internal/index/IndexBuilderTest.java
+++ b/modules/index/src/test/java/org/apache/ignite/internal/index/IndexBuilderTest.java
@@ -56,6 +56,8 @@ import org.junit.jupiter.api.Test;
/** For {@link IndexBuilder} testing. */
public class IndexBuilderTest extends BaseIgniteAbstractTest {
+ private static final int ZONE_ID = 0;
+
private static final int TABLE_ID = 1;
private static final int INDEX_ID = 2;
@@ -82,7 +84,7 @@ public class IndexBuilderTest extends BaseIgniteAbstractTest {
void testIndexBuildCompletionListener() {
CompletableFuture<Void> listenCompletionIndexBuildingFuture = listenCompletionIndexBuilding(INDEX_ID, TABLE_ID, PARTITION_ID);
- scheduleBuildIndex(INDEX_ID, TABLE_ID, PARTITION_ID, List.of(rowId(PARTITION_ID)));
+ scheduleBuildIndex(INDEX_ID, ZONE_ID, TABLE_ID, PARTITION_ID, List.of(rowId(PARTITION_ID)));
assertThat(listenCompletionIndexBuildingFuture, willCompleteSuccessfully());
}
@@ -101,7 +103,7 @@ public class IndexBuilderTest extends BaseIgniteAbstractTest {
indexBuilder.listen(listener);
indexBuilder.stopListen(listener);
- scheduleBuildIndex(INDEX_ID, TABLE_ID, PARTITION_ID, List.of(rowId(PARTITION_ID)));
+ scheduleBuildIndex(INDEX_ID, ZONE_ID, TABLE_ID, PARTITION_ID, List.of(rowId(PARTITION_ID)));
assertThat(invokeListenerFuture, willTimeoutFast());
}
@@ -118,7 +120,7 @@ public class IndexBuilderTest extends BaseIgniteAbstractTest {
CompletableFuture<Void> awaitSecondInvokeForReplicaService = awaitSecondInvokeForReplicaService(secondInvokeReplicaServiceFuture);
- scheduleBuildIndex(INDEX_ID, TABLE_ID, PARTITION_ID, nextRowIdsToBuild);
+ scheduleBuildIndex(INDEX_ID, ZONE_ID, TABLE_ID, PARTITION_ID, nextRowIdsToBuild);
assertThat(awaitSecondInvokeForReplicaService, willCompleteSuccessfully());
@@ -133,7 +135,7 @@ public class IndexBuilderTest extends BaseIgniteAbstractTest {
void testIndexBuildCompletionListenerForAlreadyBuiltIndex() {
CompletableFuture<Void> listenCompletionIndexBuildingFuture = listenCompletionIndexBuilding(INDEX_ID, TABLE_ID, PARTITION_ID);
- scheduleBuildIndex(INDEX_ID, TABLE_ID, PARTITION_ID, List.of());
+ scheduleBuildIndex(INDEX_ID, ZONE_ID, TABLE_ID, PARTITION_ID, List.of());
assertThat(listenCompletionIndexBuildingFuture, willCompleteSuccessfully());
}
@@ -146,7 +148,7 @@ public class IndexBuilderTest extends BaseIgniteAbstractTest {
.thenReturn(failedFuture(new ReplicationTimeoutException(new TablePartitionId(TABLE_ID, PARTITION_ID))))
.thenReturn(nullCompletedFuture());
- scheduleBuildIndex(INDEX_ID, TABLE_ID, PARTITION_ID, List.of(rowId(PARTITION_ID)));
+ scheduleBuildIndex(INDEX_ID, ZONE_ID, TABLE_ID, PARTITION_ID, List.of(rowId(PARTITION_ID)));
assertThat(listenCompletionIndexBuildingFuture, willCompleteSuccessfully());
@@ -158,13 +160,14 @@ public class IndexBuilderTest extends BaseIgniteAbstractTest {
CompletableFuture<Void> listenCompletionIndexBuildingAfterDisasterRecoveryFuture =
listenCompletionIndexBuildingAfterDisasterRecovery(INDEX_ID, TABLE_ID, PARTITION_ID);
- scheduleBuildIndexAfterDisasterRecovery(INDEX_ID, TABLE_ID, PARTITION_ID, List.of(rowId(PARTITION_ID)));
+ scheduleBuildIndexAfterDisasterRecovery(INDEX_ID, ZONE_ID, TABLE_ID, PARTITION_ID, List.of(rowId(PARTITION_ID)));
assertThat(listenCompletionIndexBuildingAfterDisasterRecoveryFuture, willCompleteSuccessfully());
}
- private void scheduleBuildIndex(int indexId, int tableId, int partitionId, Collection<RowId> nextRowIdsToBuild) {
+ private void scheduleBuildIndex(int indexId, int zoneId, int tableId, int partitionId, Collection<RowId> nextRowIdsToBuild) {
indexBuilder.scheduleBuildIndex(
+ zoneId,
tableId,
partitionId,
indexId,
@@ -175,8 +178,15 @@ public class IndexBuilderTest extends BaseIgniteAbstractTest {
);
}
- private void scheduleBuildIndexAfterDisasterRecovery(int indexId, int tableId, int partitionId, Collection<RowId> nextRowIdsToBuild) {
+ private void scheduleBuildIndexAfterDisasterRecovery(
+ int indexId,
+ int zoneId,
+ int tableId,
+ int partitionId,
+ Collection<RowId> nextRowIdsToBuild
+ ) {
indexBuilder.scheduleBuildIndexAfterDisasterRecovery(
+ zoneId,
tableId,
partitionId,
indexId,
diff --git a/modules/index/src/test/java/org/apache/ignite/internal/index/TestPlacementDriver.java b/modules/index/src/test/java/org/apache/ignite/internal/index/TestPlacementDriver.java
index 344ef5a0e20..d2a08a2c57f 100644
--- a/modules/index/src/test/java/org/apache/ignite/internal/index/TestPlacementDriver.java
+++ b/modules/index/src/test/java/org/apache/ignite/internal/index/TestPlacementDriver.java
@@ -32,7 +32,6 @@ import org.apache.ignite.internal.placementdriver.ReplicaMeta;
import org.apache.ignite.internal.placementdriver.event.PrimaryReplicaEvent;
import org.apache.ignite.internal.placementdriver.event.PrimaryReplicaEventParameters;
import org.apache.ignite.internal.replicator.ReplicationGroupId;
-import org.apache.ignite.internal.replicator.TablePartitionId;
import org.jetbrains.annotations.Nullable;
/** Implementation for tests. */
@@ -74,7 +73,7 @@ class TestPlacementDriver extends AbstractEventProducer<PrimaryReplicaEvent, Pri
CompletableFuture<Void> setPrimaryReplicaMeta(
long causalityToken,
- TablePartitionId replicaId,
+ ReplicationGroupId replicaId,
CompletableFuture<ReplicaMeta> replicaMetaFuture
) {
primaryReplicaMetaFutureById.put(replicaId, replicaMetaFuture);
diff --git a/modules/partition-replicator/src/integrationTest/java/org/apache/ignite/internal/partition/replicator/ItBuildIndexTest.java b/modules/partition-replicator/src/integrationTest/java/org/apache/ignite/internal/partition/replicator/ItBuildIndexTest.java
new file mode 100644
index 00000000000..fb6011b1be6
--- /dev/null
+++ b/modules/partition-replicator/src/integrationTest/java/org/apache/ignite/internal/partition/replicator/ItBuildIndexTest.java
@@ -0,0 +1,137 @@
+/*
+ * 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.partition.replicator;
+
+import static org.apache.ignite.internal.catalog.descriptors.CatalogIndexStatus.AVAILABLE;
+import static org.apache.ignite.internal.sql.SqlCommon.DEFAULT_SCHEMA_NAME;
+import static org.apache.ignite.internal.testframework.IgniteTestUtils.waitForCondition;
+import static org.apache.ignite.sql.ColumnType.DOUBLE;
+import static org.apache.ignite.sql.ColumnType.INT32;
+import static org.apache.ignite.sql.ColumnType.INT64;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import org.apache.ignite.internal.catalog.CatalogManager;
+import org.apache.ignite.internal.catalog.commands.ColumnParams;
+import org.apache.ignite.internal.catalog.descriptors.CatalogIndexDescriptor;
+import org.apache.ignite.internal.hlc.HybridClock;
+import org.apache.ignite.internal.index.message.IndexMessageGroup;
+import org.apache.ignite.internal.index.message.IndexMessagesFactory;
+import org.apache.ignite.internal.index.message.IsNodeFinishedRwTransactionsStartedBeforeRequest;
+import org.apache.ignite.internal.partition.replicator.fixtures.Node;
+import org.apache.ignite.internal.table.TableTestUtils;
+import org.apache.ignite.internal.table.TableViewInternal;
+import org.apache.ignite.table.KeyValueView;
+import org.apache.ignite.table.Tuple;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+// TODO: https://issues.apache.org/jira/browse/IGNITE-22522 remove this test after the switching to zone-based replication
+/**
+ * Tests building indices for colocation track.
+ */
+@Timeout(60)
+public class ItBuildIndexTest extends ItAbstractColocationTest {
+ private static final IndexMessagesFactory FACTORY = new IndexMessagesFactory();
+
+ @Test
+ public void testBuildIndex() throws Exception {
+ // Prepare a single node cluster.
+ startCluster(1);
+ Node node = getNode(0);
+
+ String zoneName = "test-zone";
+ createZone(node, zoneName, 1, 1);
+
+ String tableName = "TEST_TABLE";
+ createCustomTable(node, zoneName, tableName);
+ int tableId = TableTestUtils.getTableId(node.catalogManager, tableName, node.hybridClock.nowLong());
+
+ // Test node does not create IndexNodeFinishedRwTransactionsChecker, so the following code is needed to unblock index building.
+ // It's easier than creating a real service with all its dependencies.
+ node.clusterService.messagingService().addMessageHandler(
+ IndexMessageGroup.class,
+ (message, sender, correlationId) -> {
+ if (message instanceof IsNodeFinishedRwTransactionsStartedBeforeRequest) {
+ node.clusterService.messagingService().respond(
+ sender,
+ FACTORY.isNodeFinishedRwTransactionsStartedBeforeResponse().finished(true).build(),
+ correlationId
+ );
+ }
+ });
+
+ TableViewInternal tableViewInternal = node.tableManager.table(tableId);
+ KeyValueView<Tuple, Tuple> tableView = tableViewInternal.keyValueView();
+
+ node.transactions().runInTransaction(tx -> {
+ Tuple key = Tuple.create().set("KEY", 1L);
+ Tuple value = Tuple.create().set("VAL", 1).set("DOUBLEVAL", 1.0);
+ tableView.putAll(tx, Map.of(key, value));
+ });
+
+ // This async transaction is needed to update safe time, just because the idle safe time propagation is not implemented yet.
+ // https://issues.apache.org/jira/browse/IGNITE-22620
+ CompletableFuture.runAsync(() -> {
+ try {
+ Thread.sleep(1_000);
+ node.transactions().runInTransaction(tx -> {
+ Tuple key = Tuple.create().set("KEY", 1L);
+ Tuple value = Tuple.create().set("VAL", 1).set("DOUBLEVAL", 1.0);
+ tableView.putAll(tx, Map.of(key, value));
+ });
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ node.sql().execute(null, "CREATE INDEX TEST_INDEX ON TEST_TABLE (DOUBLEVAL)").close();
+
+ assertTrue(waitForCondition(() -> isIndexAvailable(node, "TEST_INDEX"), 10_000L));
+ }
+
+ private static void createCustomTable(Node node, String zoneName, String tableName) {
+ node.waitForMetadataCompletenessAtNow();
+
+ TableTestUtils.createTable(
+ node.catalogManager,
+ DEFAULT_SCHEMA_NAME,
+ zoneName,
+ tableName,
+ List.of(
+ ColumnParams.builder().name("KEY").type(INT64).build(),
+ ColumnParams.builder().name("VAL").type(INT32).nullable(true).build(),
+ ColumnParams.builder().name("DOUBLEVAL").type(DOUBLE).build()
+ ),
+ List.of("KEY")
+ );
+ }
+
+ private static boolean isIndexAvailable(Node node, String indexName) {
+ CatalogManager catalogManager = node.catalogManager;
+ HybridClock clock = node.hybridClock;
+
+ CatalogIndexDescriptor indexDescriptor = catalogManager
+ .activeCatalog(clock.nowLong())
+ .aliveIndex(DEFAULT_SCHEMA_NAME, indexName);
+
+ return indexDescriptor != null && indexDescriptor.status() == AVAILABLE;
+ }
+}
diff --git a/modules/partition-replicator/src/integrationTest/java/org/apache/ignite/internal/partition/replicator/fixtures/Node.java b/modules/partition-replicator/src/integrationTest/java/org/apache/ignite/internal/partition/replicator/fixtures/Node.java
index 75267f44bce..2bb5a77f030 100644
--- a/modules/partition-replicator/src/integrationTest/java/org/apache/ignite/internal/partition/replicator/fixtures/Node.java
+++ b/modules/partition-replicator/src/integrationTest/java/org/apache/ignite/internal/partition/replicator/fixtures/Node.java
@@ -88,6 +88,7 @@ import org.apache.ignite.internal.hlc.HybridClock;
import org.apache.ignite.internal.hlc.HybridClockImpl;
import org.apache.ignite.internal.hlc.HybridTimestamp;
import org.apache.ignite.internal.hlc.HybridTimestampTracker;
+import org.apache.ignite.internal.index.IndexBuildingManager;
import org.apache.ignite.internal.index.IndexManager;
import org.apache.ignite.internal.lang.IgniteInternalException;
import org.apache.ignite.internal.logger.IgniteLogger;
@@ -289,6 +290,9 @@ public class Node {
private final SqlQueryProcessor sqlQueryProcessor;
+ /** Index building manager. */
+ private final IndexBuildingManager indexBuildingManager;
+
/** Interceptor for {@link MetaStorageManager#invoke} calls. */
@FunctionalInterface
public interface InvokeInterceptor {
@@ -763,6 +767,19 @@ public class Node {
lowWatermark
);
+ indexBuildingManager = new IndexBuildingManager(
+ name,
+ replicaSvc,
+ catalogManager,
+ metaStorageManager,
+ indexManager,
+ indexMetaStorage,
+ placementDriverManager.placementDriver(),
+ clusterService,
+ logicalTopologyService,
+ clockService
+ );
+
systemViewManager = new SystemViewManagerImpl(name, catalogManager);
sqlQueryProcessor = new SqlQueryProcessor(
@@ -844,6 +861,7 @@ public class Node {
partitionReplicaLifecycleManager,
tableManager,
indexManager,
+ indexBuildingManager,
resourceVacuumManager,
systemViewManager,
sqlQueryProcessor
diff --git a/modules/partition-replicator/src/main/java/org/apache/ignite/internal/partition/replicator/network/command/BuildIndexCommand.java b/modules/partition-replicator/src/main/java/org/apache/ignite/internal/partition/replicator/network/command/BuildIndexCommand.java
index a8d14c7642b..1bc6215f8c5 100644
--- a/modules/partition-replicator/src/main/java/org/apache/ignite/internal/partition/replicator/network/command/BuildIndexCommand.java
+++ b/modules/partition-replicator/src/main/java/org/apache/ignite/internal/partition/replicator/network/command/BuildIndexCommand.java
@@ -28,7 +28,7 @@ import org.apache.ignite.internal.raft.WriteCommand;
/** State machine command to build a table index. */
@Transferable(PartitionReplicationMessageGroup.Commands.BUILD_INDEX)
-public interface BuildIndexCommand extends WriteCommand, CatalogVersionAware {
+public interface BuildIndexCommand extends WriteCommand, CatalogVersionAware, TableAwareCommand {
/** Returns index ID. */
int indexId();
diff --git a/modules/partition-replicator/src/main/java/org/apache/ignite/internal/partition/replicator/network/replication/BuildIndexReplicaRequest.java b/modules/partition-replicator/src/main/java/org/apache/ignite/internal/partition/replicator/network/replication/BuildIndexReplicaRequest.java
index 35b2e5617b8..71dee513a9e 100644
--- a/modules/partition-replicator/src/main/java/org/apache/ignite/internal/partition/replicator/network/replication/BuildIndexReplicaRequest.java
+++ b/modules/partition-replicator/src/main/java/org/apache/ignite/internal/partition/replicator/network/replication/BuildIndexReplicaRequest.java
@@ -23,6 +23,7 @@ import org.apache.ignite.internal.network.annotations.Transferable;
import org.apache.ignite.internal.partition.replicator.network.PartitionReplicationMessageGroup;
import org.apache.ignite.internal.replicator.exception.PrimaryReplicaMissException;
import org.apache.ignite.internal.replicator.message.PrimaryReplicaRequest;
+import org.apache.ignite.internal.replicator.message.TableAware;
/**
* Replica request to build a table index.
@@ -30,7 +31,7 @@ import org.apache.ignite.internal.replicator.message.PrimaryReplicaRequest;
* <p>It is possible to receive a {@link PrimaryReplicaMissException} in response to message processing if the leaseholder changes.</p>
*/
@Transferable(PartitionReplicationMessageGroup.BUILD_INDEX_REPLICA_REQUEST)
-public interface BuildIndexReplicaRequest extends PrimaryReplicaRequest {
+public interface BuildIndexReplicaRequest extends PrimaryReplicaRequest, TableAware {
/** Returns index ID. */
int indexId();
diff --git a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/index/IndexMeta.java b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/index/IndexMeta.java
index ffd3f0cf0ed..032a4be6fa4 100644
--- a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/index/IndexMeta.java
+++ b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/index/IndexMeta.java
@@ -105,7 +105,7 @@ public class IndexMeta {
}
/** Returns catalog version in which the current meta was created. */
- int catalogVersion() {
+ public int catalogVersion() {
return catalogVersion;
}
diff --git a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/raft/PartitionListener.java b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/raft/PartitionListener.java
index 02107845c74..25acb4391a0 100644
--- a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/raft/PartitionListener.java
+++ b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/raft/PartitionListener.java
@@ -18,26 +18,20 @@
package org.apache.ignite.internal.table.distributed.raft;
import static java.lang.Math.max;
-import static java.util.Objects.requireNonNull;
import static org.apache.ignite.internal.hlc.HybridTimestamp.NULL_HYBRID_TIMESTAMP;
import static org.apache.ignite.internal.lang.IgniteSystemProperties.enabledColocation;
+import static org.apache.ignite.internal.partition.replicator.network.PartitionReplicationMessageGroup.Commands.BUILD_INDEX;
import static org.apache.ignite.internal.partition.replicator.network.PartitionReplicationMessageGroup.Commands.FINISH_TX;
import static org.apache.ignite.internal.partition.replicator.network.PartitionReplicationMessageGroup.Commands.UPDATE_MINIMUM_ACTIVE_TX_TIME_COMMAND;
import static org.apache.ignite.internal.partition.replicator.network.PartitionReplicationMessageGroup.GROUP_TYPE;
import static org.apache.ignite.internal.table.distributed.TableUtils.indexIdsAtRwTxBeginTs;
import static org.apache.ignite.internal.table.distributed.TableUtils.indexIdsAtRwTxBeginTsOrNull;
-import static org.apache.ignite.internal.table.distributed.index.MetaIndexStatus.BUILDING;
-import static org.apache.ignite.internal.table.distributed.index.MetaIndexStatus.REGISTERED;
import static org.apache.ignite.internal.tx.TxState.COMMITTED;
import static org.apache.ignite.internal.tx.TxState.PENDING;
import static org.apache.ignite.internal.tx.message.TxMessageGroup.VACUUM_TX_STATE_COMMAND;
-import static org.apache.ignite.internal.util.CollectionUtils.last;
import java.io.Serializable;
import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
@@ -45,13 +39,11 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
-import java.util.stream.Stream;
import org.apache.ignite.internal.catalog.CatalogService;
import org.apache.ignite.internal.hlc.HybridTimestamp;
import org.apache.ignite.internal.lang.IgniteBiTuple;
import org.apache.ignite.internal.logger.IgniteLogger;
import org.apache.ignite.internal.logger.Loggers;
-import org.apache.ignite.internal.partition.replicator.network.command.BuildIndexCommand;
import org.apache.ignite.internal.partition.replicator.network.command.UpdateAllCommand;
import org.apache.ignite.internal.partition.replicator.network.command.UpdateCommand;
import org.apache.ignite.internal.partition.replicator.network.command.WriteIntentSwitchCommand;
@@ -73,19 +65,12 @@ import org.apache.ignite.internal.replicator.TablePartitionId;
import org.apache.ignite.internal.replicator.command.SafeTimePropagatingCommand;
import org.apache.ignite.internal.replicator.command.SafeTimeSyncCommand;
import org.apache.ignite.internal.replicator.message.PrimaryReplicaChangeCommand;
-import org.apache.ignite.internal.schema.BinaryRow;
-import org.apache.ignite.internal.schema.BinaryRowUpgrader;
-import org.apache.ignite.internal.schema.SchemaDescriptor;
import org.apache.ignite.internal.schema.SchemaRegistry;
-import org.apache.ignite.internal.storage.BinaryRowAndRowId;
import org.apache.ignite.internal.storage.MvPartitionStorage;
-import org.apache.ignite.internal.storage.MvPartitionStorage.Locker;
-import org.apache.ignite.internal.storage.RowId;
import org.apache.ignite.internal.storage.lease.LeaseInfo;
import org.apache.ignite.internal.table.distributed.StorageUpdateHandler;
-import org.apache.ignite.internal.table.distributed.index.IndexMeta;
import org.apache.ignite.internal.table.distributed.index.IndexMetaStorage;
-import org.apache.ignite.internal.table.distributed.index.MetaIndexStatusChange;
+import org.apache.ignite.internal.table.distributed.raft.handlers.BuildIndexCommandHandler;
import org.apache.ignite.internal.table.distributed.raft.handlers.MinimumActiveTxTimeCommandHandler;
import org.apache.ignite.internal.tx.TxManager;
import org.apache.ignite.internal.tx.TxStateMeta;
@@ -125,10 +110,6 @@ public class PartitionListener implements RaftGroupListener, RaftTableProcessor
private final CatalogService catalogService;
- private final SchemaRegistry schemaRegistry;
-
- private final IndexMetaStorage indexMetaStorage;
-
private final UUID localNodeId;
// This variable is volatile, because it may be updated outside the Raft thread under the colocation feature.
@@ -166,8 +147,6 @@ public class PartitionListener implements RaftGroupListener, RaftTableProcessor
this.safeTimeTracker = safeTimeTracker;
this.storageIndexTracker = storageIndexTracker;
this.catalogService = catalogService;
- this.schemaRegistry = schemaRegistry;
- this.indexMetaStorage = indexMetaStorage;
this.localNodeId = localNodeId;
onSnapshotSaveHandler = new OnSnapshotSaveHandler(txStatePartitionStorage);
@@ -182,6 +161,12 @@ public class PartitionListener implements RaftGroupListener, RaftTableProcessor
tablePartitionId,
minTimeCollectorService
));
+ commandHandlersBuilder.addHandler(GROUP_TYPE, BUILD_INDEX, new BuildIndexCommandHandler(
+ storage,
+ indexMetaStorage,
+ storageUpdateHandler,
+ schemaRegistry
+ ));
if (!enabledColocation()) {
commandHandlersBuilder.addHandler(
@@ -282,8 +267,6 @@ public class PartitionListener implements RaftGroupListener, RaftTableProcessor
result = handleWriteIntentSwitchCommand((WriteIntentSwitchCommand) command, commandIndex, commandTerm);
} else if (command instanceof SafeTimeSyncCommand) {
result = handleSafeTimeSyncCommand((SafeTimeSyncCommand) command, commandIndex, commandTerm);
- } else if (command instanceof BuildIndexCommand) {
- result = handleBuildIndexCommand((BuildIndexCommand) command, commandIndex, commandTerm);
} else if (command instanceof PrimaryReplicaChangeCommand) {
result = handlePrimaryReplicaChangeCommand((PrimaryReplicaChangeCommand) command, commandIndex, commandTerm);
}
@@ -624,62 +607,6 @@ public class PartitionListener implements RaftGroupListener, RaftTableProcessor
return safeTimeTracker;
}
- /**
- * Handler for the {@link BuildIndexCommand}.
- *
- * @param cmd Command.
- * @param commandIndex RAFT index of the command.
- * @param commandTerm RAFT term of the command.
- */
- IgniteBiTuple<Serializable, Boolean> handleBuildIndexCommand(BuildIndexCommand cmd, long commandIndex, long commandTerm) {
- // Skips the write command because the storage has already executed it.
- if (commandIndex <= storage.lastAppliedIndex()) {
- return new IgniteBiTuple<>(null, false);
- }
-
- IndexMeta indexMeta = indexMetaStorage.indexMeta(cmd.indexId());
-
- if (indexMeta == null || indexMeta.isDropped()) {
- // Index has been dropped.
- return new IgniteBiTuple<>(null, true);
- }
-
- BuildIndexRowVersionChooser rowVersionChooser = createBuildIndexRowVersionChooser(indexMeta);
-
- BinaryRowUpgrader binaryRowUpgrader = createBinaryRowUpgrader(indexMeta);
-
- storage.runConsistently(locker -> {
- List<UUID> rowUuids = new ArrayList<>(cmd.rowIds());
-
- // Natural UUID order matches RowId order within the same partition.
- Collections.sort(rowUuids);
-
- Stream<BinaryRowAndRowId> buildIndexRowStream = createBuildIndexRowStream(
- rowUuids,
- locker,
- rowVersionChooser,
- binaryRowUpgrader
- );
-
- RowId nextRowIdToBuild = cmd.finish() ? null : toRowId(requireNonNull(last(rowUuids))).increment();
-
- storageUpdateHandler.getIndexUpdateHandler().buildIndex(cmd.indexId(), buildIndexRowStream, nextRowIdToBuild);
-
- storage.lastApplied(commandIndex, commandTerm);
-
- return null;
- });
-
- if (cmd.finish()) {
- LOG.info(
- "Finish building the index: [tableId={}, partitionId={}, indexId={}]",
- storage.tableId(), storage.partitionId(), cmd.indexId()
- );
- }
-
- return new IgniteBiTuple<>(null, true);
- }
-
/**
* Handler for {@link PrimaryReplicaChangeCommand}.
*
@@ -719,24 +646,6 @@ public class PartitionListener implements RaftGroupListener, RaftTableProcessor
}
}
- private Stream<BinaryRowAndRowId> createBuildIndexRowStream(
- List<UUID> rowUuids,
- Locker locker,
- BuildIndexRowVersionChooser rowVersionChooser,
- BinaryRowUpgrader binaryRowUpgrader
- ) {
- return rowUuids.stream()
- .map(this::toRowId)
- .peek(locker::lock)
- .map(rowVersionChooser::chooseForBuildIndex)
- .flatMap(Collection::stream)
- .map(binaryRowAndRowId -> upgradeBinaryRow(binaryRowUpgrader, binaryRowAndRowId));
- }
-
- private RowId toRowId(UUID rowUuid) {
- return new RowId(storageUpdateHandler.partitionId(), rowUuid);
- }
-
private void replicaTouch(UUID txId, UUID txCoordinatorId, HybridTimestamp commitTimestamp, boolean full) {
txManager.updateTxMeta(txId, old -> new TxStateMeta(
full ? COMMITTED : PENDING,
@@ -747,30 +656,6 @@ public class PartitionListener implements RaftGroupListener, RaftTableProcessor
));
}
- private BuildIndexRowVersionChooser createBuildIndexRowVersionChooser(IndexMeta indexMeta) {
- MetaIndexStatusChange registeredChangeInfo = indexMeta.statusChange(REGISTERED);
- MetaIndexStatusChange buildingChangeInfo = indexMeta.statusChange(BUILDING);
-
- return new BuildIndexRowVersionChooser(
- storage,
- registeredChangeInfo.activationTimestamp(),
- buildingChangeInfo.activationTimestamp()
- );
- }
-
- private BinaryRowUpgrader createBinaryRowUpgrader(IndexMeta indexMeta) {
- SchemaDescriptor schema = schemaRegistry.schema(indexMeta.tableVersion());
-
- return new BinaryRowUpgrader(schemaRegistry, schema);
- }
-
- private static BinaryRowAndRowId upgradeBinaryRow(BinaryRowUpgrader upgrader, BinaryRowAndRowId source) {
- BinaryRow sourceBinaryRow = source.binaryRow();
- BinaryRow upgradedBinaryRow = upgrader.upgrade(sourceBinaryRow);
-
- return upgradedBinaryRow == sourceBinaryRow ? source : new BinaryRowAndRowId(upgradedBinaryRow, source.rowId());
- }
-
/**
* Checks whether the primary replica belongs to the raft group topology (peers and learners) within a raft linearized context.
* On the primary replica election prior to the lease publication, the placement driver sends a PrimaryReplicaChangeCommand that
diff --git a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/raft/handlers/BuildIndexCommandHandler.java b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/raft/handlers/BuildIndexCommandHandler.java
new file mode 100644
index 00000000000..020f5e69fcd
--- /dev/null
+++ b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/raft/handlers/BuildIndexCommandHandler.java
@@ -0,0 +1,185 @@
+/*
+ * 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.table.distributed.raft.handlers;
+
+import static java.util.Objects.requireNonNull;
+import static org.apache.ignite.internal.table.distributed.index.MetaIndexStatus.BUILDING;
+import static org.apache.ignite.internal.table.distributed.index.MetaIndexStatus.REGISTERED;
+import static org.apache.ignite.internal.util.CollectionUtils.last;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.UUID;
+import java.util.stream.Stream;
+import org.apache.ignite.internal.hlc.HybridTimestamp;
+import org.apache.ignite.internal.lang.IgniteBiTuple;
+import org.apache.ignite.internal.lang.IgniteInternalException;
+import org.apache.ignite.internal.logger.IgniteLogger;
+import org.apache.ignite.internal.logger.Loggers;
+import org.apache.ignite.internal.partition.replicator.network.command.BuildIndexCommand;
+import org.apache.ignite.internal.partition.replicator.raft.handlers.AbstractCommandHandler;
+import org.apache.ignite.internal.partition.replicator.raft.snapshot.PartitionDataStorage;
+import org.apache.ignite.internal.schema.BinaryRow;
+import org.apache.ignite.internal.schema.BinaryRowUpgrader;
+import org.apache.ignite.internal.schema.SchemaDescriptor;
+import org.apache.ignite.internal.schema.SchemaRegistry;
+import org.apache.ignite.internal.storage.BinaryRowAndRowId;
+import org.apache.ignite.internal.storage.MvPartitionStorage.Locker;
+import org.apache.ignite.internal.storage.RowId;
+import org.apache.ignite.internal.table.distributed.StorageUpdateHandler;
+import org.apache.ignite.internal.table.distributed.index.IndexMeta;
+import org.apache.ignite.internal.table.distributed.index.IndexMetaStorage;
+import org.apache.ignite.internal.table.distributed.index.MetaIndexStatusChange;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Raft command handler that handles {@link BuildIndexCommand}.
+ */
+public class BuildIndexCommandHandler extends AbstractCommandHandler<BuildIndexCommand> {
+ private static final IgniteLogger LOG = Loggers.forClass(BuildIndexCommandHandler.class);
+
+ /** Data storage to which the command will be applied. */
+ private final PartitionDataStorage storage;
+
+ private final IndexMetaStorage indexMetaStorage;
+
+ /** Handler that processes storage updates. */
+ private final StorageUpdateHandler storageUpdateHandler;
+
+ private final SchemaRegistry schemaRegistry;
+
+ /**
+ * Creates a new instance of the command handler.
+ *
+ * @param storage Partition data storage.
+ * @param indexMetaStorage Index meta storage.
+ * @param storageUpdateHandler Storage update handler.
+ * @param schemaRegistry Schema registry.
+ */
+ public BuildIndexCommandHandler(
+ PartitionDataStorage storage,
+ IndexMetaStorage indexMetaStorage,
+ StorageUpdateHandler storageUpdateHandler,
+ SchemaRegistry schemaRegistry
+ ) {
+ this.storage = storage;
+ this.indexMetaStorage = indexMetaStorage;
+ this.storageUpdateHandler = storageUpdateHandler;
+ this.schemaRegistry = schemaRegistry;
+ }
+
+ @Override
+ protected IgniteBiTuple<Serializable, Boolean> handleInternally(
+ BuildIndexCommand command,
+ long commandIndex,
+ long commandTerm,
+ @Nullable HybridTimestamp safeTimestamp
+ ) throws IgniteInternalException {
+ // Skips the write command because the storage has already executed it.
+ if (commandIndex <= storage.lastAppliedIndex()) {
+ return new IgniteBiTuple<>(null, false);
+ }
+
+ IndexMeta indexMeta = indexMetaStorage.indexMeta(command.indexId());
+
+ if (indexMeta == null || indexMeta.isDropped()) {
+ // Index has been dropped.
+ return new IgniteBiTuple<>(null, true);
+ }
+
+ BuildIndexRowVersionChooser rowVersionChooser = createBuildIndexRowVersionChooser(indexMeta);
+
+ BinaryRowUpgrader binaryRowUpgrader = createBinaryRowUpgrader(indexMeta);
+
+ storage.runConsistently(locker -> {
+ var rowUuids = new ArrayList<UUID>(command.rowIds());
+
+ // Natural UUID order matches RowId order within the same partition.
+ Collections.sort(rowUuids);
+
+ Stream<BinaryRowAndRowId> buildIndexRowStream = createBuildIndexRowStream(
+ rowUuids,
+ locker,
+ rowVersionChooser,
+ binaryRowUpgrader
+ );
+
+ RowId nextRowIdToBuild = command.finish() ? null : toRowId(requireNonNull(last(rowUuids))).increment();
+
+ storageUpdateHandler.getIndexUpdateHandler().buildIndex(command.indexId(), buildIndexRowStream, nextRowIdToBuild);
+
+ storage.lastApplied(commandIndex, commandTerm);
+
+ return null;
+ });
+
+ if (command.finish()) {
+ LOG.info(
+ "Finish building the index [tableId={}, partitionId={}, indexId={}].",
+ storage.tableId(), storage.partitionId(), command.indexId()
+ );
+ }
+
+ return new IgniteBiTuple<>(null, true);
+ }
+
+ private BuildIndexRowVersionChooser createBuildIndexRowVersionChooser(IndexMeta indexMeta) {
+ MetaIndexStatusChange registeredChangeInfo = indexMeta.statusChange(REGISTERED);
+ MetaIndexStatusChange buildingChangeInfo = indexMeta.statusChange(BUILDING);
+
+ return new BuildIndexRowVersionChooser(
+ storage,
+ registeredChangeInfo.activationTimestamp(),
+ buildingChangeInfo.activationTimestamp()
+ );
+ }
+
+ private BinaryRowUpgrader createBinaryRowUpgrader(IndexMeta indexMeta) {
+ SchemaDescriptor schema = schemaRegistry.schema(indexMeta.tableVersion());
+
+ return new BinaryRowUpgrader(schemaRegistry, schema);
+ }
+
+ private Stream<BinaryRowAndRowId> createBuildIndexRowStream(
+ List<UUID> rowUuids,
+ Locker locker,
+ BuildIndexRowVersionChooser rowVersionChooser,
+ BinaryRowUpgrader binaryRowUpgrader
+ ) {
+ return rowUuids.stream()
+ .map(this::toRowId)
+ .peek(locker::lock)
+ .map(rowVersionChooser::chooseForBuildIndex)
+ .flatMap(Collection::stream)
+ .map(binaryRowAndRowId -> upgradeBinaryRow(binaryRowUpgrader, binaryRowAndRowId));
+ }
+
+ private static BinaryRowAndRowId upgradeBinaryRow(BinaryRowUpgrader upgrader, BinaryRowAndRowId source) {
+ BinaryRow sourceBinaryRow = source.binaryRow();
+ BinaryRow upgradedBinaryRow = upgrader.upgrade(sourceBinaryRow);
+
+ return upgradedBinaryRow == sourceBinaryRow ? source : new BinaryRowAndRowId(upgradedBinaryRow, source.rowId());
+ }
+
+ private RowId toRowId(UUID rowUuid) {
+ return new RowId(storageUpdateHandler.partitionId(), rowUuid);
+ }
+}
diff --git a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/raft/BuildIndexRowVersionChooser.java b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/raft/handlers/BuildIndexRowVersionChooser.java
similarity index 98%
rename from modules/table/src/main/java/org/apache/ignite/internal/table/distributed/raft/BuildIndexRowVersionChooser.java
rename to modules/table/src/main/java/org/apache/ignite/internal/table/distributed/raft/handlers/BuildIndexRowVersionChooser.java
index 9737083481e..33b51a51827 100644
--- a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/raft/BuildIndexRowVersionChooser.java
+++ b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/raft/handlers/BuildIndexRowVersionChooser.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.ignite.internal.table.distributed.raft;
+package org.apache.ignite.internal.table.distributed.raft.handlers;
import static org.apache.ignite.internal.tx.TransactionIds.beginTimestamp;
diff --git a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/IndexBuilderTxRwOperationTracker.java b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/IndexBuilderTxRwOperationTracker.java
index 5de76489b0a..4613c54275b 100644
--- a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/IndexBuilderTxRwOperationTracker.java
+++ b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/IndexBuilderTxRwOperationTracker.java
@@ -45,7 +45,7 @@ import org.apache.ignite.internal.util.IgniteSpinBusyLock;
* <li>When completing a RW transaction operation, {@link #decrementOperationCount(int)} must be used.</li>
* </ul>
*/
-class IndexBuilderTxRwOperationTracker implements ManuallyCloseable {
+public class IndexBuilderTxRwOperationTracker implements ManuallyCloseable {
private final AtomicInteger minAllowedCatalogVersionForStartOperation = new AtomicInteger(-1);
private final NavigableMap<Integer, CompletableFuture<Void>> minAllowedVersionRaiseFutures = new ConcurrentSkipListMap<>();
@@ -100,7 +100,7 @@ class IndexBuilderTxRwOperationTracker implements ManuallyCloseable {
*
* @param catalogVersion Catalog version in which the new index appeared.
*/
- CompletableFuture<Void> awaitCompleteTxRwOperations(int catalogVersion) {
+ public CompletableFuture<Void> awaitCompleteTxRwOperations(int catalogVersion) {
return inBusyLock(busyLock, () -> {
// This code is needed to avoid races with updateAllowedCatalogVersionForStartOperation.
CompletableFuture<Void> waitForMinAllowedReachingVersion = minAllowedVersionRaiseFutures.computeIfAbsent(
diff --git a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/PartitionReplicaListener.java b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/PartitionReplicaListener.java
index 81752d2123e..4ae5a0e4d0e 100644
--- a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/PartitionReplicaListener.java
+++ b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/PartitionReplicaListener.java
@@ -36,7 +36,6 @@ import static org.apache.ignite.internal.partitiondistribution.Assignments.fromB
import static org.apache.ignite.internal.raft.PeersAndLearners.fromAssignments;
import static org.apache.ignite.internal.replicator.message.ReplicaMessageUtils.toReplicationGroupIdMessage;
import static org.apache.ignite.internal.replicator.message.ReplicaMessageUtils.toTablePartitionIdMessage;
-import static org.apache.ignite.internal.table.distributed.index.MetaIndexStatus.BUILDING;
import static org.apache.ignite.internal.table.distributed.index.MetaIndexStatus.REGISTERED;
import static org.apache.ignite.internal.table.distributed.replicator.RemoteResourceIds.cursorId;
import static org.apache.ignite.internal.table.distributed.replicator.ReplicatorUtils.beginRwTxTs;
@@ -116,7 +115,6 @@ import org.apache.ignite.internal.partition.replicator.handlers.TxStateCommitPar
import org.apache.ignite.internal.partition.replicator.handlers.VacuumTxStateReplicaRequestHandler;
import org.apache.ignite.internal.partition.replicator.network.PartitionReplicationMessagesFactory;
import org.apache.ignite.internal.partition.replicator.network.TimedBinaryRow;
-import org.apache.ignite.internal.partition.replicator.network.command.BuildIndexCommand;
import org.apache.ignite.internal.partition.replicator.network.command.TimedBinaryRowMessage;
import org.apache.ignite.internal.partition.replicator.network.command.TimedBinaryRowMessageBuilder;
import org.apache.ignite.internal.partition.replicator.network.command.UpdateAllCommand;
@@ -200,6 +198,7 @@ import org.apache.ignite.internal.table.distributed.TableUtils;
import org.apache.ignite.internal.table.distributed.index.IndexMeta;
import org.apache.ignite.internal.table.distributed.index.IndexMetaStorage;
import org.apache.ignite.internal.table.distributed.index.MetaIndexStatusChange;
+import org.apache.ignite.internal.table.distributed.replicator.handlers.BuildIndexReplicaRequestHandler;
import org.apache.ignite.internal.tx.Lock;
import org.apache.ignite.internal.tx.LockKey;
import org.apache.ignite.internal.tx.LockManager;
@@ -370,6 +369,7 @@ public class PartitionReplicaListener implements ReplicaListener {
private final MinimumActiveTxTimeReplicaRequestHandler minimumActiveTxTimeReplicaRequestHandler;
private final VacuumTxStateReplicaRequestHandler vacuumTxStateReplicaRequestHandler;
private final TxStateCommitPartitionReplicaRequestHandler txStateCommitPartitionReplicaRequestHandler;
+ private final BuildIndexReplicaRequestHandler buildIndexReplicaRequestHandler;
/**
* The constructor.
@@ -484,9 +484,16 @@ public class PartitionReplicaListener implements ReplicaListener {
clusterNodeResolver,
replicationGroupId,
localNode,
- txRecoveryEngine
- );
+ txRecoveryEngine);
+
+ buildIndexReplicaRequestHandler = new BuildIndexReplicaRequestHandler(
+ indexMetaStorage,
+ txRwOperationTracker,
+ safeTime,
+ raftCommandApplicator);
+ // TODO https://issues.apache.org/jira/browse/IGNITE-24665
+ // Consider extracting the following code to a separate class BuildIndexEventListener.
prepareIndexBuilderTxRwOperationTracker();
}
@@ -867,6 +874,8 @@ public class PartitionReplicaListener implements ReplicaListener {
return nullCompletedFuture();
} else if (request instanceof TxFinishReplicaRequest) {
+ assert !enabledColocation() : request;
+
return txFinishReplicaRequestHandler.handle((TxFinishReplicaRequest) request);
} else if (request instanceof WriteIntentSwitchReplicaRequest) {
return processWriteIntentSwitchAction((WriteIntentSwitchReplicaRequest) request);
@@ -881,7 +890,7 @@ public class PartitionReplicaListener implements ReplicaListener {
} else if (request instanceof ReplicaSafeTimeSyncRequest) {
return processReplicaSafeTimeSyncRequest(isPrimary);
} else if (request instanceof BuildIndexReplicaRequest) {
- return processBuildIndexReplicaRequest((BuildIndexReplicaRequest) request);
+ return buildIndexReplicaRequestHandler.handle((BuildIndexReplicaRequest) request);
} else if (request instanceof ReadOnlyDirectSingleRowReplicaRequest) {
return processReadOnlyDirectSingleEntryAction((ReadOnlyDirectSingleRowReplicaRequest) request, opStartTsIfDirectRo);
} else if (request instanceof ReadOnlyDirectMultiRowReplicaRequest) {
@@ -3673,16 +3682,6 @@ public class PartitionReplicaListener implements ReplicaListener {
return localNode.id().equals(nodeId);
}
- private static BuildIndexCommand toBuildIndexCommand(BuildIndexReplicaRequest request, MetaIndexStatusChange buildingChangeInfo) {
- return PARTITION_REPLICATION_MESSAGES_FACTORY.buildIndexCommand()
- .indexId(request.indexId())
- .rowIds(request.rowIds())
- .finish(request.finish())
- // We are sure that there will be no error here since the primary replica is sent the request to itself.
- .requiredCatalogVersion(buildingChangeInfo.catalogVersion())
- .build();
- }
-
private CompletableFuture<?> processOperationRequestWithTxOperationManagementLogic(
UUID senderId,
ReplicaRequest request,
@@ -3851,22 +3850,6 @@ public class PartitionReplicaListener implements ReplicaListener {
}
}
- private CompletableFuture<?> processBuildIndexReplicaRequest(BuildIndexReplicaRequest request) {
- IndexMeta indexMeta = indexMetaStorage.indexMeta(request.indexId());
-
- if (indexMeta == null || indexMeta.isDropped()) {
- // Index has been dropped.
- return nullCompletedFuture();
- }
-
- MetaIndexStatusChange registeredChangeInfo = indexMeta.statusChange(REGISTERED);
- MetaIndexStatusChange buildingChangeInfo = indexMeta.statusChange(BUILDING);
-
- return txRwOperationTracker.awaitCompleteTxRwOperations(registeredChangeInfo.catalogVersion())
- .thenCompose(unused -> safeTime.waitFor(hybridTimestamp(buildingChangeInfo.activationTimestamp())))
- .thenCompose(unused -> raftCommandRunner.run(toBuildIndexCommand(request, buildingChangeInfo)));
- }
-
private List<Integer> indexIdsAtRwTxBeginTs(UUID txId) {
return TableUtils.indexIdsAtRwTxBeginTs(catalogService, txId, tableId());
}
diff --git a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/handlers/BuildIndexReplicaRequestHandler.java b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/handlers/BuildIndexReplicaRequestHandler.java
new file mode 100644
index 00000000000..2dff324c197
--- /dev/null
+++ b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/handlers/BuildIndexReplicaRequestHandler.java
@@ -0,0 +1,107 @@
+/*
+ * 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.table.distributed.replicator.handlers;
+
+import static org.apache.ignite.internal.hlc.HybridTimestamp.hybridTimestamp;
+import static org.apache.ignite.internal.table.distributed.index.MetaIndexStatus.BUILDING;
+import static org.apache.ignite.internal.table.distributed.index.MetaIndexStatus.REGISTERED;
+import static org.apache.ignite.internal.util.CompletableFutures.nullCompletedFuture;
+
+import java.util.concurrent.CompletableFuture;
+import org.apache.ignite.internal.hlc.HybridTimestamp;
+import org.apache.ignite.internal.partition.replicator.ReplicationRaftCommandApplicator;
+import org.apache.ignite.internal.partition.replicator.network.PartitionReplicationMessagesFactory;
+import org.apache.ignite.internal.partition.replicator.network.command.BuildIndexCommand;
+import org.apache.ignite.internal.partition.replicator.network.replication.BuildIndexReplicaRequest;
+import org.apache.ignite.internal.table.distributed.index.IndexMeta;
+import org.apache.ignite.internal.table.distributed.index.IndexMetaStorage;
+import org.apache.ignite.internal.table.distributed.index.MetaIndexStatusChange;
+import org.apache.ignite.internal.table.distributed.replicator.IndexBuilderTxRwOperationTracker;
+import org.apache.ignite.internal.util.PendingComparableValuesTracker;
+
+/**
+ * Handler for {@link BuildIndexReplicaRequest}.
+ */
+public class BuildIndexReplicaRequestHandler {
+ /** Factory to create RAFT command messages. */
+ private static final PartitionReplicationMessagesFactory PARTITION_REPLICATION_MESSAGES_FACTORY =
+ new PartitionReplicationMessagesFactory();
+
+ private final IndexMetaStorage indexMetaStorage;
+
+ /** Read-write transaction operation tracker for building indexes. */
+ private final IndexBuilderTxRwOperationTracker txRwOperationTracker;
+
+ /** Partition safe-time tracker. */
+ private final PendingComparableValuesTracker<HybridTimestamp, Void> safeTime;
+
+ /** Applicator that applies RAFT command that is created by this handler. */
+ private final ReplicationRaftCommandApplicator commandApplicator;
+
+ /**
+ * Creates a new instance of request handler.
+ *
+ * @param indexMetaStorage Index meta storage.
+ * @param txRwOperationTracker Read-write transaction operation tracker for building indexes.
+ * @param safeTime Partition safe-time tracker.
+ * @param commandApplicator Applicator that applies RAFT command that is created by this handler.
+ */
+ public BuildIndexReplicaRequestHandler(
+ IndexMetaStorage indexMetaStorage,
+ IndexBuilderTxRwOperationTracker txRwOperationTracker,
+ PendingComparableValuesTracker<HybridTimestamp, Void> safeTime,
+ ReplicationRaftCommandApplicator commandApplicator
+ ) {
+ this.indexMetaStorage = indexMetaStorage;
+ this.txRwOperationTracker = txRwOperationTracker;
+ this.safeTime = safeTime;
+ this.commandApplicator = commandApplicator;
+ }
+
+ /**
+ * Handles {@link BuildIndexReplicaRequest}.
+ *
+ * @param request Request to handle.
+ */
+ public CompletableFuture<?> handle(BuildIndexReplicaRequest request) {
+ IndexMeta indexMeta = indexMetaStorage.indexMeta(request.indexId());
+
+ if (indexMeta == null || indexMeta.isDropped()) {
+ // Index has been dropped.
+ return nullCompletedFuture();
+ }
+
+ MetaIndexStatusChange registeredChangeInfo = indexMeta.statusChange(REGISTERED);
+ MetaIndexStatusChange buildingChangeInfo = indexMeta.statusChange(BUILDING);
+
+ return txRwOperationTracker.awaitCompleteTxRwOperations(registeredChangeInfo.catalogVersion())
+ .thenCompose(unused -> safeTime.waitFor(hybridTimestamp(buildingChangeInfo.activationTimestamp())))
+ .thenCompose(unused -> commandApplicator.applyCommand(toBuildIndexCommand(request, buildingChangeInfo)));
+ }
+
+ private static BuildIndexCommand toBuildIndexCommand(BuildIndexReplicaRequest request, MetaIndexStatusChange buildingChangeInfo) {
+ return PARTITION_REPLICATION_MESSAGES_FACTORY.buildIndexCommand()
+ .indexId(request.indexId())
+ .tableId(request.tableId())
+ .rowIds(request.rowIds())
+ .finish(request.finish())
+ // We are sure that there will be no error here since the primary replica is sent the request to itself.
+ .requiredCatalogVersion(buildingChangeInfo.catalogVersion())
+ .build();
+ }
+}
diff --git a/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/handlers/package-info.java b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/handlers/package-info.java
new file mode 100644
index 00000000000..ad7c7e9bffc
--- /dev/null
+++ b/modules/table/src/main/java/org/apache/ignite/internal/table/distributed/replicator/handlers/package-info.java
@@ -0,0 +1,22 @@
+/*
+ * 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.
+ */
+
+/**
+ * This package contains replica request handlers that is used by
+ * {@link org.apache.ignite.internal.table.distributed.replicator.PartitionReplicaListener}.
+ */
+package org.apache.ignite.internal.table.distributed.replicator.handlers;
diff --git a/modules/table/src/test/java/org/apache/ignite/internal/table/distributed/raft/PartitionCommandListenerTest.java b/modules/table/src/test/java/org/apache/ignite/internal/table/distributed/raft/PartitionCommandListenerTest.java
index c662df5a481..d4ea79600b7 100644
--- a/modules/table/src/test/java/org/apache/ignite/internal/table/distributed/raft/PartitionCommandListenerTest.java
+++ b/modules/table/src/test/java/org/apache/ignite/internal/table/distributed/raft/PartitionCommandListenerTest.java
@@ -703,18 +703,18 @@ public class PartitionCommandListenerTest extends BaseIgniteAbstractTest {
InOrder inOrder = inOrder(partitionDataStorage, indexUpdateHandler);
- commandListener.handleBuildIndexCommand(createBuildIndexCommand(indexId, List.of(row0.uuid()), false), 10, 1);
+ commandListener.processCommand(createBuildIndexCommand(indexId, List.of(row0.uuid()), false), 10, 1, null);
inOrder.verify(indexUpdateHandler).buildIndex(eq(indexId), any(Stream.class), eq(row0.increment()));
inOrder.verify(partitionDataStorage).lastApplied(10, 1);
- commandListener.handleBuildIndexCommand(createBuildIndexCommand(indexId, List.of(row1.uuid()), true), 20, 2);
+ commandListener.processCommand(createBuildIndexCommand(indexId, List.of(row1.uuid()), true), 20, 2, null);
inOrder.verify(indexUpdateHandler).buildIndex(eq(indexId), any(Stream.class), eq(null));
inOrder.verify(partitionDataStorage).lastApplied(20, 2);
// Let's check that the command with a lower commandIndex than in the storage will not be executed.
- commandListener.handleBuildIndexCommand(createBuildIndexCommand(indexId, List.of(row2.uuid()), false), 5, 1);
+ commandListener.processCommand(createBuildIndexCommand(indexId, List.of(row2.uuid()), false), 5, 1, null);
inOrder.verify(indexUpdateHandler, never()).buildIndex(eq(indexId), any(Stream.class), eq(row2.increment()));
inOrder.verify(partitionDataStorage, never()).lastApplied(5, 1);
@@ -723,6 +723,7 @@ public class PartitionCommandListenerTest extends BaseIgniteAbstractTest {
private BuildIndexCommand createBuildIndexCommand(int indexId, List<UUID> rowUuids, boolean finish) {
return PARTITION_REPLICATION_MESSAGES_FACTORY.buildIndexCommand()
.indexId(indexId)
+ .tableId(TABLE_ID)
.rowIds(rowUuids)
.finish(finish)
.build();
diff --git a/modules/table/src/test/java/org/apache/ignite/internal/table/distributed/raft/BuildIndexRowVersionChooserTest.java b/modules/table/src/test/java/org/apache/ignite/internal/table/distributed/raft/handlers/BuildIndexRowVersionChooserTest.java
similarity index 99%
rename from modules/table/src/test/java/org/apache/ignite/internal/table/distributed/raft/BuildIndexRowVersionChooserTest.java
rename to modules/table/src/test/java/org/apache/ignite/internal/table/distributed/raft/handlers/BuildIndexRowVersionChooserTest.java
index aaf289e2743..48cf66c1a8b 100644
--- a/modules/table/src/test/java/org/apache/ignite/internal/table/distributed/raft/BuildIndexRowVersionChooserTest.java
+++ b/modules/table/src/test/java/org/apache/ignite/internal/table/distributed/raft/handlers/BuildIndexRowVersionChooserTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package org.apache.ignite.internal.table.distributed.raft;
+package org.apache.ignite.internal.table.distributed.raft.handlers;
import static org.apache.ignite.internal.hlc.HybridTimestamp.hybridTimestamp;
import static org.apache.ignite.internal.storage.BinaryRowAndRowIdMatcher.equalToBinaryRowAndRowId;
diff --git a/modules/table/src/testFixtures/java/org/apache/ignite/internal/table/TableTestUtils.java b/modules/table/src/testFixtures/java/org/apache/ignite/internal/table/TableTestUtils.java
index a653cbba1a6..282a2641385 100644
--- a/modules/table/src/testFixtures/java/org/apache/ignite/internal/table/TableTestUtils.java
+++ b/modules/table/src/testFixtures/java/org/apache/ignite/internal/table/TableTestUtils.java
@@ -254,6 +254,18 @@ public class TableTestUtils {
return getTableStrict(catalogService, tableName, timestamp).id();
}
+ /**
+ * Returns zone ID for the given table.
+ *
+ * @param catalogService Catalog service.
+ * @param tableName Table name.
+ * @param timestamp Timestamp.
+ * @throws AssertionError If table is absent.
+ */
+ public static int getZoneIdByTableNameStrict(CatalogService catalogService, String tableName, long timestamp) {
+ return getTableStrict(catalogService, tableName, timestamp).zoneId();
+ }
+
/**
* Returns index ID form catalog, {@code null} if table is absent.
*