This is an automated email from the ASF dual-hosted git repository.

adoroszlai pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git


The following commit(s) were added to refs/heads/master by this push:
     new 1cba8584289 HDDS-17089. SCM that stops during snapshot install after 
the DB swap restarts pre-finalized and shuts down every finalized datanode 
(#11800)
1cba8584289 is described below

commit 1cba85842891db3f46798c0ae4780b9d26952f31
Author: Stephen O'Donnell <[email protected]>
AuthorDate: Fri Nov 6 20:11:35 2026 +0000

    HDDS-17089. SCM that stops during snapshot install after the DB swap 
restarts pre-finalized and shuts down every finalized datanode (#11800)
---
 .../ozone/upgrade/ComponentVersionManager.java     |  26 ++-
 .../ozone/upgrade/RatisBasedVersionManager.java    |  43 +++-
 .../hdds/scm/server/StorageContainerManager.java   |   3 +
 .../upgrade/FinalizationStateManagerImpl.java      |   2 +-
 .../TestScmStartupInvalidApparentVersion.java      |  91 --------
 ...estScmStartupWithDifferentApparentVersions.java | 259 +++++++++++++++++++++
 .../hdds/scm/TestStorageContainerManagerHA.java    |  57 ++---
 .../hadoop/hdds/upgrade/TestScmHAFinalization.java |   6 +-
 .../hadoop/ozone/om/TestOMUpgradeFinalization.java |   3 +-
 .../org/apache/hadoop/ozone/om/OzoneManager.java   |   2 +-
 10 files changed, 344 insertions(+), 148 deletions(-)

diff --git 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/ozone/upgrade/ComponentVersionManager.java
 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/ozone/upgrade/ComponentVersionManager.java
index 5aaa48aec1a..125dc514749 100644
--- 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/ozone/upgrade/ComponentVersionManager.java
+++ 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/ozone/upgrade/ComponentVersionManager.java
@@ -90,8 +90,22 @@ public boolean needsFinalization() {
   public abstract int getPersistedApparentVersion();
 
   public void finalizeUpgrade() throws UpgradeException {
+    finalizeUpgrade(softwareVersion);
+  }
+
+  /**
+   * Finalizes each version after the current apparent version, up to and 
including {@code targetVersion}. Does nothing
+   * if {@code targetVersion} is already finalized.
+   *
+   * @param targetVersion The last version to finalize. Must be supported by 
the software version.
+   */
+  public void finalizeUpgrade(ComponentVersion targetVersion) throws 
UpgradeException {
+    if (!targetVersion.isSupportedBy(softwareVersion)) {
+      throw new IllegalArgumentException("Cannot finalize to version " + 
targetVersion
+          + " which is newer than software version " + softwareVersion + ".");
+    }
     ComponentVersion prevVersion = apparentVersion;
-    for (ComponentVersion newVersion : getUnfinalizedVersions()) {
+    for (ComponentVersion newVersion : getUnfinalizedVersions(targetVersion)) {
       validateForFinalization(newVersion);
       runUpgradeAction(newVersion);
       persistApparentVersion(newVersion, prevVersion);
@@ -110,16 +124,18 @@ public void finalizeUpgrade() throws UpgradeException {
   public abstract ComponentVersion getVersionForClient();
 
   /**
-   * @return An Iterable of all versions after the current apparent version 
which still need to be finalized. If this
-   *    component is already finalized, the Iterable will be empty.
+   * @return An Iterable of all versions after the current apparent version, 
up to and including
+   *    {@code targetVersion}, which still need to be finalized. If {@code 
targetVersion} is already finalized, the
+   *    Iterable will be empty.
    */
-  private Iterable<ComponentVersion> getUnfinalizedVersions() {
+  private Iterable<ComponentVersion> getUnfinalizedVersions(ComponentVersion 
targetVersion) {
     return () -> new Iterator<ComponentVersion>() {
       private ComponentVersion currentVersion = apparentVersion;
 
       @Override
       public boolean hasNext() {
-        return currentVersion.nextVersion() != null;
+        ComponentVersion nextVersion = currentVersion.nextVersion();
+        return nextVersion != null && nextVersion.isSupportedBy(targetVersion);
       }
 
       @Override
diff --git 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/ozone/upgrade/RatisBasedVersionManager.java
 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/ozone/upgrade/RatisBasedVersionManager.java
index e6d31cc4275..2c6a5df8de2 100644
--- 
a/hadoop-hdds/framework/src/main/java/org/apache/hadoop/ozone/upgrade/RatisBasedVersionManager.java
+++ 
b/hadoop-hdds/framework/src/main/java/org/apache/hadoop/ozone/upgrade/RatisBasedVersionManager.java
@@ -46,15 +46,40 @@ public void validateDBVersion(Table<String, String> 
finalizationStore) throws IO
     }
   }
 
-  public void finalizeFromSnapshotIfRequired(Table<String, String> 
finalizationStore) throws IOException {
-    ComponentVersion apparentVersionInNewDB = 
getApparentVersionInDB(finalizationStore);
-    if (apparentVersionInNewDB != null && !isAllowed(apparentVersionInNewDB)) {
-      LOG.info("New snapshot received with higher apparent version {}. 
Attempting to finalize to that version.",
-          apparentVersionInNewDB);
-      finalizeUpgrade();
-      // Update the apparent version in the DB to match the VERSION file.
-      // When finalization is not done with a snapshot, this DB value is 
updated by OMCompleteFinalizeUpgradeRequest.
-      finalizationStore.put(APPARENT_VERSION_KEY, 
String.valueOf(getApparentVersion().serialize()));
+  public void finalizeFromDBIfRequired(Table<String, String> 
finalizationStore) throws IOException {
+    // This call is expected to throw and crash the process if the apparent 
version in the DB is larger than our
+    // software version, which we cannot support.
+    ComponentVersion apparentVersionInDB = 
getApparentVersionInDB(finalizationStore);
+    if (apparentVersionInDB == null) {
+      LOG.debug("Component has apparent version {} but no apparent version was 
found in the DB. That is expected if " +
+          "this component has never been finalized to a newer version.", 
getApparentVersion());
+    } else if (!apparentVersionInDB.equals(getApparentVersion())) {
+      // We only need to take potential action if DB version != apparent 
version.
+      if (isAllowed(apparentVersionInDB)) {
+        // DB version < apparent version.
+        LOG.debug("Received apparent version {} in DB which is less than the 
current apparent version {}. " +
+            "Component likely previously crashed during finalization. Ratis 
log replay should correct this issue " +
+            "after startup.",
+            apparentVersionInDB, getApparentVersion());
+      } else {
+        // DB version > apparent version. We must finalize to this version.
+        if (apparentVersionInDB.isSupportedBy(getSoftwareVersion()) &&
+            !apparentVersionInDB.equals(getSoftwareVersion())) {
+          // DB version < software version.
+          // This should never happen. When restarting after failed 
finalization, the DB should not have been updated
+          // until all versions up to the software version were finalized. On 
the snapshot installation path all
+          // components should be running the same software version when 
finalization is run.
+          LOG.warn("Received apparent version {} in DB which is between the 
current apparent version {} " +
+              "and the software version {}. User may have incorrectly run 
finalization in a mixed version " +
+              "cluster.", apparentVersionInDB, getApparentVersion(), 
getSoftwareVersion());
+        } else {
+          // DB version == software version. This is expected when we receive 
finalization from a Ratis snapshot.
+          // The previous attempt to finalize from a snapshot may have failed, 
so we will resume it here.
+          LOG.info("Version file has lower apparent version ({}) than DB ({}). 
Finalizing to the DB version.",
+              getApparentVersion(), apparentVersionInDB);
+        }
+        finalizeUpgrade(apparentVersionInDB);
+      }
     }
   }
 
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/StorageContainerManager.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/StorageContainerManager.java
index b292c8a6e08..ae4bd0d96ab 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/StorageContainerManager.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/StorageContainerManager.java
@@ -1536,6 +1536,9 @@ public CertificateStore getCertificateStore() {
    */
   @Override
   public void start() throws IOException {
+    // If the SCM stopped during a snapshot install after the DB was replaced, 
the VERSION file is behind the DB, and
+    // the finalization included in the snapshot is not in the Raft log to be 
replayed.
+    versionManager.finalizeFromDBIfRequired(scmMetadataStore.getMetaTable());
     if (LOG.isInfoEnabled()) {
       LOG.info(buildRpcServerStartMessage(
           "StorageContainerLocationProtocol RPC server",
diff --git 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/upgrade/FinalizationStateManagerImpl.java
 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/upgrade/FinalizationStateManagerImpl.java
index f83cd4fefc3..c2c4cbeb073 100644
--- 
a/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/upgrade/FinalizationStateManagerImpl.java
+++ 
b/hadoop-hdds/server-scm/src/main/java/org/apache/hadoop/hdds/scm/server/upgrade/FinalizationStateManagerImpl.java
@@ -59,7 +59,7 @@ public void finalizeUpgrade() throws IOException {
   public void reinitialize(Table<String, String> newFinalizationStore) throws 
IOException {
     try {
       this.finalizationStore = newFinalizationStore;
-      versionManager.finalizeFromSnapshotIfRequired(finalizationStore);
+      versionManager.finalizeFromDBIfRequired(finalizationStore);
     } catch (Exception ex) {
       LOG.error("Failed to reinitialize finalization state", ex);
       throw new IOException(ex);
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/upgrade/TestScmStartupInvalidApparentVersion.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/upgrade/TestScmStartupInvalidApparentVersion.java
deleted file mode 100644
index 16272a2fb33..00000000000
--- 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/upgrade/TestScmStartupInvalidApparentVersion.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.hadoop.hdds.scm.upgrade;
-
-import static org.apache.hadoop.hdds.HDDSVersion.SOFTWARE_VERSION;
-import static org.apache.hadoop.ozone.OzoneConsts.SCM_HA;
-import static org.apache.hadoop.ozone.OzoneConsts.SCM_ID;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.Path;
-import java.util.Properties;
-import org.apache.hadoop.hdds.HDDSVersion;
-import org.apache.hadoop.hdds.HddsConfigKeys;
-import org.apache.hadoop.hdds.conf.OzoneConfiguration;
-import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
-import org.apache.hadoop.hdds.scm.ScmConfigKeys;
-import org.apache.hadoop.hdds.scm.server.StorageContainerManager;
-import org.apache.hadoop.hdds.upgrade.HDDSLayoutFeature;
-import org.apache.hadoop.ozone.upgrade.UpgradeTestUtils;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.io.TempDir;
-
-/**
- * Ensures SCM does not start when the VERSION file records an apparent version
- * that is larger than the software version.
- */
-public class TestScmStartupInvalidApparentVersion {
-
-  @TempDir
-  private Path folder;
-
-  @Test
-  public void 
testStartupFailsWhenApparentVersionBetweenLastLayoutFeatureAndZdu() throws 
Exception {
-    assertStartupFailsWithComponentVersionMessage(
-        HDDSLayoutFeature.STORAGE_SPACE_DISTRIBUTION.serialize() + 1);
-  }
-
-  @Test
-  public void 
testStartupFailsWhenApparentVersionBeyondLastKnownComponentVersion() throws 
Exception {
-    assertStartupFailsWithComponentVersionMessage(SOFTWARE_VERSION.serialize() 
+ 1);
-  }
-
-  private void assertStartupFailsWithComponentVersionMessage(int 
serializedApparentVersion)
-      throws Exception {
-    File scmSubdir = folder.resolve("scm").resolve("current").toFile();
-    assertTrue(scmSubdir.mkdirs());
-
-    File ratisDir = folder.resolve("scm.ratis").toFile();
-    File snapshotDir = folder.resolve("scm.ratis.snapshot").toFile();
-    assertTrue(ratisDir.mkdirs());
-    assertTrue(snapshotDir.mkdirs());
-
-    OzoneConfiguration conf = new OzoneConfiguration();
-    conf.set(ScmConfigKeys.OZONE_SCM_DB_DIRS, 
folder.toAbsolutePath().toString());
-    conf.set(HddsConfigKeys.OZONE_METADATA_DIRS, 
folder.toAbsolutePath().toString());
-
-    Properties properties = new Properties();
-    properties.setProperty(SCM_ID, "scm");
-    properties.setProperty(SCM_HA, "true");
-
-    UpgradeTestUtils.createVersionFile(scmSubdir, HddsProtos.NodeType.SCM, 
serializedApparentVersion, properties);
-
-    String expectedMessage =
-        "Initialization failed. Disk contains unknown apparent version " + 
serializedApparentVersion
-            + " for software version " + HDDSVersion.SOFTWARE_VERSION + ". 
Make sure this component was not" +
-            " downgraded after finalization";
-
-    IOException ioException =
-        assertThrows(IOException.class, () -> new 
StorageContainerManager(conf));
-    assertEquals(expectedMessage, ioException.getMessage());
-  }
-}
diff --git 
a/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/upgrade/TestScmStartupWithDifferentApparentVersions.java
 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/upgrade/TestScmStartupWithDifferentApparentVersions.java
new file mode 100644
index 00000000000..643266211c7
--- /dev/null
+++ 
b/hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/upgrade/TestScmStartupWithDifferentApparentVersions.java
@@ -0,0 +1,259 @@
+/*
+ * 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.hadoop.hdds.scm.upgrade;
+
+import static org.apache.hadoop.hdds.HDDSVersion.SOFTWARE_VERSION;
+import static org.apache.hadoop.hdds.HDDSVersion.ZDU;
+import static org.apache.hadoop.hdds.upgrade.HDDSLayoutFeature.INITIAL_VERSION;
+import static org.apache.hadoop.ozone.OzoneConsts.APPARENT_VERSION_KEY;
+import static org.apache.hadoop.ozone.OzoneConsts.SCM_HA;
+import static org.apache.hadoop.ozone.OzoneConsts.SCM_ID;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Properties;
+import org.apache.hadoop.hdds.ComponentVersion;
+import org.apache.hadoop.hdds.HDDSVersion;
+import org.apache.hadoop.hdds.HddsConfigKeys;
+import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.scm.HddsTestUtils;
+import org.apache.hadoop.hdds.scm.ScmConfigKeys;
+import org.apache.hadoop.hdds.scm.server.SCMConfigurator;
+import org.apache.hadoop.hdds.scm.server.SCMStorageConfig;
+import org.apache.hadoop.hdds.scm.server.StorageContainerManager;
+import org.apache.hadoop.hdds.upgrade.HDDSLayoutFeature;
+import org.apache.hadoop.ozone.upgrade.UpgradeTestUtils;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+/**
+ * Ensures SCM does not start when the VERSION file records an apparent version
+ * that is larger than the software version, and that it finalizes on startup
+ * when the DB records a higher apparent version than the VERSION file.
+ */
+public class TestScmStartupWithDifferentApparentVersions {
+
+  @TempDir
+  private Path folder;
+
+  @Test
+  public void 
testStartupFailsWhenApparentVersionBetweenLastLayoutFeatureAndZdu() throws 
Exception {
+    assertStartupFailsWithComponentVersionMessage(
+        HDDSLayoutFeature.STORAGE_SPACE_DISTRIBUTION.serialize() + 1);
+  }
+
+  @Test
+  public void 
testStartupFailsWhenApparentVersionBeyondLastKnownComponentVersion() throws 
Exception {
+    assertStartupFailsWithComponentVersionMessage(SOFTWARE_VERSION.serialize() 
+ 1);
+  }
+
+  /**
+   * An SCM that stops after replacing its DB with a finalized checkpoint, but 
before updating its VERSION file, cannot
+   * replay the finalization from the Raft log, so it should finalize up to 
the version in its DB on restart.
+   */
+  @Test
+  public void testStartupFinalizesToApparentVersionInDB() throws Exception {
+    OzoneConfiguration conf = createScmStorage(INITIAL_VERSION.serialize());
+    StorageContainerManager scm = HddsTestUtils.getScm(conf, new 
SCMConfigurator());
+    try {
+      // Without a version in the DB, startup leaves the SCM pre-finalized.
+      
assertThat(scm.getScmMetadataStore().getMetaTable().get(APPARENT_VERSION_KEY)).isNull();
+      
assertThat(scm.getVersionManager().getApparentVersion()).isEqualTo(INITIAL_VERSION);
+
+      // The DB is ahead of the VERSION file, as the interrupted install 
leaves it. The SCM finalizes to the
+      // software version
+      scm = restartWithDBVersion(scm, SOFTWARE_VERSION);
+      // finalizeFromDBIfRequired is called by scm.start(), but calling that 
here makes the tests slow and we would
+      // need more setup for safemode etc. As this test is unit testing 
finalizeFromDBIfRequired we call it directly
+      // to keep the tests simple.
+      
scm.getVersionManager().finalizeFromDBIfRequired(scm.getScmMetadataStore().getMetaTable());
+      assertVersions(scm, SOFTWARE_VERSION, SOFTWARE_VERSION);
+      assertThat(scm.getVersionManager().needsFinalization()).isFalse();
+    } finally {
+      scm.stop();
+      scm.join();
+    }
+  }
+
+  /**
+   * The VERSION file is ahead of the DB. This can happen if finalization 
wrote the VERSION file (inside Ratis
+   * applyTransaction) but the process crashed before the Ratis transaction 
buffer was flushed to RocksDB.
+   * Ratis log replay is async and may not have finished when this method 
runs, so this is treated as an expected
+   * case and no action is taken — log replay will correct the DB after 
startup.
+   */
+  @Test
+  public void testFinalizeFromDBNoOpWhenVersionFileAheadOfDB() throws 
Exception {
+    OzoneConfiguration conf = createScmStorage(SOFTWARE_VERSION.serialize());
+    StorageContainerManager scm = HddsTestUtils.getScm(conf, new 
SCMConfigurator());
+    try {
+      // Force the DB to a lower version to simulate the unflushed transaction 
buffer.
+      scm.getScmMetadataStore().getMetaTable().put(APPARENT_VERSION_KEY, 
String.valueOf(ZDU.serialize()));
+      scm.stop();
+      scm.join();
+
+      // On restart, finalizeFromDBIfRequired detects DB version < VERSION 
file version but takes no action.
+      // finalizeFromDBIfRequired is called by scm.start(), but calling that 
here makes the tests slow and we would
+      // need more setup for safemode etc. As this test is unit testing 
finalizeFromDBIfRequired we call it directly
+      // to keep the tests simple.
+      scm = HddsTestUtils.getScm(scm.getConfiguration(), new 
SCMConfigurator());
+      
scm.getVersionManager().finalizeFromDBIfRequired(scm.getScmMetadataStore().getMetaTable());
+      // Apparent version unchanged; DB version also unchanged (left for Ratis 
log replay to correct).
+      assertVersions(scm, SOFTWARE_VERSION, ZDU);
+    } finally {
+      scm.stop();
+      scm.join();
+    }
+  }
+
+  /**
+   * When the DB has no apparent version, the component was never finalized. 
finalizeFromDBIfRequired takes no action.
+   */
+  @Test
+  public void testFinalizeFromDBNoOpWhenDBNull() throws Exception {
+    OzoneConfiguration conf = createScmStorage(INITIAL_VERSION.serialize());
+    StorageContainerManager scm = HddsTestUtils.getScm(conf, new 
SCMConfigurator());
+    try {
+      
assertThat(scm.getScmMetadataStore().getMetaTable().get(APPARENT_VERSION_KEY)).isNull();
+      
scm.getVersionManager().finalizeFromDBIfRequired(scm.getScmMetadataStore().getMetaTable());
+      
assertThat(scm.getVersionManager().getApparentVersion()).isEqualTo(INITIAL_VERSION);
+      
assertThat(scm.getScmMetadataStore().getMetaTable().get(APPARENT_VERSION_KEY)).isNull();
+    } finally {
+      scm.stop();
+      scm.join();
+    }
+  }
+
+  /**
+   * When the DB matches the apparent version, no finalization or update is 
needed.
+   */
+  @Test
+  public void testFinalizeFromDBNoOpWhenDBEqualsApparent() throws Exception {
+    OzoneConfiguration conf = createScmStorage(SOFTWARE_VERSION.serialize());
+    StorageContainerManager scm = HddsTestUtils.getScm(conf, new 
SCMConfigurator());
+    try {
+      scm.getScmMetadataStore().getMetaTable().put(APPARENT_VERSION_KEY, 
String.valueOf(SOFTWARE_VERSION.serialize()));
+      
scm.getVersionManager().finalizeFromDBIfRequired(scm.getScmMetadataStore().getMetaTable());
+      assertVersions(scm, SOFTWARE_VERSION, SOFTWARE_VERSION);
+      assertFalse(scm.getVersionManager().needsFinalization());
+    } finally {
+      scm.stop();
+      scm.join();
+    }
+  }
+
+  /**
+   * The DB version is between the apparent version and the software version. 
This should not happen in practice,
+   * but if it does the safest recovery is to partially finalize up to the DB 
version to avoid mixed apparent versions
+   * in the quorum.
+   */
+  @Test
+  public void testFinalizeFromDBFinalizesToIntermediateDBVersion() throws 
Exception {
+    OzoneConfiguration conf = createScmStorage(INITIAL_VERSION.serialize());
+    StorageContainerManager scm = HddsTestUtils.getScm(conf, new 
SCMConfigurator());
+    try {
+      scm.getScmMetadataStore().getMetaTable().put(APPARENT_VERSION_KEY, 
String.valueOf(ZDU.serialize()));
+      
scm.getVersionManager().finalizeFromDBIfRequired(scm.getScmMetadataStore().getMetaTable());
+      assertVersions(scm, ZDU, ZDU);
+      // Component is not fully finalized: ZDU < SOFTWARE_VERSION.
+      assertTrue(scm.getVersionManager().needsFinalization());
+    } finally {
+      scm.stop();
+      scm.join();
+    }
+  }
+
+  /**
+   * The DB version exceeds the software version. This cannot be supported and 
the process must crash.
+   */
+  @Test
+  public void testFinalizeFromDBThrowsWhenDBVersionExceedsSoftwareVersion() 
throws Exception {
+    OzoneConfiguration conf = createScmStorage(INITIAL_VERSION.serialize());
+    StorageContainerManager scm = HddsTestUtils.getScm(conf, new 
SCMConfigurator());
+    try {
+      scm.getScmMetadataStore().getMetaTable().put(APPARENT_VERSION_KEY,
+          String.valueOf(SOFTWARE_VERSION.serialize() + 1));
+      assertThrows(IOException.class,
+          () -> 
scm.getVersionManager().finalizeFromDBIfRequired(scm.getScmMetadataStore().getMetaTable()));
+    } finally {
+      scm.stop();
+      scm.join();
+    }
+  }
+
+  /**
+   * Writes {@code dbVersion} to the DB of {@code scm}, stops it and creates a 
new SCM on the same storage.
+   */
+  private static StorageContainerManager 
restartWithDBVersion(StorageContainerManager scm, ComponentVersion dbVersion)
+      throws Exception {
+    scm.getScmMetadataStore().getMetaTable().put(APPARENT_VERSION_KEY, 
String.valueOf(dbVersion.serialize()));
+    scm.stop();
+    scm.join();
+    return HddsTestUtils.getScm(scm.getConfiguration(), new SCMConfigurator());
+  }
+
+  private static void assertVersions(StorageContainerManager scm, 
ComponentVersion expectedApparentVersion,
+      ComponentVersion expectedDBVersion) throws IOException {
+    
assertThat(scm.getVersionManager().getApparentVersion()).isEqualTo(expectedApparentVersion);
+    assertThat(new 
SCMStorageConfig(scm.getConfiguration()).getApparentVersion())
+        .isEqualTo(expectedApparentVersion.serialize());
+    
assertThat(scm.getScmMetadataStore().getMetaTable().get(APPARENT_VERSION_KEY))
+        .isEqualTo(String.valueOf(expectedDBVersion.serialize()));
+  }
+
+  private void assertStartupFailsWithComponentVersionMessage(int 
serializedApparentVersion)
+      throws Exception {
+    OzoneConfiguration conf = createScmStorage(serializedApparentVersion);
+
+    String expectedMessage =
+        "Initialization failed. Disk contains unknown apparent version " + 
serializedApparentVersion
+            + " for software version " + HDDSVersion.SOFTWARE_VERSION + ". 
Make sure this component was not" +
+            " downgraded after finalization";
+
+    IOException ioException =
+        assertThrows(IOException.class, () -> new 
StorageContainerManager(conf));
+    assertEquals(expectedMessage, ioException.getMessage());
+  }
+
+  private OzoneConfiguration createScmStorage(int serializedApparentVersion) 
throws IOException {
+    File scmSubdir = folder.resolve("scm").resolve("current").toFile();
+    assertTrue(scmSubdir.mkdirs());
+
+    File ratisDir = folder.resolve("scm.ratis").toFile();
+    File snapshotDir = folder.resolve("scm.ratis.snapshot").toFile();
+    assertTrue(ratisDir.mkdirs());
+    assertTrue(snapshotDir.mkdirs());
+
+    OzoneConfiguration conf = new OzoneConfiguration();
+    conf.set(ScmConfigKeys.OZONE_SCM_DB_DIRS, 
folder.toAbsolutePath().toString());
+    conf.set(HddsConfigKeys.OZONE_METADATA_DIRS, 
folder.toAbsolutePath().toString());
+
+    Properties properties = new Properties();
+    properties.setProperty(SCM_ID, "scm");
+    properties.setProperty(SCM_HA, "true");
+
+    UpgradeTestUtils.createVersionFile(scmSubdir, HddsProtos.NodeType.SCM, 
serializedApparentVersion, properties);
+    return conf;
+  }
+}
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestStorageContainerManagerHA.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestStorageContainerManagerHA.java
index 9ded335c96c..288d7807eef 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestStorageContainerManagerHA.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/scm/TestStorageContainerManagerHA.java
@@ -22,6 +22,7 @@
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.IOException;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.UUID;
 import java.util.concurrent.CountDownLatch;
@@ -146,48 +147,30 @@ public void testSCMLeadershipMetric() throws IOException, 
InterruptedException {
     // in order to initialize and bootstrap SCM instances only
     cluster = haMiniClusterBuilder.build();
 
-    List<StorageContainerManager> storageContainerManagersList = 
cluster.getStorageContainerManagersList();
-
-    // stop the single SCM instance in order to imitate further simultaneous 
start of SCMs
-    storageContainerManagersList.get(0).stop();
-    storageContainerManagersList.get(0).join();
-
-    // WHEN (imitate simultaneous start of the SCMs)
-    int retryCount = 0;
-    while (true) {
-      CountDownLatch scmInstancesCounter = new 
CountDownLatch(scmInstancesCount);
-      AtomicInteger failedSCMs = new AtomicInteger();
-      for (StorageContainerManager scm : storageContainerManagersList) {
-        new Thread(() -> {
-          try {
-            scm.start();
-          } catch (IOException e) {
-            failedSCMs.incrementAndGet();
-          } finally {
-            scmInstancesCounter.countDown();
-          }
-        }).start();
-      }
-      scmInstancesCounter.await();
-      if (failedSCMs.get() == 0) {
-        break;
-      } else {
-        for (StorageContainerManager scm : storageContainerManagersList) {
-          scm.stop();
-          scm.join();
-          LOG.info("Stopping StorageContainerManager server at {}",
-              scm.getClientRpcAddress());
+    // WHEN (imitate simultaneous start of the SCMs that were bootstrapped but 
not started). A stopped SCM cannot be
+    // started again, so the running SCM is left as is.
+    List<StorageContainerManager> inactiveSCMs = new ArrayList<>();
+    cluster.getInactiveSCM().forEachRemaining(inactiveSCMs::add);
+    CountDownLatch scmInstancesCounter = new 
CountDownLatch(inactiveSCMs.size());
+    AtomicInteger failedSCMs = new AtomicInteger();
+    for (StorageContainerManager scm : inactiveSCMs) {
+      new Thread(() -> {
+        try {
+          scm.start();
+        } catch (Exception e) {
+          LOG.error("Failed to start SCM {}", scm.getSCMNodeId(), e);
+          failedSCMs.incrementAndGet();
+        } finally {
+          scmInstancesCounter.countDown();
         }
-        ++retryCount;
-        LOG.info("SCMs port conflicts, retried {} times",
-            retryCount);
-        failedSCMs.set(0);
-      }
+      }).start();
     }
+    scmInstancesCounter.await();
+    assertEquals(0, failedSCMs.get());
 
     // THEN expect only one SCM node (leader) will have 
'scmha_metrics_scmha_leader_state' metric set to 1
     int leaderCount = 0;
-    for (StorageContainerManager scm : storageContainerManagersList) {
+    for (StorageContainerManager scm : 
cluster.getStorageContainerManagersList()) {
       if (scm.getScmHAMetrics() != null && 
scm.getScmHAMetrics().getSCMHAMetricsInfoLeaderState() == 1) {
         leaderCount++;
         break;
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/upgrade/TestScmHAFinalization.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/upgrade/TestScmHAFinalization.java
index a95d0f4b99a..fe479e948f9 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/upgrade/TestScmHAFinalization.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/hdds/upgrade/TestScmHAFinalization.java
@@ -201,8 +201,8 @@ public void testSnapshotFinalization() throws Exception {
     HddsUpgradeTestUtils.testPostUpgradeConditionsSCM(
         inactiveScm, 0);
 
-    // Use log to verify a snapshot was installed.
-    assertThat(logCapture.getOutput()).contains("New snapshot received with 
higher apparent version " +
-        HDDSVersion.SOFTWARE_VERSION + ". Attempting to finalize to that 
version.");
+    // Use log to verify a snapshot was installed and triggered finalization.
+    assertThat(logCapture.getOutput()).contains("Version file has lower 
apparent version (INITIAL_VERSION (0)) than " +
+        "DB (" + HDDSVersion.SOFTWARE_VERSION + "). Finalizing to the DB 
version.");
   }
 }
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMUpgradeFinalization.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMUpgradeFinalization.java
index db9d38ade1c..338f018f6b8 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMUpgradeFinalization.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/om/TestOMUpgradeFinalization.java
@@ -162,7 +162,8 @@ void testFinalizationFromSnapshot() throws Exception {
         assertEquals(OzoneManagerVersion.SOFTWARE_VERSION.serialize(), 
Integer.parseInt(dbVersion));
 
         // Confirm finalization happened via snapshot install, not log replay.
-        assertThat(versionManagerLogCapture.getOutput()).contains("New 
snapshot received with higher apparent version");
+        assertThat(versionManagerLogCapture.getOutput()).contains(
+            "Version file has lower apparent version (INITIAL_VERSION (0)) 
than DB");
         versionManagerLogCapture.stopCapturing();
       }
     }
diff --git 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java
 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java
index 12beaffa2f4..c207586f8ff 100644
--- 
a/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java
+++ 
b/hadoop-ozone/ozone-manager/src/main/java/org/apache/hadoop/ozone/om/OzoneManager.java
@@ -1159,7 +1159,7 @@ public void close() {
     updateActiveSnapshotMetrics();
 
     if (withNewSnapshot) {
-      
versionManager.finalizeFromSnapshotIfRequired(metadataManager.getMetaTable());
+      versionManager.finalizeFromDBIfRequired(metadataManager.getMetaTable());
     }
   }
 


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to