You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by tk...@apache.org on 2023/01/18 16:30:04 UTC
[ignite-3] branch main updated: IGNITE-18029 Implementation of a full rebalance for PersistentPageMemoryMvPartitionStorage on receiver (#1506)
This is an automated email from the ASF dual-hosted git repository.
tkalkirill 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 ba3e1cfe54 IGNITE-18029 Implementation of a full rebalance for PersistentPageMemoryMvPartitionStorage on receiver (#1506)
ba3e1cfe54 is described below
commit ba3e1cfe54e48cca808d69cc0854524e6c3fab8e
Author: Kirill Tkalenko <tk...@yandex.ru>
AuthorDate: Wed Jan 18 19:29:58 2023 +0300
IGNITE-18029 Implementation of a full rebalance for PersistentPageMemoryMvPartitionStorage on receiver (#1506)
---
.../java/org/apache/ignite/lang/ErrorGroups.java | 3 +
.../ignite/lang/IgniteInternalException.java | 8 +-
.../internal/storage/MvPartitionStorage.java | 3 +
.../internal/storage/StorageClosedException.java | 13 +-
.../ignite/internal/storage/StorageException.java | 18 +-
.../storage/StorageRebalanceException.java | 25 ++-
.../StorageState.java} | 22 +-
.../ignite/internal/storage/util/StorageUtils.java | 112 +++++++++++
.../internal/storage/TestMvTableStorageTest.java | 20 +-
.../storage/AbstractMvTableStorageTest.java | 102 +++++++++-
.../storage/impl/TestMvPartitionStorage.java | 2 +-
.../internal/storage/impl/TestMvTableStorage.java | 4 +-
.../pagememory/AbstractPageMemoryTableStorage.java | 142 +++++++++++--
.../PersistentPageMemoryTableStorage.java | 223 +++++++++++++++------
.../pagememory/VolatilePageMemoryTableStorage.java | 23 +--
.../index/hash/PageMemoryHashIndexStorage.java | 94 ++++++++-
.../index/sorted/PageMemorySortedIndexStorage.java | 99 ++++++++-
.../mv/AbstractPageMemoryMvPartitionStorage.java | 174 +++++++++++++---
.../mv/PersistentPageMemoryMvPartitionStorage.java | 104 ++++++++--
.../mv/VolatilePageMemoryMvPartitionStorage.java | 32 ++-
.../PersistentPageMemoryMvTableStorageTest.java | 48 +----
.../VolatilePageMemoryMvTableStorageTest.java | 34 +---
.../storage/rocksdb/RocksDbMvTableStorageTest.java | 48 ++---
.../state/rocksdb/TxStateRocksDbStorage.java | 2 +-
24 files changed, 1026 insertions(+), 329 deletions(-)
diff --git a/modules/core/src/main/java/org/apache/ignite/lang/ErrorGroups.java b/modules/core/src/main/java/org/apache/ignite/lang/ErrorGroups.java
index 5ecce0f4ff..d455731179 100755
--- a/modules/core/src/main/java/org/apache/ignite/lang/ErrorGroups.java
+++ b/modules/core/src/main/java/org/apache/ignite/lang/ErrorGroups.java
@@ -331,6 +331,9 @@ public class ErrorGroups {
/** Operation on closed storage. */
public static final int ALREADY_CLOSED_ERR = STORAGE_ERR_GROUP.registerErrorCode(3);
+
+ /** Storage rebalancing error. */
+ public static final int STORAGE_REBALANCE_ERR = STORAGE_ERR_GROUP.registerErrorCode(4);
}
/** Distribution zones error group. */
diff --git a/modules/core/src/main/java/org/apache/ignite/lang/IgniteInternalException.java b/modules/core/src/main/java/org/apache/ignite/lang/IgniteInternalException.java
index 2e8268ecd6..546e71c8df 100644
--- a/modules/core/src/main/java/org/apache/ignite/lang/IgniteInternalException.java
+++ b/modules/core/src/main/java/org/apache/ignite/lang/IgniteInternalException.java
@@ -106,7 +106,7 @@ public class IgniteInternalException extends RuntimeException {
* @param code Full error code.
* @param cause Optional nested exception (can be {@code null}).
*/
- public IgniteInternalException(int code, Throwable cause) {
+ public IgniteInternalException(int code, @Nullable Throwable cause) {
this(UUID.randomUUID(), code, cause);
}
@@ -117,7 +117,7 @@ public class IgniteInternalException extends RuntimeException {
* @param code Full error code.
* @param cause Optional nested exception (can be {@code null}).
*/
- public IgniteInternalException(UUID traceId, int code, Throwable cause) {
+ public IgniteInternalException(UUID traceId, int code, @Nullable Throwable cause) {
super(errorMessageFromCause(traceId, code, cause), cause);
this.traceId = traceId;
@@ -132,7 +132,7 @@ public class IgniteInternalException extends RuntimeException {
* @param message Detail message.
* @param cause Optional nested exception (can be {@code null}).
*/
- public IgniteInternalException(int code, String message, Throwable cause) {
+ public IgniteInternalException(int code, String message, @Nullable Throwable cause) {
this(UUID.randomUUID(), code, message, cause);
}
@@ -144,7 +144,7 @@ public class IgniteInternalException extends RuntimeException {
* @param message Detail message.
* @param cause Optional nested exception (can be {@code null}).
*/
- public IgniteInternalException(UUID traceId, int code, String message, Throwable cause) {
+ public IgniteInternalException(UUID traceId, int code, String message, @Nullable Throwable cause) {
super(errorMessage(traceId, code, message), cause);
this.traceId = traceId;
diff --git a/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/MvPartitionStorage.java b/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/MvPartitionStorage.java
index 1898308bcc..4035746404 100644
--- a/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/MvPartitionStorage.java
+++ b/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/MvPartitionStorage.java
@@ -89,6 +89,9 @@ public interface MvPartitionStorage extends ManuallyCloseable {
/**
* Sets the last applied index and term.
+ *
+ * @param lastAppliedIndex Last applied index value.
+ * @param lastAppliedTerm Last applied term value.
*/
void lastApplied(long lastAppliedIndex, long lastAppliedTerm) throws StorageException;
diff --git a/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageClosedException.java b/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageClosedException.java
index 6bbd058587..3c0c1d0a8a 100644
--- a/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageClosedException.java
+++ b/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageClosedException.java
@@ -26,9 +26,18 @@ public class StorageClosedException extends StorageException {
private static final long serialVersionUID = -7988332521347221109L;
/**
- * Constructor.
+ * Default constructor.
*/
public StorageClosedException() {
- super(Storage.ALREADY_CLOSED_ERR, "Storage is already closed");
+ this("Storage is already closed");
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param message Error message.
+ */
+ public StorageClosedException(String message) {
+ super(Storage.ALREADY_CLOSED_ERR, message);
}
}
diff --git a/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageException.java b/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageException.java
index 7f19415bb1..71a4fdd250 100644
--- a/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageException.java
+++ b/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageException.java
@@ -19,6 +19,7 @@ package org.apache.ignite.internal.storage;
import org.apache.ignite.lang.ErrorGroups.Storage;
import org.apache.ignite.lang.IgniteInternalException;
+import org.jetbrains.annotations.Nullable;
/**
* Exception thrown by the storage.
@@ -39,16 +40,16 @@ public class StorageException extends IgniteInternalException {
* Constructor.
*
* @param message Error message.
- * @param cause The cause.
+ * @param cause Optional nested exception (can be {@code null}).
*/
- public StorageException(String message, Throwable cause) {
+ public StorageException(String message, @Nullable Throwable cause) {
super(Storage.GENERIC_ERR, message, cause);
}
/**
* Constructor.
*
- * @param cause The cause.
+ * @param cause Non-null throwable cause.
*/
public StorageException(Throwable cause) {
super(Storage.GENERIC_ERR, cause);
@@ -63,4 +64,15 @@ public class StorageException extends IgniteInternalException {
protected StorageException(int code, String message) {
super(code, message);
}
+
+ /**
+ * Constructor.
+ *
+ * @param code Full error code.
+ * @param message Error message.
+ * @param cause Optional nested exception (can be {@code null}).
+ */
+ protected StorageException(int code, String message, @Nullable Throwable cause) {
+ super(code, message, cause);
+ }
}
diff --git a/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageRebalanceException.java b/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageRebalanceException.java
index 6a99a8003a..c18ecb25f7 100644
--- a/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageRebalanceException.java
+++ b/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageRebalanceException.java
@@ -17,35 +17,38 @@
package org.apache.ignite.internal.storage;
+import org.apache.ignite.lang.ErrorGroups.Storage;
+import org.jetbrains.annotations.Nullable;
+
/**
* Exception that will be thrown when the storage is in the process of rebalance.
*/
public class StorageRebalanceException extends StorageException {
+ private static final long serialVersionUID = -4840074471464728969L;
+
/**
- * Constructor.
- *
- * @param message Error message.
+ * Default constructor.
*/
- public StorageRebalanceException(String message) {
- super(message);
+ public StorageRebalanceException() {
+ this("Storage in the process of rebalancing");
}
/**
* Constructor.
*
* @param message Error message.
- * @param cause The cause.
*/
- public StorageRebalanceException(String message, Throwable cause) {
- super(message, cause);
+ public StorageRebalanceException(String message) {
+ super(Storage.STORAGE_REBALANCE_ERR, message);
}
/**
* Constructor.
*
- * @param cause The cause.
+ * @param message Error message.
+ * @param cause Optional nested exception (can be {@code null}).
*/
- public StorageRebalanceException(Throwable cause) {
- super(cause);
+ public StorageRebalanceException(String message, @Nullable Throwable cause) {
+ super(Storage.STORAGE_REBALANCE_ERR, message, cause);
}
}
diff --git a/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageClosedException.java b/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/util/StorageState.java
similarity index 64%
copy from modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageClosedException.java
copy to modules/storage-api/src/main/java/org/apache/ignite/internal/storage/util/StorageState.java
index 6bbd058587..711df878cf 100644
--- a/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/StorageClosedException.java
+++ b/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/util/StorageState.java
@@ -15,20 +15,18 @@
* limitations under the License.
*/
-package org.apache.ignite.internal.storage;
-
-import org.apache.ignite.lang.ErrorGroups.Storage;
+package org.apache.ignite.internal.storage.util;
/**
- * Exception that will be thrown when the storage is closed.
+ * Storage states.
*/
-public class StorageClosedException extends StorageException {
- private static final long serialVersionUID = -7988332521347221109L;
+public enum StorageState {
+ /** Storage is running. */
+ RUNNABLE,
+
+ /** Storage is in the process of being closed or has already closed. */
+ CLOSED,
- /**
- * Constructor.
- */
- public StorageClosedException() {
- super(Storage.ALREADY_CLOSED_ERR, "Storage is already closed");
- }
+ /** Storage is in the process of rebalancing. */
+ REBALANCE
}
diff --git a/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/util/StorageUtils.java b/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/util/StorageUtils.java
new file mode 100644
index 0000000000..9034d5567d
--- /dev/null
+++ b/modules/storage-api/src/main/java/org/apache/ignite/internal/storage/util/StorageUtils.java
@@ -0,0 +1,112 @@
+/*
+ * 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.storage.util;
+
+import java.util.function.Supplier;
+import org.apache.ignite.internal.storage.StorageClosedException;
+import org.apache.ignite.internal.storage.StorageException;
+import org.apache.ignite.internal.storage.StorageRebalanceException;
+import org.apache.ignite.lang.IgniteStringFormatter;
+
+/**
+ * Helper class for storages.
+ */
+public class StorageUtils {
+ /**
+ * Creates an error message about missing multi-version partition storage.
+ *
+ * @param partitionId Partition ID.
+ */
+ public static String createMissingMvPartitionErrorMessage(int partitionId) {
+ return "Partition ID " + partitionId + " does not exist";
+ }
+
+ /**
+ * Throws an {@link StorageRebalanceException} if the storage is in the process of rebalancing.
+ *
+ * @param state Storage state.
+ * @param storageInfoSupplier Storage information supplier, for example in the format "table=user, partitionId=1".
+ */
+ public static void throwExceptionIfStorageInProgressOfRebalance(StorageState state, Supplier<String> storageInfoSupplier) {
+ if (state == StorageState.REBALANCE) {
+ throw new StorageRebalanceException(createStorageInProcessOfRebalanceErrorMessage(storageInfoSupplier.get()));
+ }
+ }
+
+ /**
+ * Throws an {@link StorageRebalanceException} depending on {@link StorageState} on rebalance.
+ *
+ * @param state Storage state.
+ * @param storageInfo Storage information, for example in the format "table=user, partitionId=1".
+ * @throws StorageRebalanceException Depending on {@link StorageState}.
+ */
+ public static void throwExceptionDependingOnStorageStateOnRebalance(StorageState state, String storageInfo) {
+ switch (state) {
+ case CLOSED:
+ throw new StorageRebalanceException(createStorageClosedErrorMessage(storageInfo));
+ case REBALANCE:
+ throw new StorageRebalanceException(createStorageInProcessOfRebalanceErrorMessage(storageInfo));
+ default:
+ throw new StorageRebalanceException(createUnexpectedStorageStateErrorMessage(state, storageInfo));
+ }
+ }
+
+ /**
+ * Throws an exception depending on {@link StorageState}.
+ *
+ * @param state Storage state.
+ * @param storageInfo Storage information, for example in the format "table=user, partitionId=1".
+ * @throws StorageClosedException If the storage is closed.
+ * @throws StorageRebalanceException If storage is in the process of rebalancing.
+ * @throws StorageException For other {@link StorageState}.
+ */
+ public static void throwExceptionDependingOnStorageState(StorageState state, String storageInfo) {
+ switch (state) {
+ case CLOSED:
+ throw new StorageClosedException(createStorageClosedErrorMessage(storageInfo));
+ case REBALANCE:
+ throw new StorageRebalanceException(createStorageInProcessOfRebalanceErrorMessage(storageInfo));
+ default:
+ throw new StorageException(createUnexpectedStorageStateErrorMessage(state, storageInfo));
+ }
+ }
+
+ /**
+ * Throws an {@link StorageRebalanceException} if the storage is <strong>NOT</strong> in the process of rebalancing.
+ *
+ * @param state Storage state.
+ * @param storageInfoSupplier Storage information supplier, for example in the format "table=user, partitionId=1".
+ */
+ public static void throwExceptionIfStorageNotInProgressOfRebalance(StorageState state, Supplier<String> storageInfoSupplier) {
+ if (state != StorageState.REBALANCE) {
+ throw new StorageRebalanceException(createStorageInProcessOfRebalanceErrorMessage(storageInfoSupplier.get()));
+ }
+ }
+
+ private static String createStorageInProcessOfRebalanceErrorMessage(String storageInfo) {
+ return IgniteStringFormatter.format("Storage in the process of rebalancing: [{}]", storageInfo);
+ }
+
+ private static String createUnexpectedStorageStateErrorMessage(StorageState state, String storageInfo) {
+ return IgniteStringFormatter.format("Unexpected state: [{}, state={}]", storageInfo, state);
+ }
+
+ private static String createStorageClosedErrorMessage(String storageInfo) {
+ return IgniteStringFormatter.format("Storage is already closed: [{}]", storageInfo);
+ }
+}
diff --git a/modules/storage-api/src/test/java/org/apache/ignite/internal/storage/TestMvTableStorageTest.java b/modules/storage-api/src/test/java/org/apache/ignite/internal/storage/TestMvTableStorageTest.java
index 6b8d3e5856..3de0a3912e 100644
--- a/modules/storage-api/src/test/java/org/apache/ignite/internal/storage/TestMvTableStorageTest.java
+++ b/modules/storage-api/src/test/java/org/apache/ignite/internal/storage/TestMvTableStorageTest.java
@@ -22,7 +22,6 @@ import org.apache.ignite.internal.configuration.testframework.InjectConfiguratio
import org.apache.ignite.internal.schema.configuration.TablesConfiguration;
import org.apache.ignite.internal.storage.impl.TestMvTableStorage;
import org.apache.ignite.internal.storage.impl.TestStorageEngine;
-import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -31,26 +30,11 @@ import org.junit.jupiter.api.extension.ExtendWith;
*/
@ExtendWith(ConfigurationExtension.class)
public class TestMvTableStorageTest extends AbstractMvTableStorageTest {
- private TestMvTableStorage storage;
-
@BeforeEach
void setUp(
- @InjectConfiguration(
- value = "mock.tables.foo.dataStorage.name = " + TestStorageEngine.ENGINE_NAME
- )
+ @InjectConfiguration("mock.tables.foo.dataStorage.name = " + TestStorageEngine.ENGINE_NAME)
TablesConfiguration tablesConfig
) {
- storage = new TestMvTableStorage(tablesConfig.tables().get("foo"), tablesConfig);
-
- storage.start();
-
- initialize(storage, tablesConfig);
- }
-
- @AfterEach
- void tearDown() {
- if (storage != null) {
- storage.stop();
- }
+ initialize(new TestStorageEngine(), tablesConfig);
}
}
diff --git a/modules/storage-api/src/testFixtures/java/org/apache/ignite/internal/storage/AbstractMvTableStorageTest.java b/modules/storage-api/src/testFixtures/java/org/apache/ignite/internal/storage/AbstractMvTableStorageTest.java
index d9caa63a73..ecd27123cd 100644
--- a/modules/storage-api/src/testFixtures/java/org/apache/ignite/internal/storage/AbstractMvTableStorageTest.java
+++ b/modules/storage-api/src/testFixtures/java/org/apache/ignite/internal/storage/AbstractMvTableStorageTest.java
@@ -38,6 +38,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.mockito.Mockito.mock;
import java.nio.ByteBuffer;
@@ -61,14 +62,18 @@ import org.apache.ignite.internal.schema.testutils.definition.ColumnType;
import org.apache.ignite.internal.schema.testutils.definition.TableDefinition;
import org.apache.ignite.internal.schema.testutils.definition.index.IndexDefinition;
import org.apache.ignite.internal.storage.engine.MvTableStorage;
+import org.apache.ignite.internal.storage.engine.StorageEngine;
import org.apache.ignite.internal.storage.impl.TestMvPartitionStorage;
import org.apache.ignite.internal.storage.index.HashIndexStorage;
import org.apache.ignite.internal.storage.index.IndexRow;
import org.apache.ignite.internal.storage.index.IndexRowImpl;
import org.apache.ignite.internal.storage.index.IndexStorage;
+import org.apache.ignite.internal.storage.index.PeekCursor;
import org.apache.ignite.internal.storage.index.SortedIndexStorage;
import org.apache.ignite.internal.util.Cursor;
+import org.apache.ignite.internal.util.IgniteUtils;
import org.apache.ignite.lang.IgniteTuple3;
+import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@@ -88,25 +93,49 @@ public abstract class AbstractMvTableStorageTest extends BaseMvStoragesTest {
/** Partition id for 1 storage. */
protected static final int PARTITION_ID_1 = 1 << 8;
- private MvTableStorage tableStorage;
+ protected MvTableStorage tableStorage;
private TableIndexView sortedIdx;
private TableIndexView hashIdx;
+ protected StorageEngine storageEngine;
+
/**
* Initializes the internal structures needed for tests.
*
* <p>This method *MUST* always be called in either subclass' constructor or setUp method.
*/
- protected final void initialize(MvTableStorage tableStorage, TablesConfiguration tablesCfg) {
- createTestTable(tableStorage.configuration());
- createTestIndexes(tablesCfg);
+ protected final void initialize(StorageEngine storageEngine, TablesConfiguration tablesConfig) {
+ createTestTable(getTableConfig(tablesConfig));
+ createTestIndexes(tablesConfig);
+
+ this.storageEngine = storageEngine;
+
+ this.storageEngine.start();
- this.tableStorage = tableStorage;
+ this.tableStorage = createMvTableStorage(tablesConfig);
+
+ this.tableStorage.start();
+
+ sortedIdx = tablesConfig.indexes().get(SORTED_INDEX_NAME).value();
+ hashIdx = tablesConfig.indexes().get(HASH_INDEX_NAME).value();
+ }
+
+ @AfterEach
+ void tearDown() throws Exception {
+ IgniteUtils.closeAll(
+ tableStorage == null ? null : tableStorage::stop,
+ storageEngine == null ? null : storageEngine::stop
+ );
+ }
+
+ protected MvTableStorage createMvTableStorage(TablesConfiguration tablesConfig) {
+ return storageEngine.createMvTable(getTableConfig(tablesConfig), tablesConfig);
+ }
- sortedIdx = tablesCfg.indexes().get(SORTED_INDEX_NAME).value();
- hashIdx = tablesCfg.indexes().get(HASH_INDEX_NAME).value();
+ private TableConfiguration getTableConfig(TablesConfiguration tablesConfig) {
+ return tablesConfig.tables().get("foo");
}
/**
@@ -548,6 +577,51 @@ public abstract class AbstractMvTableStorageTest extends BaseMvStoragesTest {
assertThat(tableStorage.destroy(), willCompleteSuccessfully());
}
+ /**
+ * Checks that if we restart the storages after a crash in the middle of a rebalance, the storages will be empty.
+ */
+ @Test
+ public void testRestartStoragesAfterFailDuringRebalance() {
+ assumeFalse(tableStorage.isVolatile());
+
+ MvPartitionStorage mvPartitionStorage = tableStorage.getOrCreateMvPartition(PARTITION_ID);
+ HashIndexStorage hashIndexStorage = tableStorage.getOrCreateHashIndex(PARTITION_ID, hashIdx.id());
+ SortedIndexStorage sortedIndexStorage = tableStorage.getOrCreateSortedIndex(PARTITION_ID, sortedIdx.id());
+
+ List<IgniteTuple3<RowId, BinaryRow, HybridTimestamp>> rows = List.of(
+ new IgniteTuple3<>(new RowId(PARTITION_ID), binaryRow(new TestKey(0, "0"), new TestValue(0, "0")), clock.now())
+ );
+
+ fillStorages(mvPartitionStorage, hashIndexStorage, sortedIndexStorage, rows);
+
+ // Since it is not possible to close storages in middle of rebalance, we will shorten path a bit by updating only lastApplied*.
+ MvPartitionStorage finalMvPartitionStorage = mvPartitionStorage;
+
+ mvPartitionStorage.runConsistently(() -> {
+ finalMvPartitionStorage.lastApplied(REBALANCE_IN_PROGRESS, REBALANCE_IN_PROGRESS);
+
+ return null;
+ });
+
+ assertThat(mvPartitionStorage.flush(), willCompleteSuccessfully());
+
+ // Restart storages.
+ tableStorage.stop();
+
+ tableStorage = createMvTableStorage(tableStorage.tablesConfiguration());
+
+ tableStorage.start();
+
+ mvPartitionStorage = tableStorage.getOrCreateMvPartition(PARTITION_ID);
+ hashIndexStorage = tableStorage.getOrCreateHashIndex(PARTITION_ID, hashIdx.id());
+ sortedIndexStorage = tableStorage.getOrCreateSortedIndex(PARTITION_ID, sortedIdx.id());
+
+ // Let's check the repositories: they should be empty.
+ checkForMissingRows(mvPartitionStorage, hashIndexStorage, sortedIndexStorage, rows);
+
+ checkLastApplied(mvPartitionStorage, 0, 0, 0);
+ }
+
private static void createTestIndexes(TablesConfiguration tablesConfig) {
List<IndexDefinition> indexDefinitions = List.of(
SchemaBuilders.sortedIndex(SORTED_INDEX_NAME)
@@ -747,6 +821,10 @@ public abstract class AbstractMvTableStorageTest extends BaseMvStoragesTest {
assertThrows(StorageRebalanceException.class, cursor::hasNext);
assertThrows(StorageRebalanceException.class, cursor::next);
+
+ if (cursor instanceof PeekCursor) {
+ assertThrows(StorageRebalanceException.class, ((PeekCursor<?>) cursor)::peek);
+ }
}
private void fillStorages(
@@ -811,8 +889,8 @@ public abstract class AbstractMvTableStorageTest extends BaseMvStoragesTest {
) {
for (IgniteTuple3<RowId, BinaryRow, HybridTimestamp> row : rows) {
assertThat(
- getAll(mvPartitionStorage.scanVersions(row.get1())).stream().map(ReadResult::binaryRow).collect(toList()),
- containsInAnyOrder(row.get2())
+ toListOfByteArrays(mvPartitionStorage.scanVersions(row.get1())),
+ containsInAnyOrder(row.get2().bytes())
);
IndexRow hashIndexRow = indexRow(hashIndexStorage.indexDescriptor(), row.get2(), row.get1());
@@ -833,4 +911,10 @@ public abstract class AbstractMvTableStorageTest extends BaseMvStoragesTest {
assertEquals(expPersistentIndex, storage.persistedIndex());
assertEquals(expLastAppliedTerm, storage.lastAppliedTerm());
}
+
+ private static List<byte[]> toListOfByteArrays(Cursor<ReadResult> cursor) {
+ try (cursor) {
+ return cursor.stream().map(ReadResult::binaryRow).map(BinaryRow::bytes).collect(toList());
+ }
+ }
}
diff --git a/modules/storage-api/src/testFixtures/java/org/apache/ignite/internal/storage/impl/TestMvPartitionStorage.java b/modules/storage-api/src/testFixtures/java/org/apache/ignite/internal/storage/impl/TestMvPartitionStorage.java
index 6cc5214bb7..7c27a2f136 100644
--- a/modules/storage-api/src/testFixtures/java/org/apache/ignite/internal/storage/impl/TestMvPartitionStorage.java
+++ b/modules/storage-api/src/testFixtures/java/org/apache/ignite/internal/storage/impl/TestMvPartitionStorage.java
@@ -563,7 +563,7 @@ public class TestMvPartitionStorage implements MvPartitionStorage {
private void checkStorageInProcessOfRebalance() {
if (rebalance) {
- throw new StorageRebalanceException("Storage in the process of rebalancing");
+ throw new StorageRebalanceException();
}
}
diff --git a/modules/storage-api/src/testFixtures/java/org/apache/ignite/internal/storage/impl/TestMvTableStorage.java b/modules/storage-api/src/testFixtures/java/org/apache/ignite/internal/storage/impl/TestMvTableStorage.java
index 8d237c3645..45e59cfa97 100644
--- a/modules/storage-api/src/testFixtures/java/org/apache/ignite/internal/storage/impl/TestMvTableStorage.java
+++ b/modules/storage-api/src/testFixtures/java/org/apache/ignite/internal/storage/impl/TestMvTableStorage.java
@@ -252,9 +252,7 @@ public class TestMvTableStorage implements MvTableStorage {
throw new StorageRebalanceException(createPartitionDoesNotExistsErrorMessage(partitionId));
}
- if (destroyFutureByPartitionId.containsKey(partitionId)) {
- throw new StorageRebalanceException("Partition in the process of destruction: " + partitionId);
- }
+ assert !destroyFutureByPartitionId.containsKey(partitionId) : partitionId;
if (partitionStorage.closed()) {
throw new StorageRebalanceException("Partition closed: " + partitionId);
diff --git a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/AbstractPageMemoryTableStorage.java b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/AbstractPageMemoryTableStorage.java
index ce3625e62d..bb671be899 100644
--- a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/AbstractPageMemoryTableStorage.java
+++ b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/AbstractPageMemoryTableStorage.java
@@ -18,6 +18,8 @@
package org.apache.ignite.internal.storage.pagememory;
import static java.util.concurrent.CompletableFuture.completedFuture;
+import static org.apache.ignite.internal.storage.MvPartitionStorage.REBALANCE_IN_PROGRESS;
+import static org.apache.ignite.internal.storage.util.StorageUtils.createMissingMvPartitionErrorMessage;
import static org.apache.ignite.internal.util.IgniteUtils.inBusyLock;
import java.util.ArrayList;
@@ -31,17 +33,21 @@ import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.function.Supplier;
import org.apache.ignite.internal.pagememory.DataRegion;
import org.apache.ignite.internal.pagememory.PageMemory;
+import org.apache.ignite.internal.pagememory.freelist.FreeList;
+import org.apache.ignite.internal.pagememory.reuse.ReuseList;
+import org.apache.ignite.internal.pagememory.tree.BplusTree;
import org.apache.ignite.internal.schema.configuration.TableConfiguration;
import org.apache.ignite.internal.schema.configuration.TableView;
import org.apache.ignite.internal.schema.configuration.TablesConfiguration;
import org.apache.ignite.internal.storage.StorageException;
+import org.apache.ignite.internal.storage.StorageRebalanceException;
import org.apache.ignite.internal.storage.engine.MvTableStorage;
import org.apache.ignite.internal.storage.index.HashIndexStorage;
import org.apache.ignite.internal.storage.index.SortedIndexStorage;
import org.apache.ignite.internal.storage.pagememory.mv.AbstractPageMemoryMvPartitionStorage;
-import org.apache.ignite.internal.tostring.S;
import org.apache.ignite.internal.util.IgniteSpinBusyLock;
import org.apache.ignite.internal.util.IgniteUtils;
+import org.apache.ignite.lang.IgniteStringFormatter;
import org.jetbrains.annotations.Nullable;
/**
@@ -54,8 +60,11 @@ public abstract class AbstractPageMemoryTableStorage implements MvTableStorage {
protected volatile AtomicReferenceArray<AbstractPageMemoryMvPartitionStorage> mvPartitions;
- protected final ConcurrentMap<Integer, CompletableFuture<Void>> partitionIdDestroyFutureMap = new ConcurrentHashMap<>();
+ protected final ConcurrentMap<Integer, CompletableFuture<Void>> destroyFutureByPartitionId = new ConcurrentHashMap<>();
+ protected final ConcurrentMap<Integer, CompletableFuture<Void>> rebalanceFutureByPartitionId = new ConcurrentHashMap<>();
+
+ /** Busy lock. */
private final IgniteSpinBusyLock busyLock = new IgniteSpinBusyLock();
/** Prevents double stopping of the component. */
@@ -65,6 +74,7 @@ public abstract class AbstractPageMemoryTableStorage implements MvTableStorage {
* Constructor.
*
* @param tableCfg Table configuration.
+ * @param tablesCfg Tables configuration.
*/
protected AbstractPageMemoryTableStorage(TableConfiguration tableCfg, TablesConfiguration tablesCfg) {
this.tableCfg = tableCfg;
@@ -118,7 +128,7 @@ public abstract class AbstractPageMemoryTableStorage implements MvTableStorage {
try {
IgniteUtils.closeAll(closeables);
} catch (Exception e) {
- throw new StorageException("Failed to stop PageMemory table storage.", e);
+ throw new StorageException("Failed to stop PageMemory table storage: " + getTableName(), e);
}
}
@@ -133,7 +143,7 @@ public abstract class AbstractPageMemoryTableStorage implements MvTableStorage {
List<CompletableFuture<Void>> destroyFutures = new ArrayList<>();
for (int i = 0; i < mvPartitions.length(); i++) {
- CompletableFuture<Void> destroyPartitionFuture = partitionIdDestroyFutureMap.get(i);
+ CompletableFuture<Void> destroyPartitionFuture = destroyFutureByPartitionId.get(i);
if (destroyPartitionFuture != null) {
destroyFutures.add(destroyPartitionFuture);
@@ -216,9 +226,12 @@ public abstract class AbstractPageMemoryTableStorage implements MvTableStorage {
return busy(() -> {
checkPartitionId(partitionId);
+ assert !rebalanceFutureByPartitionId.containsKey(partitionId)
+ : IgniteStringFormatter.format("table={}, partitionId={}", getTableName(), partitionId);
+
CompletableFuture<Void> destroyPartitionFuture = new CompletableFuture<>();
- CompletableFuture<Void> previousDestroyPartitionFuture = partitionIdDestroyFutureMap.putIfAbsent(
+ CompletableFuture<Void> previousDestroyPartitionFuture = destroyFutureByPartitionId.putIfAbsent(
partitionId,
destroyPartitionFuture
);
@@ -231,7 +244,7 @@ public abstract class AbstractPageMemoryTableStorage implements MvTableStorage {
if (partition != null) {
destroyMvPartitionStorage(partition).whenComplete((unused, throwable) -> {
- partitionIdDestroyFutureMap.remove(partitionId);
+ destroyFutureByPartitionId.remove(partitionId);
if (throwable != null) {
destroyPartitionFuture.completeExceptionally(throwable);
@@ -240,7 +253,7 @@ public abstract class AbstractPageMemoryTableStorage implements MvTableStorage {
}
});
} else {
- partitionIdDestroyFutureMap.remove(partitionId).complete(null);
+ destroyFutureByPartitionId.remove(partitionId).complete(null);
}
return destroyPartitionFuture;
@@ -253,7 +266,7 @@ public abstract class AbstractPageMemoryTableStorage implements MvTableStorage {
AbstractPageMemoryMvPartitionStorage partitionStorage = getMvPartitionBusy(partitionId);
if (partitionStorage == null) {
- throw new StorageException(String.format("Partition ID %d does not exist", partitionId));
+ throw new StorageException(createMissingMvPartitionErrorMessage(partitionId));
}
return partitionStorage.getOrCreateSortedIndex(indexId);
@@ -266,7 +279,7 @@ public abstract class AbstractPageMemoryTableStorage implements MvTableStorage {
AbstractPageMemoryMvPartitionStorage partitionStorage = getMvPartitionBusy(partitionId);
if (partitionStorage == null) {
- throw new StorageException(String.format("Partition ID %d does not exist", partitionId));
+ throw new StorageException(createMissingMvPartitionErrorMessage(partitionId));
}
return partitionStorage.getOrCreateHashIndex(indexId);
@@ -292,11 +305,11 @@ public abstract class AbstractPageMemoryTableStorage implements MvTableStorage {
int partitions = mvPartitions.length();
if (partitionId < 0 || partitionId >= partitions) {
- throw new IllegalArgumentException(S.toString(
- "Unable to access partition with id outside of configured range",
- "table", tableCfg.value().name(), false,
- "partitionId", partitionId, false,
- "partitions", partitions, false
+ throw new IllegalArgumentException(IgniteStringFormatter.format(
+ "Unable to access partition with id outside of configured range: [table={}, partitionId={}, partitions={}]",
+ getTableName(),
+ partitionId,
+ partitions
));
}
}
@@ -304,4 +317,105 @@ public abstract class AbstractPageMemoryTableStorage implements MvTableStorage {
private <V> V busy(Supplier<V> supplier) {
return inBusyLock(busyLock, supplier);
}
+
+ @Override
+ public CompletableFuture<Void> startRebalancePartition(int partitionId) {
+ return inBusyLock(busyLock, () -> {
+ AbstractPageMemoryMvPartitionStorage mvPartitionStorage = getMvPartitionBusy(partitionId);
+
+ if (mvPartitionStorage == null) {
+ throw new StorageRebalanceException(createMissingMvPartitionErrorMessage(partitionId));
+ }
+
+ assert !destroyFutureByPartitionId.containsKey(partitionId) : mvPartitionStorage.createStorageInfo();
+
+ mvPartitionStorage.startRebalance();
+
+ CompletableFuture<Void> rebalanceFuture = clearStorageAndUpdateDataStructures(mvPartitionStorage)
+ .thenAccept(unused ->
+ mvPartitionStorage.runConsistently(() -> {
+ mvPartitionStorage.lastAppliedOnRebalance(REBALANCE_IN_PROGRESS, REBALANCE_IN_PROGRESS);
+
+ return null;
+ })
+ );
+
+ CompletableFuture<Void> previousRebalanceFuture = rebalanceFutureByPartitionId.putIfAbsent(partitionId, rebalanceFuture);
+
+ assert previousRebalanceFuture == null : mvPartitionStorage.createStorageInfo();
+
+ return rebalanceFuture;
+ });
+ }
+
+ @Override
+ public CompletableFuture<Void> abortRebalancePartition(int partitionId) {
+ return inBusyLock(busyLock, () -> {
+ AbstractPageMemoryMvPartitionStorage mvPartitionStorage = getMvPartitionBusy(partitionId);
+
+ if (mvPartitionStorage == null) {
+ throw new StorageRebalanceException(createMissingMvPartitionErrorMessage(partitionId));
+ }
+
+ CompletableFuture<Void> rebalanceFuture = rebalanceFutureByPartitionId.remove(partitionId);
+
+ if (rebalanceFuture == null) {
+ return completedFuture(null);
+ }
+
+ return rebalanceFuture
+ .thenCompose(unused -> clearStorageAndUpdateDataStructures(mvPartitionStorage))
+ .thenAccept(unused -> {
+ mvPartitionStorage.runConsistently(() -> {
+ mvPartitionStorage.lastAppliedOnRebalance(0, 0);
+
+ return null;
+ });
+
+ mvPartitionStorage.completeRebalance();
+ });
+ });
+ }
+
+ @Override
+ public CompletableFuture<Void> finishRebalancePartition(int partitionId, long lastAppliedIndex, long lastAppliedTerm) {
+ return inBusyLock(busyLock, () -> {
+ AbstractPageMemoryMvPartitionStorage mvPartitionStorage = getMvPartitionBusy(partitionId);
+
+ if (mvPartitionStorage == null) {
+ throw new StorageRebalanceException(createMissingMvPartitionErrorMessage(partitionId));
+ }
+
+ CompletableFuture<Void> rebalanceFuture = rebalanceFutureByPartitionId.remove(partitionId);
+
+ if (rebalanceFuture == null) {
+ throw new StorageRebalanceException("Rebalance for partition did not start: " + mvPartitionStorage.createStorageInfo());
+ }
+
+ return rebalanceFuture.thenAccept(unused -> {
+ mvPartitionStorage.runConsistently(() -> {
+ mvPartitionStorage.lastAppliedOnRebalance(lastAppliedIndex, lastAppliedTerm);
+
+ return null;
+ });
+
+ mvPartitionStorage.completeRebalance();
+ });
+ });
+ }
+
+ /**
+ * Clears the partition multi-version storage and all its indexes, updates their internal data structures such as {@link BplusTree},
+ * {@link FreeList} and {@link ReuseList}.
+ *
+ * @return Future of the operation.
+ */
+ abstract CompletableFuture<Void> clearStorageAndUpdateDataStructures(AbstractPageMemoryMvPartitionStorage mvPartitionStorage);
+
+ /**
+ * Returns table name.
+ */
+ public String getTableName() {
+ return tableCfg.name().value();
+ }
}
diff --git a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/PersistentPageMemoryTableStorage.java b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/PersistentPageMemoryTableStorage.java
index e0c0fb59f0..34b3f50f35 100644
--- a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/PersistentPageMemoryTableStorage.java
+++ b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/PersistentPageMemoryTableStorage.java
@@ -18,17 +18,19 @@
package org.apache.ignite.internal.storage.pagememory;
import static org.apache.ignite.internal.pagememory.PageIdAllocator.FLAG_AUX;
+import static org.apache.ignite.internal.storage.MvPartitionStorage.REBALANCE_IN_PROGRESS;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Supplier;
+import org.apache.ignite.internal.pagememory.PageMemory;
import org.apache.ignite.internal.pagememory.evict.PageEvictionTrackerNoOp;
import org.apache.ignite.internal.pagememory.metric.IoStatisticsHolderNoOp;
import org.apache.ignite.internal.pagememory.persistence.GroupPartitionId;
import org.apache.ignite.internal.pagememory.persistence.PartitionMeta;
import org.apache.ignite.internal.pagememory.persistence.PersistentPageMemory;
-import org.apache.ignite.internal.pagememory.persistence.checkpoint.CheckpointManager;
import org.apache.ignite.internal.pagememory.persistence.checkpoint.CheckpointProgress;
import org.apache.ignite.internal.pagememory.persistence.checkpoint.CheckpointTimeoutLock;
import org.apache.ignite.internal.pagememory.persistence.store.FilePageStore;
@@ -62,6 +64,7 @@ public class PersistentPageMemoryTableStorage extends AbstractPageMemoryTableSto
* Constructor.
*
* @param tableCfg Table configuration.
+ * @param tablesCfg Tables configuration.
* @param engine Storage engine instance.
* @param dataRegion Data region for the table.
*/
@@ -101,44 +104,17 @@ public class PersistentPageMemoryTableStorage extends AbstractPageMemoryTableSto
@Override
public PersistentPageMemoryMvPartitionStorage createMvPartitionStorage(int partitionId) {
- CompletableFuture<Void> partitionDestroyFuture = partitionIdDestroyFutureMap.get(partitionId);
-
- if (partitionDestroyFuture != null) {
- try {
- // Time is chosen randomly (long enough) so as not to call #join().
- partitionDestroyFuture.get(10, TimeUnit.SECONDS);
- } catch (Exception e) {
- throw new StorageException("Error waiting for the destruction of the previous version of the partition: " + partitionId, e);
- }
- }
+ waitPartitionToBeDestroyed(partitionId);
TableView tableView = tableCfg.value();
- GroupPartitionId groupPartitionId = new GroupPartitionId(tableView.tableId(), partitionId);
-
- FilePageStore filePageStore = ensurePartitionFilePageStore(tableView, groupPartitionId);
+ GroupPartitionId groupPartitionId = createGroupPartitionId(partitionId);
- CheckpointManager checkpointManager = dataRegion.checkpointManager();
+ PartitionMeta meta = getOrCreatePartitionMetaOnCreatePartition(groupPartitionId);
- CheckpointTimeoutLock checkpointTimeoutLock = checkpointManager.checkpointTimeoutLock();
-
- checkpointTimeoutLock.checkpointReadLock();
-
- try {
+ return inCheckpointLock(() -> {
PersistentPageMemory pageMemory = dataRegion.pageMemory();
- PartitionMeta meta = dataRegion.partitionMetaManager().readOrCreateMeta(lastCheckpointId(), groupPartitionId, filePageStore);
-
- dataRegion.partitionMetaManager().addMeta(groupPartitionId, meta);
-
- filePageStore.pages(meta.pageCount());
-
- filePageStore.setPageAllocationListener(pageIdx -> {
- assert checkpointTimeoutLock.checkpointLockIsHeldByThread();
-
- meta.incrementPageCount(lastCheckpointId());
- });
-
RowVersionFreeList rowVersionFreeList = createRowVersionFreeList(tableView, partitionId, pageMemory, meta);
IndexColumnsFreeList indexColumnsFreeList
@@ -155,17 +131,9 @@ public class PersistentPageMemoryTableStorage extends AbstractPageMemoryTableSto
rowVersionFreeList,
indexColumnsFreeList,
versionChainTree,
- indexMetaTree,
- tablesCfg
+ indexMetaTree
);
- } catch (IgniteInternalCheckedException e) {
- throw new StorageException(
- String.format("Error getting or creating partition [tableName=%s, partitionId=%s]", tableView.name(), partitionId),
- e
- );
- } finally {
- checkpointTimeoutLock.checkpointReadUnlock();
- }
+ });
}
/**
@@ -176,7 +144,10 @@ public class PersistentPageMemoryTableStorage extends AbstractPageMemoryTableSto
* @return Partition file page store.
* @throws StorageException If failed.
*/
- private FilePageStore ensurePartitionFilePageStore(TableView tableView, GroupPartitionId groupPartitionId) throws StorageException {
+ private FilePageStore ensurePartitionFilePageStoreExists(
+ TableView tableView,
+ GroupPartitionId groupPartitionId
+ ) throws StorageException {
try {
dataRegion.filePageStoreManager().initialize(tableView.name(), groupPartitionId);
@@ -405,42 +376,166 @@ public class PersistentPageMemoryTableStorage extends AbstractPageMemoryTableSto
}
@Override
- public CompletableFuture<Void> startRebalancePartition(int partitionId) {
- // TODO: IGNITE-18029 Implement
- throw new UnsupportedOperationException();
- }
+ CompletableFuture<Void> destroyMvPartitionStorage(AbstractPageMemoryMvPartitionStorage mvPartitionStorage) {
+ // It is enough for us to close the partition storage and its indexes (do not destroy). Prepare the data region, checkpointer, and
+ // compactor to remove the partition, and then simply delete the partition file and its delta files.
+ mvPartitionStorage.close();
- @Override
- public CompletableFuture<Void> abortRebalancePartition(int partitionId) {
- // TODO: IGNITE-18029 Implement
- throw new UnsupportedOperationException();
+ return destroyPartitionPhysically(createGroupPartitionId(mvPartitionStorage.partitionId()));
}
@Override
- public CompletableFuture<Void> finishRebalancePartition(int partitionId, long lastAppliedIndex, long lastAppliedTerm) {
- // TODO: IGNITE-18029 Implement
- throw new UnsupportedOperationException();
- }
+ CompletableFuture<Void> clearStorageAndUpdateDataStructures(AbstractPageMemoryMvPartitionStorage mvPartitionStorage) {
+ GroupPartitionId groupPartitionId = createGroupPartitionId(mvPartitionStorage.partitionId());
- @Override
- CompletableFuture<Void> destroyMvPartitionStorage(AbstractPageMemoryMvPartitionStorage mvPartitionStorage) {
- int partitionId = mvPartitionStorage.partitionId();
+ return destroyPartitionPhysically(groupPartitionId).thenAccept(unused -> {
+ TableView tableView = tableCfg.value();
- // It is enough for us to close the partition storage and its indexes (do not destroy). Prepare the data region, checkpointer, and
- // compactor to remove the partition, and then simply delete the partition file and its delta files.
+ PersistentPageMemory pageMemory = dataRegion.pageMemory();
- mvPartitionStorage.close();
+ int partitionId = groupPartitionId.getPartitionId();
+
+ PartitionMeta meta = getOrCreatePartitionMeta(
+ groupPartitionId,
+ ensurePartitionFilePageStoreExists(tableView, groupPartitionId)
+ );
+
+ inCheckpointLock(() -> {
+ RowVersionFreeList rowVersionFreeList = createRowVersionFreeList(tableView, partitionId, pageMemory, meta);
+
+ IndexColumnsFreeList indexColumnsFreeList
+ = createIndexColumnsFreeList(tableView, partitionId, rowVersionFreeList, pageMemory, meta);
+
+ VersionChainTree versionChainTree = createVersionChainTree(tableView, partitionId, rowVersionFreeList, pageMemory, meta);
- int tableId = tableCfg.tableId().value();
+ IndexMetaTree indexMetaTree = createIndexMetaTree(tableView, partitionId, rowVersionFreeList, pageMemory, meta);
- GroupPartitionId groupPartitionId = new GroupPartitionId(tableId, partitionId);
+ ((PersistentPageMemoryMvPartitionStorage) mvPartitionStorage).updateDataStructuresOnRebalance(
+ meta,
+ rowVersionFreeList,
+ indexColumnsFreeList,
+ versionChainTree,
+ indexMetaTree
+ );
+ return null;
+ });
+ });
+ }
+
+ private CompletableFuture<Void> destroyPartitionPhysically(GroupPartitionId groupPartitionId) {
dataRegion.filePageStoreManager().getStore(groupPartitionId).markToDestroy();
- dataRegion.pageMemory().invalidate(tableId, partitionId);
+ dataRegion.pageMemory().invalidate(groupPartitionId.getGroupId(), groupPartitionId.getPartitionId());
return dataRegion.checkpointManager().onPartitionDestruction(groupPartitionId)
.thenAccept(unused -> dataRegion.partitionMetaManager().removeMeta(groupPartitionId))
.thenCompose(unused -> dataRegion.filePageStoreManager().destroyPartition(groupPartitionId));
}
+
+ private GroupPartitionId createGroupPartitionId(int partitionId) {
+ return new GroupPartitionId(tableCfg.tableId().value(), partitionId);
+ }
+
+ private <V> V inCheckpointLock(Supplier<V> supplier) {
+ CheckpointTimeoutLock checkpointTimeoutLock = dataRegion.checkpointManager().checkpointTimeoutLock();
+
+ checkpointTimeoutLock.checkpointReadLock();
+
+ try {
+ return supplier.get();
+ } finally {
+ checkpointTimeoutLock.checkpointReadUnlock();
+ }
+ }
+
+ /**
+ * Creates or gets partition meta from a file.
+ *
+ * <p>Safe to use without a checkpointReadLock as we read the meta directly without using {@link PageMemory}.
+ *
+ * @param groupPartitionId Partition of the group.
+ * @param filePageStore Partition file page store.
+ */
+ private PartitionMeta getOrCreatePartitionMeta(GroupPartitionId groupPartitionId, FilePageStore filePageStore) {
+ try {
+ PartitionMeta meta = dataRegion.partitionMetaManager().readOrCreateMeta(lastCheckpointId(), groupPartitionId, filePageStore);
+
+ dataRegion.partitionMetaManager().addMeta(groupPartitionId, meta);
+
+ filePageStore.pages(meta.pageCount());
+
+ filePageStore.setPageAllocationListener(pageIdx -> {
+ assert dataRegion.checkpointManager().checkpointTimeoutLock().checkpointLockIsHeldByThread();
+
+ meta.incrementPageCount(lastCheckpointId());
+ });
+
+ return meta;
+ } catch (IgniteInternalCheckedException e) {
+ throw new StorageException(
+ IgniteStringFormatter.format(
+ "Error reading or creating partition meta information: [table={}, partitionId={}]",
+ getTableName(),
+ groupPartitionId.getPartitionId()
+ ),
+ e
+ );
+ }
+ }
+
+ /**
+ * Creates or receives partition meta from a file, if the rebalancing has not finished in time, the file page store will be recreated.
+ *
+ * <p>Safe to use without a checkpointReadLock as we read the meta directly without using {@link PageMemory}.
+ *
+ * @param groupPartitionId Partition of the group.
+ */
+ private PartitionMeta getOrCreatePartitionMetaOnCreatePartition(GroupPartitionId groupPartitionId) {
+ TableView tableView = tableCfg.value();
+
+ FilePageStore filePageStore = ensurePartitionFilePageStoreExists(tableView, groupPartitionId);
+
+ PartitionMeta partitionMeta = getOrCreatePartitionMeta(groupPartitionId, filePageStore);
+
+ if (partitionMeta.lastAppliedIndex() == REBALANCE_IN_PROGRESS) {
+ try {
+ // TODO: IGNITE-18565 We need to return a CompletableFuture
+ destroyPartitionPhysically(groupPartitionId).get(10, TimeUnit.SECONDS);
+ } catch (Exception e) {
+ throw new StorageException(
+ IgniteStringFormatter.format(
+ "Error when physically destroying a partition: [table={}, partitionId={}]",
+ getTableName(),
+ groupPartitionId.getPartitionId()
+ ),
+ e
+ );
+ }
+
+ return getOrCreatePartitionMeta(groupPartitionId, ensurePartitionFilePageStoreExists(tableView, groupPartitionId));
+ } else {
+ return partitionMeta;
+ }
+ }
+
+ private void waitPartitionToBeDestroyed(int partitionId) {
+ CompletableFuture<Void> partitionDestroyFuture = destroyFutureByPartitionId.get(partitionId);
+
+ if (partitionDestroyFuture != null) {
+ try {
+ // TODO: IGNITE-18565 We need to return a CompletableFuture
+ partitionDestroyFuture.get(10, TimeUnit.SECONDS);
+ } catch (Exception e) {
+ throw new StorageException(
+ IgniteStringFormatter.format(
+ "Error waiting for the destruction of the previous version of the partition: [table={}, partitionId={}]",
+ getTableName(),
+ partitionId
+ ),
+ e
+ );
+ }
+ }
+ }
}
diff --git a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/VolatilePageMemoryTableStorage.java b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/VolatilePageMemoryTableStorage.java
index fb6cf5f178..240a3fc0a2 100644
--- a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/VolatilePageMemoryTableStorage.java
+++ b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/VolatilePageMemoryTableStorage.java
@@ -17,6 +17,7 @@
package org.apache.ignite.internal.storage.pagememory;
+import static java.util.concurrent.CompletableFuture.completedFuture;
import static org.apache.ignite.internal.pagememory.PageIdAllocator.FLAG_AUX;
import java.util.concurrent.CompletableFuture;
@@ -44,8 +45,9 @@ public class VolatilePageMemoryTableStorage extends AbstractPageMemoryTableStora
/**
* Constructor.
*
- * @param tableCfg – Table configuration.
- * @param dataRegion – Data region for the table.
+ * @param tableCfg Table configuration.
+ * @param tablesCfg Tables configuration.
+ * @param dataRegion Data region for the table.
*/
public VolatilePageMemoryTableStorage(
TableConfiguration tableCfg,
@@ -72,7 +74,6 @@ public class VolatilePageMemoryTableStorage extends AbstractPageMemoryTableStora
return new VolatilePageMemoryMvPartitionStorage(
this,
- tablesCfg,
partitionId,
versionChainTree,
indexMetaTree,
@@ -145,19 +146,7 @@ public class VolatilePageMemoryTableStorage extends AbstractPageMemoryTableStora
}
@Override
- public CompletableFuture<Void> startRebalancePartition(int partitionId) {
- // TODO: IGNITE-18028 Implement
- throw new UnsupportedOperationException();
- }
-
- @Override
- public CompletableFuture<Void> abortRebalancePartition(int partitionId) {
- // TODO: IGNITE-18028 Implement
- throw new UnsupportedOperationException();
- }
-
- @Override
- public CompletableFuture<Void> finishRebalancePartition(int partitionId, long lastAppliedIndex, long lastAppliedTerm) {
+ CompletableFuture<Void> clearStorageAndUpdateDataStructures(AbstractPageMemoryMvPartitionStorage mvPartitionStorage) {
// TODO: IGNITE-18028 Implement
throw new UnsupportedOperationException();
}
@@ -172,6 +161,6 @@ public class VolatilePageMemoryTableStorage extends AbstractPageMemoryTableStora
// we don't care when it finishes.
volatilePartitionStorage.destroyStructures();
- return CompletableFuture.completedFuture(null);
+ return completedFuture(null);
}
}
diff --git a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/index/hash/PageMemoryHashIndexStorage.java b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/index/hash/PageMemoryHashIndexStorage.java
index fe2422f229..8641c96d17 100644
--- a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/index/hash/PageMemoryHashIndexStorage.java
+++ b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/index/hash/PageMemoryHashIndexStorage.java
@@ -17,20 +17,27 @@
package org.apache.ignite.internal.storage.pagememory.index.hash;
-import java.util.concurrent.atomic.AtomicBoolean;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionDependingOnStorageState;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionDependingOnStorageStateOnRebalance;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionIfStorageInProgressOfRebalance;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionIfStorageNotInProgressOfRebalance;
+
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import org.apache.ignite.internal.schema.BinaryTuple;
import org.apache.ignite.internal.storage.RowId;
-import org.apache.ignite.internal.storage.StorageClosedException;
import org.apache.ignite.internal.storage.StorageException;
+import org.apache.ignite.internal.storage.StorageRebalanceException;
import org.apache.ignite.internal.storage.index.HashIndexDescriptor;
import org.apache.ignite.internal.storage.index.HashIndexStorage;
import org.apache.ignite.internal.storage.index.IndexRow;
import org.apache.ignite.internal.storage.pagememory.index.freelist.IndexColumns;
import org.apache.ignite.internal.storage.pagememory.index.freelist.IndexColumnsFreeList;
+import org.apache.ignite.internal.storage.util.StorageState;
import org.apache.ignite.internal.util.Cursor;
import org.apache.ignite.internal.util.IgniteSpinBusyLock;
import org.apache.ignite.lang.IgniteInternalCheckedException;
+import org.apache.ignite.lang.IgniteStringFormatter;
/**
* Implementation of Hash index storage using Page Memory.
@@ -40,10 +47,10 @@ public class PageMemoryHashIndexStorage implements HashIndexStorage {
private final HashIndexDescriptor descriptor;
/** Free list to store index columns. */
- private final IndexColumnsFreeList freeList;
+ private volatile IndexColumnsFreeList freeList;
/** Hash index tree instance. */
- private final HashIndexTree hashIndexTree;
+ private volatile HashIndexTree hashIndexTree;
/** Partition id. */
private final int partitionId;
@@ -54,11 +61,11 @@ public class PageMemoryHashIndexStorage implements HashIndexStorage {
/** Highest possible RowId according to signed long ordering. */
private final RowId highestRowId;
- /** Busy lock for synchronous closing. */
+ /** Busy lock. */
private final IgniteSpinBusyLock busyLock = new IgniteSpinBusyLock();
- /** Prevents double stopping of the component. */
- private final AtomicBoolean stopGuard = new AtomicBoolean();
+ /** Current state of the storage. */
+ private final AtomicReference<StorageState> state = new AtomicReference<>(StorageState.RUNNABLE);
/**
* Constructor.
@@ -87,6 +94,8 @@ public class PageMemoryHashIndexStorage implements HashIndexStorage {
@Override
public Cursor<RowId> get(BinaryTuple key) throws StorageException {
return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
try {
IndexColumns indexColumns = new IndexColumns(partitionId, key.byteBuffer());
@@ -103,12 +112,20 @@ public class PageMemoryHashIndexStorage implements HashIndexStorage {
@Override
public boolean hasNext() {
- return busy(cursor::hasNext);
+ return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), PageMemoryHashIndexStorage.this::createStorageInfo);
+
+ return cursor.hasNext();
+ });
}
@Override
public RowId next() {
- return busy(() -> cursor.next().rowId());
+ return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), PageMemoryHashIndexStorage.this::createStorageInfo);
+
+ return cursor.next().rowId();
+ });
}
};
} catch (IgniteInternalCheckedException e) {
@@ -139,6 +156,8 @@ public class PageMemoryHashIndexStorage implements HashIndexStorage {
@Override
public void remove(IndexRow row) throws StorageException {
busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
try {
IndexColumns indexColumns = new IndexColumns(partitionId, row.indexColumns().byteBuffer());
@@ -168,7 +187,11 @@ public class PageMemoryHashIndexStorage implements HashIndexStorage {
* Closes the hash index storage.
*/
public void close() {
- if (!stopGuard.compareAndSet(false, true)) {
+ if (!state.compareAndSet(StorageState.RUNNABLE, StorageState.CLOSED)) {
+ StorageState state = this.state.get();
+
+ assert state == StorageState.CLOSED : state;
+
return;
}
@@ -179,7 +202,7 @@ public class PageMemoryHashIndexStorage implements HashIndexStorage {
private <V> V busy(Supplier<V> supplier) {
if (!busyLock.enterBusy()) {
- throw new StorageClosedException();
+ throwExceptionDependingOnStorageState(state.get(), createStorageInfo());
}
try {
@@ -188,4 +211,53 @@ public class PageMemoryHashIndexStorage implements HashIndexStorage {
busyLock.leaveBusy();
}
}
+
+ /**
+ * Prepares storage for rebalancing.
+ *
+ * @throws StorageRebalanceException If there was an error when starting the rebalance.
+ */
+ public void startRebalance() {
+ if (!state.compareAndSet(StorageState.RUNNABLE, StorageState.REBALANCE)) {
+ throwExceptionDependingOnStorageStateOnRebalance(state.get(), createStorageInfo());
+ }
+
+ // Changed storage states and expect all storage operations to stop soon.
+ busyLock.block();
+
+ try {
+ this.hashIndexTree.close();
+ } finally {
+ busyLock.unblock();
+ }
+ }
+
+ /**
+ * Completes the rebalancing of the storage.
+ *
+ * @throws StorageRebalanceException If there is an error while completing the storage rebalance.
+ */
+ public void completeRebalance() {
+ if (!state.compareAndSet(StorageState.REBALANCE, StorageState.RUNNABLE)) {
+ throwExceptionDependingOnStorageStateOnRebalance(state.get(), createStorageInfo());
+ }
+ }
+
+ /**
+ * Updates the internal data structures of the storage on rebalance.
+ *
+ * @param freeList Free list to store index columns.
+ * @param hashIndexTree Hash index tree instance.
+ * @throws StorageRebalanceException If the storage is not in the process of rebalancing.
+ */
+ public void updateDataStructuresOnRebalance(IndexColumnsFreeList freeList, HashIndexTree hashIndexTree) {
+ throwExceptionIfStorageNotInProgressOfRebalance(state.get(), this::createStorageInfo);
+
+ this.freeList = freeList;
+ this.hashIndexTree = hashIndexTree;
+ }
+
+ private String createStorageInfo() {
+ return IgniteStringFormatter.format("indexId={}, partitionId={}", descriptor.id(), partitionId);
+ }
}
diff --git a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/index/sorted/PageMemorySortedIndexStorage.java b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/index/sorted/PageMemorySortedIndexStorage.java
index 46c730d8a3..45b8b98dcf 100644
--- a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/index/sorted/PageMemorySortedIndexStorage.java
+++ b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/index/sorted/PageMemorySortedIndexStorage.java
@@ -17,9 +17,14 @@
package org.apache.ignite.internal.storage.pagememory.index.sorted;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionDependingOnStorageState;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionDependingOnStorageStateOnRebalance;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionIfStorageInProgressOfRebalance;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionIfStorageNotInProgressOfRebalance;
+
import java.nio.ByteBuffer;
import java.util.NoSuchElementException;
-import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.ignite.internal.binarytuple.BinaryTupleCommon;
@@ -28,6 +33,7 @@ import org.apache.ignite.internal.schema.BinaryTuplePrefix;
import org.apache.ignite.internal.storage.RowId;
import org.apache.ignite.internal.storage.StorageClosedException;
import org.apache.ignite.internal.storage.StorageException;
+import org.apache.ignite.internal.storage.StorageRebalanceException;
import org.apache.ignite.internal.storage.index.IndexRow;
import org.apache.ignite.internal.storage.index.IndexRowImpl;
import org.apache.ignite.internal.storage.index.PeekCursor;
@@ -35,9 +41,11 @@ import org.apache.ignite.internal.storage.index.SortedIndexDescriptor;
import org.apache.ignite.internal.storage.index.SortedIndexStorage;
import org.apache.ignite.internal.storage.pagememory.index.freelist.IndexColumns;
import org.apache.ignite.internal.storage.pagememory.index.freelist.IndexColumnsFreeList;
+import org.apache.ignite.internal.storage.util.StorageState;
import org.apache.ignite.internal.util.Cursor;
import org.apache.ignite.internal.util.IgniteSpinBusyLock;
import org.apache.ignite.lang.IgniteInternalCheckedException;
+import org.apache.ignite.lang.IgniteStringFormatter;
import org.jetbrains.annotations.Nullable;
/**
@@ -48,10 +56,10 @@ public class PageMemorySortedIndexStorage implements SortedIndexStorage {
private final SortedIndexDescriptor descriptor;
/** Free list to store index columns. */
- private final IndexColumnsFreeList freeList;
+ private volatile IndexColumnsFreeList freeList;
/** Sorted index tree instance. */
- private final SortedIndexTree sortedIndexTree;
+ private volatile SortedIndexTree sortedIndexTree;
/** Partition id. */
private final int partitionId;
@@ -62,11 +70,11 @@ public class PageMemorySortedIndexStorage implements SortedIndexStorage {
/** Highest possible RowId according to signed long ordering. */
private final RowId highestRowId;
- /** Busy lock for synchronous closing. */
+ /** Busy lock. */
private final IgniteSpinBusyLock busyLock = new IgniteSpinBusyLock();
- /** Prevents double stopping of the component. */
- private final AtomicBoolean stopGuard = new AtomicBoolean();
+ /** Current state of the storage. */
+ private final AtomicReference<StorageState> state = new AtomicReference<>(StorageState.RUNNABLE);
/**
* Constructor.
@@ -95,6 +103,8 @@ public class PageMemorySortedIndexStorage implements SortedIndexStorage {
@Override
public Cursor<RowId> get(BinaryTuple key) throws StorageException {
return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
try {
SortedIndexRowKey lowerBound = toSortedIndexRow(key, lowestRowId);
@@ -127,6 +137,8 @@ public class PageMemorySortedIndexStorage implements SortedIndexStorage {
@Override
public void remove(IndexRow row) {
busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
try {
SortedIndexRow sortedIndexRow = toSortedIndexRow(row.indexColumns(), row.rowId());
@@ -147,6 +159,8 @@ public class PageMemorySortedIndexStorage implements SortedIndexStorage {
@Override
public PeekCursor<IndexRow> scan(@Nullable BinaryTuplePrefix lowerBound, @Nullable BinaryTuplePrefix upperBound, int flags) {
return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
boolean includeLower = (flags & GREATER_OR_EQUAL) != 0;
boolean includeUpper = (flags & LESS_OR_EQUAL) != 0;
@@ -189,7 +203,11 @@ public class PageMemorySortedIndexStorage implements SortedIndexStorage {
* Closes the sorted index storage.
*/
public void close() {
- if (!stopGuard.compareAndSet(false, true)) {
+ if (!state.compareAndSet(StorageState.RUNNABLE, StorageState.CLOSED)) {
+ StorageState state = this.state.get();
+
+ assert state == StorageState.CLOSED : state;
+
return;
}
@@ -214,12 +232,20 @@ public class PageMemorySortedIndexStorage implements SortedIndexStorage {
@Override
public boolean hasNext() {
- return busy(cursor::hasNext);
+ return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), PageMemorySortedIndexStorage.this::createStorageInfo);
+
+ return cursor.hasNext();
+ });
}
@Override
public R next() {
- return busy(() -> mapper.apply(cursor.next()));
+ return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), PageMemorySortedIndexStorage.this::createStorageInfo);
+
+ return mapper.apply(cursor.next());
+ });
}
};
}
@@ -284,6 +310,8 @@ public class PageMemorySortedIndexStorage implements SortedIndexStorage {
@Override
public @Nullable IndexRow peek() {
return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), PageMemorySortedIndexStorage.this::createStorageInfo);
+
if (hasNext != null) {
if (hasNext) {
return toIndexRowImpl(treeRow);
@@ -313,6 +341,8 @@ public class PageMemorySortedIndexStorage implements SortedIndexStorage {
}
private void advanceIfNeeded() throws IgniteInternalCheckedException {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), PageMemorySortedIndexStorage.this::createStorageInfo);
+
if (hasNext != null) {
return;
}
@@ -344,7 +374,7 @@ public class PageMemorySortedIndexStorage implements SortedIndexStorage {
private <V> V busy(Supplier<V> supplier) {
if (!busyLock.enterBusy()) {
- throw new StorageClosedException();
+ throwExceptionDependingOnStorageState(state.get(), createStorageInfo());
}
try {
@@ -353,4 +383,53 @@ public class PageMemorySortedIndexStorage implements SortedIndexStorage {
busyLock.leaveBusy();
}
}
+
+ /**
+ * Prepares storage for rebalancing.
+ *
+ * @throws StorageRebalanceException If there was an error when starting the rebalance.
+ */
+ public void startRebalance() {
+ if (!state.compareAndSet(StorageState.RUNNABLE, StorageState.REBALANCE)) {
+ throwExceptionDependingOnStorageStateOnRebalance(state.get(), createStorageInfo());
+ }
+
+ // Changed storage states and expect all storage operations to stop soon.
+ busyLock.block();
+
+ try {
+ this.sortedIndexTree.close();
+ } finally {
+ busyLock.unblock();
+ }
+ }
+
+ /**
+ * Completes the rebalancing of the storage.
+ *
+ * @throws StorageRebalanceException If there is an error while completing the storage rebalance.
+ */
+ public void completeRebalance() {
+ if (!state.compareAndSet(StorageState.REBALANCE, StorageState.RUNNABLE)) {
+ throwExceptionDependingOnStorageStateOnRebalance(state.get(), createStorageInfo());
+ }
+ }
+
+ /**
+ * Updates the internal data structures of the storage on rebalance.
+ *
+ * @param freeList Free list to store index columns.
+ * @param sortedIndexTree Sorted index tree instance.
+ * @throws StorageRebalanceException If the storage is not in the process of rebalancing.
+ */
+ public void updateDataStructuresOnRebalance(IndexColumnsFreeList freeList, SortedIndexTree sortedIndexTree) {
+ throwExceptionIfStorageNotInProgressOfRebalance(state.get(), this::createStorageInfo);
+
+ this.freeList = freeList;
+ this.sortedIndexTree = sortedIndexTree;
+ }
+
+ private String createStorageInfo() {
+ return IgniteStringFormatter.format("indexId={}, partitionId={}", descriptor.id(), partitionId);
+ }
}
diff --git a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/mv/AbstractPageMemoryMvPartitionStorage.java b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/mv/AbstractPageMemoryMvPartitionStorage.java
index 5496706fd4..5e2ca0f718 100644
--- a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/mv/AbstractPageMemoryMvPartitionStorage.java
+++ b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/mv/AbstractPageMemoryMvPartitionStorage.java
@@ -19,6 +19,9 @@ package org.apache.ignite.internal.storage.pagememory.mv;
import static org.apache.ignite.internal.configuration.util.ConfigurationUtil.getByInternalId;
import static org.apache.ignite.internal.pagememory.util.PageIdUtils.NULL_LINK;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionDependingOnStorageState;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionDependingOnStorageStateOnRebalance;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionIfStorageInProgressOfRebalance;
import java.nio.ByteBuffer;
import java.util.ArrayList;
@@ -27,8 +30,8 @@ import java.util.NoSuchElementException;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.apache.ignite.configuration.NamedListView;
@@ -40,7 +43,6 @@ import org.apache.ignite.internal.pagememory.metric.IoStatisticsHolderNoOp;
import org.apache.ignite.internal.pagememory.util.PageLockListenerNoOp;
import org.apache.ignite.internal.schema.BinaryRow;
import org.apache.ignite.internal.schema.ByteBufferRow;
-import org.apache.ignite.internal.schema.configuration.TablesConfiguration;
import org.apache.ignite.internal.schema.configuration.index.HashIndexView;
import org.apache.ignite.internal.schema.configuration.index.SortedIndexView;
import org.apache.ignite.internal.schema.configuration.index.TableIndexView;
@@ -50,6 +52,7 @@ import org.apache.ignite.internal.storage.ReadResult;
import org.apache.ignite.internal.storage.RowId;
import org.apache.ignite.internal.storage.StorageClosedException;
import org.apache.ignite.internal.storage.StorageException;
+import org.apache.ignite.internal.storage.StorageRebalanceException;
import org.apache.ignite.internal.storage.TxIdMismatchException;
import org.apache.ignite.internal.storage.index.HashIndexDescriptor;
import org.apache.ignite.internal.storage.index.SortedIndexDescriptor;
@@ -62,10 +65,12 @@ import org.apache.ignite.internal.storage.pagememory.index.meta.IndexMeta;
import org.apache.ignite.internal.storage.pagememory.index.meta.IndexMetaTree;
import org.apache.ignite.internal.storage.pagememory.index.sorted.PageMemorySortedIndexStorage;
import org.apache.ignite.internal.storage.pagememory.index.sorted.SortedIndexTree;
+import org.apache.ignite.internal.storage.util.StorageState;
import org.apache.ignite.internal.util.Cursor;
import org.apache.ignite.internal.util.IgniteSpinBusyLock;
import org.apache.ignite.internal.util.IgniteUtils;
import org.apache.ignite.lang.IgniteInternalCheckedException;
+import org.apache.ignite.lang.IgniteStringFormatter;
import org.jetbrains.annotations.Nullable;
/**
@@ -82,13 +87,13 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
protected final AbstractPageMemoryTableStorage tableStorage;
- protected final VersionChainTree versionChainTree;
+ protected volatile VersionChainTree versionChainTree;
- protected final RowVersionFreeList rowVersionFreeList;
+ protected volatile RowVersionFreeList rowVersionFreeList;
- protected final IndexColumnsFreeList indexFreeList;
+ protected volatile IndexColumnsFreeList indexFreeList;
- protected final IndexMetaTree indexMetaTree;
+ protected volatile IndexMetaTree indexMetaTree;
protected final DataPageReader rowVersionDataPageReader;
@@ -96,16 +101,16 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
protected final ConcurrentMap<UUID, PageMemorySortedIndexStorage> sortedIndexes = new ConcurrentHashMap<>();
- /** Busy lock for synchronous closing. */
+ /** Busy lock. */
protected final IgniteSpinBusyLock busyLock = new IgniteSpinBusyLock();
- /** Prevents double stopping of the component. */
- protected final AtomicBoolean stopGuard = new AtomicBoolean();
+ /** Current state of the storage. */
+ protected final AtomicReference<StorageState> state = new AtomicReference<>(StorageState.RUNNABLE);
/**
* Constructor.
*
- * @param partitionId Partition id.
+ * @param partitionId Partition ID.
* @param tableStorage Table storage instance.
* @param rowVersionFreeList Free list for {@link RowVersion}.
* @param indexFreeList Free list fot {@link IndexColumns}.
@@ -118,8 +123,7 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
RowVersionFreeList rowVersionFreeList,
IndexColumnsFreeList indexFreeList,
VersionChainTree versionChainTree,
- IndexMetaTree indexMetaTree,
- TablesConfiguration tablesCfg
+ IndexMetaTree indexMetaTree
) {
this.partitionId = partitionId;
this.tableStorage = tableStorage;
@@ -151,9 +155,9 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
TableIndexView indexCfgView = getByInternalId(indexesCfgView, indexMeta.id());
if (indexCfgView instanceof HashIndexView) {
- createOrRestoreHashIndex(indexMeta);
+ hashIndexes.put(indexCfgView.id(), createOrRestoreHashIndex(indexMeta));
} else if (indexCfgView instanceof SortedIndexView) {
- createOrRestoreSortedIndex(indexMeta);
+ sortedIndexes.put(indexCfgView.id(), createOrRestoreSortedIndex(indexMeta));
} else {
assert indexCfgView == null;
@@ -196,6 +200,12 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
private PageMemoryHashIndexStorage createOrRestoreHashIndex(IndexMeta indexMeta) {
var indexDescriptor = new HashIndexDescriptor(indexMeta.id(), tableStorage.tablesConfiguration().value());
+ HashIndexTree hashIndexTree = createHashIndexTree(indexDescriptor, indexMeta);
+
+ return new PageMemoryHashIndexStorage(indexDescriptor, indexFreeList, hashIndexTree);
+ }
+
+ HashIndexTree createHashIndexTree(HashIndexDescriptor indexDescriptor, IndexMeta indexMeta) {
try {
PageMemory pageMemory = tableStorage.dataRegion().pageMemory();
@@ -205,11 +215,9 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
? pageMemory.allocatePage(groupId, partitionId, PageIdAllocator.FLAG_AUX)
: indexMeta.metaPageId();
- String tableName = tableStorage.configuration().value().name();
-
HashIndexTree hashIndexTree = new HashIndexTree(
groupId,
- tableName,
+ tableStorage.getTableName(),
partitionId,
pageMemory,
PageLockListenerNoOp.INSTANCE,
@@ -226,15 +234,29 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
assert !replaced;
}
- return new PageMemoryHashIndexStorage(indexDescriptor, indexFreeList, hashIndexTree);
+ return hashIndexTree;
} catch (IgniteInternalCheckedException e) {
- throw new RuntimeException(e);
+ throw new StorageException(
+ IgniteStringFormatter.format(
+ "Error creating hash index tree: [table={}, partitionId={}, indexId={}]",
+ tableStorage.getTableName(),
+ partitionId,
+ indexMeta.id()
+ ),
+ e
+ );
}
}
private PageMemorySortedIndexStorage createOrRestoreSortedIndex(IndexMeta indexMeta) {
var indexDescriptor = new SortedIndexDescriptor(indexMeta.id(), tableStorage.tablesConfiguration().value());
+ SortedIndexTree sortedIndexTree = createSortedIndexTree(indexDescriptor, indexMeta);
+
+ return new PageMemorySortedIndexStorage(indexDescriptor, indexFreeList, sortedIndexTree);
+ }
+
+ SortedIndexTree createSortedIndexTree(SortedIndexDescriptor indexDescriptor, IndexMeta indexMeta) {
try {
PageMemory pageMemory = tableStorage.dataRegion().pageMemory();
@@ -244,11 +266,9 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
? pageMemory.allocatePage(groupId, partitionId, PageIdAllocator.FLAG_AUX)
: indexMeta.metaPageId();
- String tableName = tableStorage.configuration().value().name();
-
SortedIndexTree sortedIndexTree = new SortedIndexTree(
groupId,
- tableName,
+ tableStorage.getTableName(),
partitionId,
pageMemory,
PageLockListenerNoOp.INSTANCE,
@@ -265,15 +285,25 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
assert !replaced;
}
- return new PageMemorySortedIndexStorage(indexDescriptor, indexFreeList, sortedIndexTree);
+ return sortedIndexTree;
} catch (IgniteInternalCheckedException e) {
- throw new RuntimeException(e);
+ throw new StorageException(
+ IgniteStringFormatter.format(
+ "Error creating sorted index tree: [table={}, partitionId={}, indexId={}]",
+ tableStorage.getTableName(),
+ partitionId,
+ indexMeta.id()
+ ),
+ e
+ );
}
}
@Override
public ReadResult read(RowId rowId, HybridTimestamp timestamp) throws StorageException {
return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
if (rowId.partitionId() != partitionId) {
throw new IllegalArgumentException(
String.format("RowId partition [%d] is not equal to storage partition [%d].", rowId.partitionId(), partitionId));
@@ -533,6 +563,8 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
assert rowId.partitionId() == partitionId : rowId;
return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
VersionChain currentVersionChain = findVersionChain(rowId);
if (currentVersionChain == null || currentVersionChain.transactionId() == null) {
@@ -658,7 +690,11 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
@Override
public Cursor<ReadResult> scanVersions(RowId rowId) throws StorageException {
- return busy(() -> new ScanVersionsCursor(rowId));
+ return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
+ return new ScanVersionsCursor(rowId);
+ });
}
private static ReadResult rowVersionToResultNotFillingLastCommittedTs(VersionChain versionChain, RowVersion rowVersion) {
@@ -681,6 +717,8 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
@Override
public PartitionTimestampCursor scan(HybridTimestamp timestamp) throws StorageException {
return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
Cursor<VersionChain> treeCursor;
try {
@@ -700,6 +738,8 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
@Override
public @Nullable RowId closestRowId(RowId lowerBound) throws StorageException {
return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
try (Cursor<VersionChain> cursor = versionChainTree.find(new VersionChainKey(lowerBound), null)) {
return cursor.hasNext() ? cursor.next().rowId() : null;
} catch (Exception e) {
@@ -711,6 +751,8 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
@Override
public long rowsCount() {
return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
try {
return versionChainTree.size();
} catch (IgniteInternalCheckedException e) {
@@ -735,6 +777,8 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
@Override
public final ReadResult next() {
return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), AbstractPageMemoryMvPartitionStorage.this::createStorageInfo);
+
if (!hasNext()) {
throw new NoSuchElementException("The cursor is exhausted");
}
@@ -757,6 +801,8 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
@Override
public @Nullable BinaryRow committed(HybridTimestamp timestamp) {
return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), AbstractPageMemoryMvPartitionStorage.this::createStorageInfo);
+
if (currentChain == null) {
throw new IllegalStateException();
}
@@ -791,6 +837,8 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
@Override
public boolean hasNext() {
return busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), AbstractPageMemoryMvPartitionStorage.this::createStorageInfo);
+
if (nextRead != null) {
return true;
}
@@ -802,6 +850,8 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
currentChain = null;
while (true) {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), AbstractPageMemoryMvPartitionStorage.this::createStorageInfo);
+
if (!treeCursor.hasNext()) {
iterationExhausted = true;
@@ -915,6 +965,8 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
}
private void advanceIfNeeded() {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), AbstractPageMemoryMvPartitionStorage.this::createStorageInfo);
+
if (hasNext != null) {
return;
}
@@ -937,7 +989,11 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
@Override
public void close() {
- if (!stopGuard.compareAndSet(false, true)) {
+ if (!state.compareAndSet(StorageState.RUNNABLE, StorageState.CLOSED)) {
+ StorageState state = this.state.get();
+
+ assert state == StorageState.CLOSED : state;
+
return;
}
@@ -978,7 +1034,7 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
*/
protected <V> V busy(Supplier<V> supplier) {
if (!busyLock.enterBusy()) {
- throw new StorageClosedException();
+ throwExceptionDependingOnStorageState(state.get(), createStorageInfo());
}
try {
@@ -987,4 +1043,68 @@ public abstract class AbstractPageMemoryMvPartitionStorage implements MvPartitio
busyLock.leaveBusy();
}
}
+
+ /**
+ * Creates a summary info of the storage in the format "table=user, partitionId=1".
+ */
+ public String createStorageInfo() {
+ return IgniteStringFormatter.format("table={}, partitionId={}", tableStorage.getTableName(), partitionId);
+ }
+
+ /**
+ * Prepares the storage and its indexes for rebalancing.
+ *
+ * <p>Stops ongoing operations on the storage and its indexes.
+ *
+ * @throws StorageRebalanceException If there was an error when starting the rebalance.
+ */
+ public void startRebalance() {
+ if (!state.compareAndSet(StorageState.RUNNABLE, StorageState.REBALANCE)) {
+ throwExceptionDependingOnStorageStateOnRebalance(state.get(), createStorageInfo());
+ }
+
+ // Changed storage states and expect all storage operations to stop soon.
+ busyLock.block();
+
+ try {
+ IgniteUtils.closeAll(getResourcesToCloseOnRebalance());
+
+ hashIndexes.values().forEach(PageMemoryHashIndexStorage::startRebalance);
+ sortedIndexes.values().forEach(PageMemorySortedIndexStorage::startRebalance);
+ } catch (Exception e) {
+ throw new StorageRebalanceException(
+ IgniteStringFormatter.format("Error on start of rebalancing: [{}]", createStorageInfo()),
+ e
+ );
+ } finally {
+ busyLock.unblock();
+ }
+ }
+
+ /**
+ * Completes the rebalancing of the storage and its indexes.
+ *
+ * @throws StorageRebalanceException If there is an error while completing the storage and its indexes rebalance.
+ */
+ public void completeRebalance() {
+ if (!state.compareAndSet(StorageState.REBALANCE, StorageState.RUNNABLE)) {
+ throwExceptionDependingOnStorageStateOnRebalance(state.get(), createStorageInfo());
+ }
+
+ hashIndexes.values().forEach(PageMemoryHashIndexStorage::completeRebalance);
+ sortedIndexes.values().forEach(PageMemorySortedIndexStorage::completeRebalance);
+ }
+
+ /**
+ * Sets the last applied index and term on rebalance.
+ *
+ * @param lastAppliedIndex Last applied index value.
+ * @param lastAppliedTerm Last applied term value.
+ */
+ public abstract void lastAppliedOnRebalance(long lastAppliedIndex, long lastAppliedTerm) throws StorageException;
+
+ /**
+ * Returns resources that will have to close on rebalancing.
+ */
+ abstract List<AutoCloseable> getResourcesToCloseOnRebalance();
}
diff --git a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/mv/PersistentPageMemoryMvPartitionStorage.java b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/mv/PersistentPageMemoryMvPartitionStorage.java
index 6576debc83..a19abb6ddf 100644
--- a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/mv/PersistentPageMemoryMvPartitionStorage.java
+++ b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/mv/PersistentPageMemoryMvPartitionStorage.java
@@ -17,6 +17,9 @@
package org.apache.ignite.internal.storage.pagememory.mv;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionIfStorageInProgressOfRebalance;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionIfStorageNotInProgressOfRebalance;
+
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -33,15 +36,16 @@ import org.apache.ignite.internal.pagememory.persistence.checkpoint.CheckpointPr
import org.apache.ignite.internal.pagememory.persistence.checkpoint.CheckpointState;
import org.apache.ignite.internal.pagememory.persistence.checkpoint.CheckpointTimeoutLock;
import org.apache.ignite.internal.pagememory.tree.BplusTree;
-import org.apache.ignite.internal.schema.configuration.TablesConfiguration;
import org.apache.ignite.internal.storage.MvPartitionStorage;
import org.apache.ignite.internal.storage.RaftGroupConfiguration;
import org.apache.ignite.internal.storage.StorageException;
+import org.apache.ignite.internal.storage.StorageRebalanceException;
import org.apache.ignite.internal.storage.pagememory.PersistentPageMemoryTableStorage;
import org.apache.ignite.internal.storage.pagememory.configuration.schema.PersistentPageMemoryStorageEngineView;
import org.apache.ignite.internal.storage.pagememory.index.freelist.IndexColumns;
import org.apache.ignite.internal.storage.pagememory.index.freelist.IndexColumnsFreeList;
import org.apache.ignite.internal.storage.pagememory.index.hash.PageMemoryHashIndexStorage;
+import org.apache.ignite.internal.storage.pagememory.index.meta.IndexMeta;
import org.apache.ignite.internal.storage.pagememory.index.meta.IndexMetaTree;
import org.apache.ignite.internal.storage.pagememory.index.sorted.PageMemorySortedIndexStorage;
import org.apache.ignite.internal.util.ByteUtils;
@@ -59,7 +63,7 @@ public class PersistentPageMemoryMvPartitionStorage extends AbstractPageMemoryMv
private final CheckpointTimeoutLock checkpointTimeoutLock;
/** Partition meta instance. */
- private final PartitionMeta meta;
+ private volatile PartitionMeta meta;
/** Value of currently persisted last applied index. */
private volatile long persistedIndex;
@@ -67,7 +71,7 @@ public class PersistentPageMemoryMvPartitionStorage extends AbstractPageMemoryMv
/** Checkpoint listener. */
private final CheckpointListener checkpointListener;
- private final BlobStorage blobStorage;
+ private volatile BlobStorage blobStorage;
/** Lock that protects group config read/write. */
private final ReadWriteLock replicationProtocolGroupConfigReadWriteLock = new ReentrantReadWriteLock();
@@ -90,10 +94,9 @@ public class PersistentPageMemoryMvPartitionStorage extends AbstractPageMemoryMv
RowVersionFreeList rowVersionFreeList,
IndexColumnsFreeList indexFreeList,
VersionChainTree versionChainTree,
- IndexMetaTree indexMetaTree,
- TablesConfiguration tablesCfg
+ IndexMetaTree indexMetaTree
) {
- super(partitionId, tableStorage, rowVersionFreeList, indexFreeList, versionChainTree, indexMetaTree, tablesCfg);
+ super(partitionId, tableStorage, rowVersionFreeList, indexFreeList, versionChainTree, indexMetaTree);
checkpointManager = tableStorage.engine().checkpointManager();
checkpointTimeoutLock = checkpointManager.checkpointTimeoutLock();
@@ -178,18 +181,24 @@ public class PersistentPageMemoryMvPartitionStorage extends AbstractPageMemoryMv
@Override
public void lastApplied(long lastAppliedIndex, long lastAppliedTerm) throws StorageException {
busy(() -> {
- assert checkpointTimeoutLock.checkpointLockIsHeldByThread();
-
- CheckpointProgress lastCheckpoint = checkpointManager.lastCheckpointProgress();
-
- UUID lastCheckpointId = lastCheckpoint == null ? null : lastCheckpoint.id();
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
- meta.lastApplied(lastCheckpointId, lastAppliedIndex, lastAppliedTerm);
+ lastAppliedBusy(lastAppliedIndex, lastAppliedTerm);
return null;
});
}
+ private void lastAppliedBusy(long lastAppliedIndex, long lastAppliedTerm) throws StorageException {
+ assert checkpointTimeoutLock.checkpointLockIsHeldByThread();
+
+ CheckpointProgress lastCheckpoint = checkpointManager.lastCheckpointProgress();
+
+ UUID lastCheckpointId = lastCheckpoint == null ? null : lastCheckpoint.id();
+
+ meta.lastApplied(lastCheckpointId, lastAppliedIndex, lastAppliedTerm);
+ }
+
@Override
public long persistedIndex() {
return busy(() -> persistedIndex);
@@ -226,6 +235,8 @@ public class PersistentPageMemoryMvPartitionStorage extends AbstractPageMemoryMv
busy(() -> {
assert checkpointTimeoutLock.checkpointLockIsHeldByThread();
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
CheckpointProgress lastCheckpoint = checkpointManager.lastCheckpointProgress();
UUID lastCheckpointId = lastCheckpoint == null ? null : lastCheckpoint.id();
@@ -316,4 +327,73 @@ public class PersistentPageMemoryMvPartitionStorage extends AbstractPageMemoryMv
});
}
}
+
+ @Override
+ public void lastAppliedOnRebalance(long lastAppliedIndex, long lastAppliedTerm) throws StorageException {
+ throwExceptionIfStorageNotInProgressOfRebalance(state.get(), this::createStorageInfo);
+
+ lastAppliedBusy(lastAppliedIndex, lastAppliedTerm);
+
+ persistedIndex = lastAppliedIndex;
+ }
+
+ /**
+ * Updates the internal data structures of the storage and its indexes on rebalance.
+ *
+ * @param meta Partition meta.
+ * @param rowVersionFreeList Free list for {@link RowVersion}.
+ * @param indexFreeList Free list fot {@link IndexColumns}.
+ * @param versionChainTree Table tree for {@link VersionChain}.
+ * @param indexMetaTree Tree that contains SQL indexes' metadata.
+ * @throws StorageRebalanceException If the storage is not in the process of rebalancing.
+ */
+ public void updateDataStructuresOnRebalance(
+ PartitionMeta meta,
+ RowVersionFreeList rowVersionFreeList,
+ IndexColumnsFreeList indexFreeList,
+ VersionChainTree versionChainTree,
+ IndexMetaTree indexMetaTree
+ ) {
+ throwExceptionIfStorageNotInProgressOfRebalance(state.get(), this::createStorageInfo);
+
+ this.meta = meta;
+
+ this.rowVersionFreeList = rowVersionFreeList;
+ this.indexFreeList = indexFreeList;
+ this.versionChainTree = versionChainTree;
+ this.indexMetaTree = indexMetaTree;
+
+ this.blobStorage = new BlobStorage(
+ rowVersionFreeList,
+ tableStorage.dataRegion().pageMemory(),
+ tableStorage.configuration().tableId().value(),
+ partitionId,
+ IoStatisticsHolderNoOp.INSTANCE
+ );
+
+ for (PageMemoryHashIndexStorage indexStorage : hashIndexes.values()) {
+ indexStorage.updateDataStructuresOnRebalance(
+ indexFreeList,
+ createHashIndexTree(indexStorage.indexDescriptor(), new IndexMeta(indexStorage.indexDescriptor().id(), 0L))
+ );
+ }
+
+ for (PageMemorySortedIndexStorage indexStorage : sortedIndexes.values()) {
+ indexStorage.updateDataStructuresOnRebalance(
+ indexFreeList,
+ createSortedIndexTree(indexStorage.indexDescriptor(), new IndexMeta(indexStorage.indexDescriptor().id(), 0L))
+ );
+ }
+ }
+
+ @Override
+ List<AutoCloseable> getResourcesToCloseOnRebalance() {
+ return List.of(
+ rowVersionFreeList::close,
+ indexFreeList::close,
+ versionChainTree::close,
+ indexMetaTree::close,
+ blobStorage::close
+ );
+ }
}
diff --git a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/mv/VolatilePageMemoryMvPartitionStorage.java b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/mv/VolatilePageMemoryMvPartitionStorage.java
index 0c7fc0b5bd..3cdcfcb073 100644
--- a/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/mv/VolatilePageMemoryMvPartitionStorage.java
+++ b/modules/storage-page-memory/src/main/java/org/apache/ignite/internal/storage/pagememory/mv/VolatilePageMemoryMvPartitionStorage.java
@@ -18,14 +18,16 @@
package org.apache.ignite.internal.storage.pagememory.mv;
import static java.util.concurrent.CompletableFuture.completedFuture;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionIfStorageInProgressOfRebalance;
+import static org.apache.ignite.internal.storage.util.StorageUtils.throwExceptionIfStorageNotInProgressOfRebalance;
+import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import org.apache.ignite.internal.hlc.HybridTimestamp;
import org.apache.ignite.internal.pagememory.tree.BplusTree;
import org.apache.ignite.internal.pagememory.util.GradualTaskExecutor;
import org.apache.ignite.internal.pagememory.util.PageIdUtils;
-import org.apache.ignite.internal.schema.configuration.TablesConfiguration;
import org.apache.ignite.internal.storage.MvPartitionStorage;
import org.apache.ignite.internal.storage.RaftGroupConfiguration;
import org.apache.ignite.internal.storage.StorageException;
@@ -64,7 +66,6 @@ public class VolatilePageMemoryMvPartitionStorage extends AbstractPageMemoryMvPa
*/
public VolatilePageMemoryMvPartitionStorage(
VolatilePageMemoryTableStorage tableStorage,
- TablesConfiguration tablesCfg,
int partitionId,
VersionChainTree versionChainTree,
IndexMetaTree indexMetaTree,
@@ -76,8 +77,7 @@ public class VolatilePageMemoryMvPartitionStorage extends AbstractPageMemoryMvPa
tableStorage.dataRegion().rowVersionFreeList(),
tableStorage.dataRegion().indexColumnsFreeList(),
versionChainTree,
- indexMetaTree,
- tablesCfg
+ indexMetaTree
);
this.destructionExecutor = destructionExecutor;
@@ -106,6 +106,8 @@ public class VolatilePageMemoryMvPartitionStorage extends AbstractPageMemoryMvPa
@Override
public void lastApplied(long lastAppliedIndex, long lastAppliedTerm) throws StorageException {
busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
this.lastAppliedIndex = lastAppliedIndex;
this.lastAppliedTerm = lastAppliedTerm;
@@ -125,7 +127,21 @@ public class VolatilePageMemoryMvPartitionStorage extends AbstractPageMemoryMvPa
@Override
public void committedGroupConfiguration(RaftGroupConfiguration config) {
- this.groupConfig = config;
+ busy(() -> {
+ throwExceptionIfStorageInProgressOfRebalance(state.get(), this::createStorageInfo);
+
+ groupConfig = config;
+
+ return null;
+ });
+ }
+
+ @Override
+ public void lastAppliedOnRebalance(long lastAppliedIndex, long lastAppliedTerm) throws StorageException {
+ throwExceptionIfStorageNotInProgressOfRebalance(state.get(), this::createStorageInfo);
+
+ this.lastAppliedIndex = lastAppliedIndex;
+ this.lastAppliedTerm = lastAppliedTerm;
}
/**
@@ -164,4 +180,10 @@ public class VolatilePageMemoryMvPartitionStorage extends AbstractPageMemoryMvPa
rowVersionLink = rowVersion.nextLink();
}
}
+
+ @Override
+ List<AutoCloseable> getResourcesToCloseOnRebalance() {
+ // TODO: IGNITE-18028 Implement
+ throw new UnsupportedOperationException();
+ }
}
diff --git a/modules/storage-page-memory/src/test/java/org/apache/ignite/internal/storage/pagememory/PersistentPageMemoryMvTableStorageTest.java b/modules/storage-page-memory/src/test/java/org/apache/ignite/internal/storage/pagememory/PersistentPageMemoryMvTableStorageTest.java
index c65cec3e05..01e6cbc673 100644
--- a/modules/storage-page-memory/src/test/java/org/apache/ignite/internal/storage/pagememory/PersistentPageMemoryMvTableStorageTest.java
+++ b/modules/storage-page-memory/src/test/java/org/apache/ignite/internal/storage/pagememory/PersistentPageMemoryMvTableStorageTest.java
@@ -25,14 +25,10 @@ import org.apache.ignite.internal.pagememory.io.PageIoRegistry;
import org.apache.ignite.internal.pagememory.persistence.checkpoint.CheckpointState;
import org.apache.ignite.internal.schema.configuration.TablesConfiguration;
import org.apache.ignite.internal.storage.AbstractMvTableStorageTest;
-import org.apache.ignite.internal.storage.engine.MvTableStorage;
import org.apache.ignite.internal.storage.pagememory.configuration.schema.PersistentPageMemoryStorageEngineConfiguration;
import org.apache.ignite.internal.testframework.WorkDirectory;
import org.apache.ignite.internal.testframework.WorkDirectoryExtension;
-import org.apache.ignite.internal.util.IgniteUtils;
-import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -41,10 +37,6 @@ import org.junit.jupiter.api.extension.ExtendWith;
*/
@ExtendWith({ConfigurationExtension.class, WorkDirectoryExtension.class})
public class PersistentPageMemoryMvTableStorageTest extends AbstractMvTableStorageTest {
- private PersistentPageMemoryStorageEngine engine;
-
- private MvTableStorage tableStorage;
-
@BeforeEach
void setUp(
@WorkDirectory
@@ -52,7 +44,7 @@ public class PersistentPageMemoryMvTableStorageTest extends AbstractMvTableStora
@InjectConfiguration
PersistentPageMemoryStorageEngineConfiguration engineConfig,
@InjectConfiguration(
- value = "mock.tables.foo{ partitions = 512, dataStorage.name = " + PersistentPageMemoryStorageEngine.ENGINE_NAME + "}"
+ "mock.tables.foo{ partitions = 512, dataStorage.name = " + PersistentPageMemoryStorageEngine.ENGINE_NAME + "}"
)
TablesConfiguration tablesConfig
) {
@@ -60,23 +52,7 @@ public class PersistentPageMemoryMvTableStorageTest extends AbstractMvTableStora
ioRegistry.loadFromServiceLoader();
- engine = new PersistentPageMemoryStorageEngine("test", engineConfig, ioRegistry, workDir, null);
-
- engine.start();
-
- tableStorage = engine.createMvTable(tablesConfig.tables().get("foo"), tablesConfig);
-
- tableStorage.start();
-
- initialize(tableStorage, tablesConfig);
- }
-
- @AfterEach
- void tearDown() throws Exception {
- IgniteUtils.closeAll(
- tableStorage == null ? null : tableStorage::stop,
- engine == null ? null : engine::stop
- );
+ initialize(new PersistentPageMemoryStorageEngine("test", engineConfig, ioRegistry, workDir, null), tablesConfig);
}
@Test
@@ -85,27 +61,9 @@ public class PersistentPageMemoryMvTableStorageTest extends AbstractMvTableStora
super.testDestroyPartition();
// Let's make sure that the checkpoint doesn't fail.
- engine.checkpointManager()
+ ((PersistentPageMemoryStorageEngine) storageEngine).checkpointManager()
.forceCheckpoint("after-test-destroy-partition")
.futureFor(CheckpointState.FINISHED)
.get(1, TimeUnit.SECONDS);
}
-
- @Disabled("https://issues.apache.org/jira/browse/IGNITE-18029")
- @Override
- public void testSuccessRebalance() throws Exception {
- super.testSuccessRebalance();
- }
-
- @Disabled("https://issues.apache.org/jira/browse/IGNITE-18029")
- @Override
- public void testFailRebalance() throws Exception {
- super.testFailRebalance();
- }
-
- @Disabled("https://issues.apache.org/jira/browse/IGNITE-18029")
- @Override
- public void testStartRebalanceForClosedPartition() {
- super.testStartRebalanceForClosedPartition();
- }
}
diff --git a/modules/storage-page-memory/src/test/java/org/apache/ignite/internal/storage/pagememory/VolatilePageMemoryMvTableStorageTest.java b/modules/storage-page-memory/src/test/java/org/apache/ignite/internal/storage/pagememory/VolatilePageMemoryMvTableStorageTest.java
index d351034cfb..4c14d38804 100644
--- a/modules/storage-page-memory/src/test/java/org/apache/ignite/internal/storage/pagememory/VolatilePageMemoryMvTableStorageTest.java
+++ b/modules/storage-page-memory/src/test/java/org/apache/ignite/internal/storage/pagememory/VolatilePageMemoryMvTableStorageTest.java
@@ -37,9 +37,7 @@ import org.apache.ignite.internal.storage.AbstractMvTableStorageTest;
import org.apache.ignite.internal.storage.MvPartitionStorage;
import org.apache.ignite.internal.storage.RowId;
import org.apache.ignite.internal.storage.pagememory.configuration.schema.VolatilePageMemoryStorageEngineConfiguration;
-import org.apache.ignite.internal.util.IgniteUtils;
import org.apache.ignite.lang.IgniteInternalCheckedException;
-import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@@ -52,10 +50,6 @@ import org.junit.jupiter.api.extension.ExtendWith;
public class VolatilePageMemoryMvTableStorageTest extends AbstractMvTableStorageTest {
private final PageEvictionTracker pageEvictionTracker = spy(PageEvictionTrackerNoOp.INSTANCE);
- private VolatilePageMemoryStorageEngine engine;
-
- private VolatilePageMemoryTableStorage tableStorage;
-
@BeforeEach
void setUp(
@InjectConfiguration
@@ -69,23 +63,7 @@ public class VolatilePageMemoryMvTableStorageTest extends AbstractMvTableStorage
ioRegistry.loadFromServiceLoader();
- engine = new VolatilePageMemoryStorageEngine("node", engineConfig, ioRegistry, pageEvictionTracker);
-
- engine.start();
-
- tableStorage = engine.createMvTable(tablesConfig.tables().get("foo"), tablesConfig);
-
- tableStorage.start();
-
- initialize(tableStorage, tablesConfig);
- }
-
- @AfterEach
- void tearDown() throws Exception {
- IgniteUtils.closeAll(
- tableStorage == null ? null : tableStorage::stop,
- engine == null ? null : engine::stop
- );
+ initialize(new VolatilePageMemoryStorageEngine("node", engineConfig, ioRegistry, pageEvictionTracker), tablesConfig);
}
@Disabled("https://issues.apache.org/jira/browse/IGNITE-18028")
@@ -112,7 +90,7 @@ public class VolatilePageMemoryMvTableStorageTest extends AbstractMvTableStorage
insertOneRow(partitionStorage);
- long emptyDataPagesBeforeDestroy = tableStorage.dataRegion().rowVersionFreeList().emptyDataPages();
+ long emptyDataPagesBeforeDestroy = dataRegion().rowVersionFreeList().emptyDataPages();
assertThat(tableStorage.destroyPartition(0), willSucceedFast());
@@ -121,7 +99,7 @@ public class VolatilePageMemoryMvTableStorageTest extends AbstractMvTableStorage
private void assertDestructionCompletes(long emptyDataPagesBeforeDestroy) throws InterruptedException, IgniteInternalCheckedException {
assertTrue(waitForCondition(
- () -> tableStorage.dataRegion().rowVersionFreeList().emptyDataPages() > emptyDataPagesBeforeDestroy,
+ () -> dataRegion().rowVersionFreeList().emptyDataPages() > emptyDataPagesBeforeDestroy,
5_000
));
@@ -144,10 +122,14 @@ public class VolatilePageMemoryMvTableStorageTest extends AbstractMvTableStorage
insertOneRow(partitionStorage);
- long emptyDataPagesBeforeDestroy = tableStorage.dataRegion().rowVersionFreeList().emptyDataPages();
+ long emptyDataPagesBeforeDestroy = dataRegion().rowVersionFreeList().emptyDataPages();
assertThat(tableStorage.destroy(), willSucceedFast());
assertDestructionCompletes(emptyDataPagesBeforeDestroy);
}
+
+ private VolatilePageMemoryDataRegion dataRegion() {
+ return ((VolatilePageMemoryTableStorage) tableStorage).dataRegion();
+ }
}
diff --git a/modules/storage-rocksdb/src/test/java/org/apache/ignite/internal/storage/rocksdb/RocksDbMvTableStorageTest.java b/modules/storage-rocksdb/src/test/java/org/apache/ignite/internal/storage/rocksdb/RocksDbMvTableStorageTest.java
index 51ea832730..3a56c297de 100644
--- a/modules/storage-rocksdb/src/test/java/org/apache/ignite/internal/storage/rocksdb/RocksDbMvTableStorageTest.java
+++ b/modules/storage-rocksdb/src/test/java/org/apache/ignite/internal/storage/rocksdb/RocksDbMvTableStorageTest.java
@@ -18,7 +18,6 @@
package org.apache.ignite.internal.storage.rocksdb;
import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
@@ -34,12 +33,9 @@ import org.apache.ignite.internal.schema.configuration.TablesConfiguration;
import org.apache.ignite.internal.storage.AbstractMvTableStorageTest;
import org.apache.ignite.internal.storage.MvPartitionStorage;
import org.apache.ignite.internal.storage.RowId;
-import org.apache.ignite.internal.storage.engine.MvTableStorage;
import org.apache.ignite.internal.storage.rocksdb.configuration.schema.RocksDbStorageEngineConfiguration;
import org.apache.ignite.internal.testframework.WorkDirectory;
import org.apache.ignite.internal.testframework.WorkDirectoryExtension;
-import org.apache.ignite.internal.util.IgniteUtils;
-import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@@ -51,40 +47,17 @@ import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(WorkDirectoryExtension.class)
@ExtendWith(ConfigurationExtension.class)
public class RocksDbMvTableStorageTest extends AbstractMvTableStorageTest {
- @InjectConfiguration(
- value = "mock.tables.foo{ partitions = 512, dataStorage.name = " + RocksDbStorageEngine.ENGINE_NAME + "}"
- )
- private TablesConfiguration tablesConfig;
-
- private RocksDbStorageEngine engine;
-
- private MvTableStorage tableStorage;
-
@BeforeEach
void setUp(
@WorkDirectory Path workDir,
@InjectConfiguration("mock {flushDelayMillis = 0, defaultRegion {size = 16536, writeBufferSize = 16536}}")
- RocksDbStorageEngineConfiguration rocksDbEngineConfig
+ RocksDbStorageEngineConfiguration rocksDbEngineConfig,
+ @InjectConfiguration(
+ "mock.tables.foo{ partitions = 512, dataStorage.name = " + RocksDbStorageEngine.ENGINE_NAME + "}"
+ )
+ TablesConfiguration tablesConfig
) {
- engine = new RocksDbStorageEngine(rocksDbEngineConfig, workDir);
-
- engine.start();
-
- tableStorage = engine.createMvTable(tablesConfig.tables().get("foo"), tablesConfig);
-
- assertThat(tableStorage, is(instanceOf(RocksDbTableStorage.class)));
-
- tableStorage.start();
-
- initialize(tableStorage, tablesConfig);
- }
-
- @AfterEach
- void tearDown() throws Exception {
- IgniteUtils.closeAll(
- tableStorage == null ? null : tableStorage::stop,
- engine == null ? null : engine::stop
- );
+ initialize(new RocksDbStorageEngine(rocksDbEngineConfig, workDir), tablesConfig);
}
/**
@@ -137,7 +110,7 @@ public class RocksDbMvTableStorageTest extends AbstractMvTableStorageTest {
tableStorage.stop();
- tableStorage = engine.createMvTable(tablesConfig.tables().get("foo"), tablesConfig);
+ tableStorage = createMvTableStorage(tableStorage.tablesConfiguration());
tableStorage.start();
@@ -180,4 +153,11 @@ public class RocksDbMvTableStorageTest extends AbstractMvTableStorageTest {
public void testDestroyTableStorage() throws Exception {
super.testDestroyTableStorage();
}
+
+ @Test
+ @Disabled("https://issues.apache.org/jira/browse/IGNITE-18027")
+ @Override
+ public void testRestartStoragesAfterFailDuringRebalance() {
+ super.testRestartStoragesAfterFailDuringRebalance();
+ }
}
diff --git a/modules/transactions/src/main/java/org/apache/ignite/internal/tx/storage/state/rocksdb/TxStateRocksDbStorage.java b/modules/transactions/src/main/java/org/apache/ignite/internal/tx/storage/state/rocksdb/TxStateRocksDbStorage.java
index aa34d1d7a8..6d3200f278 100644
--- a/modules/transactions/src/main/java/org/apache/ignite/internal/tx/storage/state/rocksdb/TxStateRocksDbStorage.java
+++ b/modules/transactions/src/main/java/org/apache/ignite/internal/tx/storage/state/rocksdb/TxStateRocksDbStorage.java
@@ -637,7 +637,7 @@ public class TxStateRocksDbStorage implements TxStateStorage {
}
/**
- * Tries to close the repository with resources if it hasn't already been closed.
+ * Tries to close the storage with resources if it hasn't already been closed.
*
* @return {@code True} if the storage was successfully closed, otherwise the storage has already been closed.
*/