From 1836e0951adda1c169e813703ca8aeaf8ff2886b Mon Sep 17 00:00:00 2001 From: Mashrfee Aryan Date: Mon, 19 Oct 2026 10:26:14 -0500 Subject: [PATCH 01/12] Keep management server IDs stable across restarts Save the initial ID and reuse it when network interfaces change. Add JVM overrides and regression tests for issue #14253. --- .../utils/identity/ManagementServerId.java | 84 ++++++++ .../utils/identity/ManagementServerNode.java | 3 +- .../identity/ManagementServerIdTest.java | 179 ++++++++++++++++++ 3 files changed, 264 insertions(+), 2 deletions(-) create mode 100644 utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java create mode 100644 utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java new file mode 100644 index 000000000000..dcebb5d9ad13 --- /dev/null +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java @@ -0,0 +1,84 @@ +// 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.cloudstack.utils.identity; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.function.LongSupplier; + +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.net.MacAddress; + +final class ManagementServerId { + + private ManagementServerId() { + } + + static long get() { + Path path = Paths.get(System.getProperty("management.server.id.file", + Paths.get(System.getProperty("user.home"), ".cloudstack", "management-server.id").toString())); + try { + return load(path, System.getProperty("management.server.id"), () -> MacAddress.getMacAddress().toLong()); + } catch (IOException | IllegalArgumentException e) { + throw new CloudRuntimeException("Unable to load the management server ID from " + path, e); + } + } + + static long load(Path path, String configuredId, LongSupplier initialId) throws IOException { + if (configuredId != null) { + return parse(configuredId); + } + + Files.createDirectories(path.toAbsolutePath().getParent()); + try (FileChannel lockChannel = FileChannel.open(path.resolveSibling(path.getFileName() + ".lock"), + StandardOpenOption.CREATE, StandardOpenOption.WRITE); + FileLock lock = lockChannel.lock()) { + if (Files.exists(path)) { + if (Files.size(path) > 64) { + throw new IllegalArgumentException("Invalid management server ID file"); + } + return parse(new String(Files.readAllBytes(path), StandardCharsets.UTF_8)); + } + + long id = parse(Long.toString(initialId.getAsLong())); + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) { + ByteBuffer buffer = StandardCharsets.UTF_8.encode(id + "\n"); + while (buffer.hasRemaining()) { + channel.write(buffer); + } + channel.force(true); + } + return id; + } + } + + private static long parse(String value) { + long id = Long.parseLong(value.trim()); + if (id <= 0) { + throw new IllegalArgumentException("Management server ID must be a positive integer"); + } + return id; + } +} diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java index 32989c3497c5..cc85ca18c02b 100644 --- a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java @@ -25,11 +25,10 @@ import com.cloud.utils.component.ComponentLifecycle; import com.cloud.utils.component.SystemIntegrityChecker; import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.MacAddress; public class ManagementServerNode extends AdapterBase implements SystemIntegrityChecker { - private static final long s_nodeId = MacAddress.getMacAddress().toLong(); + private static final long s_nodeId = ManagementServerId.get(); public ManagementServerNode() { setRunLevel(ComponentLifecycle.RUN_LEVEL_FRAMEWORK_BOOTSTRAP); diff --git a/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java new file mode 100644 index 000000000000..030161895206 --- /dev/null +++ b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java @@ -0,0 +1,179 @@ +// 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.cloudstack.utils.identity; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.function.LongSupplier; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import com.cloud.utils.exception.CloudRuntimeException; + +public class ManagementServerIdTest { + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private Path idFile() { + return folder.getRoot().toPath().resolve("identity/management-server.id"); + } + + private LongSupplier unexpectedLookup() { + return () -> { + throw new AssertionError("Network interfaces must not be consulted"); + }; + } + + @Test + public void preservesInitialIdWhenNetworkInterfacesChange() throws IOException { + Path path = idFile(); + assertEquals(130014950130305L, ManagementServerId.load(path, null, () -> 130014950130305L)); + assertEquals(130014950130305L, ManagementServerId.load(path, null, () -> 42L)); + assertEquals(130014950130305L, ManagementServerId.load(path, null, unexpectedLookup())); + } + + @Test + public void configuredIdTakesPrecedenceOverSavedId() throws IOException { + Path path = idFile(); + ManagementServerId.load(path, null, () -> 42L); + assertEquals(123L, ManagementServerId.load(path, "123", unexpectedLookup())); + assertEquals(42L, ManagementServerId.load(path, null, unexpectedLookup())); + } + + @Test + public void configuredIdDoesNotRequireWritableStorage() throws IOException { + Path path = folder.newFile("not-a-directory").toPath().resolve("id"); + assertEquals(123L, ManagementServerId.load(path, "123", unexpectedLookup())); + } + + @Test + public void rejectsInvalidConfiguredIds() { + for (String value : new String[] {"", "0", "-1", "invalid", "9223372036854775808"}) { + assertThrows(IllegalArgumentException.class, + () -> ManagementServerId.load(idFile(), value, unexpectedLookup())); + } + assertFalse(Files.exists(idFile())); + } + + @Test + public void rejectsInvalidSavedIdsWithoutReplacingThem() throws IOException { + Path path = folder.newFile("id").toPath(); + for (String value : new String[] {"", "0", "-1", "invalid", "9223372036854775808", "1".repeat(65)}) { + Files.write(path, value.getBytes(StandardCharsets.UTF_8)); + assertThrows(IllegalArgumentException.class, + () -> ManagementServerId.load(path, null, unexpectedLookup())); + assertEquals(value, Files.readString(path)); + } + } + + @Test + public void rejectsInvalidInitialIdsWithoutSavingThem() { + for (long value : new long[] {0L, -1L}) { + assertThrows(IllegalArgumentException.class, + () -> ManagementServerId.load(idFile(), null, () -> value)); + } + assertFalse(Files.exists(idFile())); + } + + @Test + public void failsWhenIdentityCannotBeSaved() throws IOException { + Path path = folder.newFile("not-a-directory").toPath().resolve("id"); + assertThrows(IOException.class, () -> ManagementServerId.load(path, null, unexpectedLookup())); + } + + @Test + public void readsWhitespaceAndFullLongIds() throws IOException { + Path path = folder.newFile("id").toPath(); + Files.writeString(path, " " + Long.MAX_VALUE + "\n", StandardCharsets.UTF_8); + assertEquals(Long.MAX_VALUE, ManagementServerId.load(path, null, unexpectedLookup())); + } + + @Test + public void usesJvmSettingsAndReportsInvalidStorage() throws IOException { + String previousFile = System.getProperty("management.server.id.file"); + String previousId = System.getProperty("management.server.id"); + Path path = folder.newFile("id").toPath(); + try { + System.setProperty("management.server.id.file", path.toString()); + System.clearProperty("management.server.id"); + Files.writeString(path, "42\n", StandardCharsets.UTF_8); + assertEquals(42L, ManagementServerId.get()); + + System.setProperty("management.server.id", "123"); + assertEquals(123L, ManagementServerId.get()); + + System.clearProperty("management.server.id"); + Files.writeString(path, "invalid", StandardCharsets.UTF_8); + assertThrows(CloudRuntimeException.class, ManagementServerId::get); + } finally { + restoreProperty("management.server.id.file", previousFile); + restoreProperty("management.server.id", previousId); + } + } + + @Test + public void concurrentProcessesUseTheSameId() throws Exception { + Path path = idFile(); + List processes = new ArrayList<>(); + try { + for (int i = 1; i <= 3; i++) { + processes.add(new ProcessBuilder(Paths.get(System.getProperty("java.home"), "bin", "java").toString(), + "-cp", System.getProperty("java.class.path"), IdWriter.class.getName(), path.toString(), Integer.toString(i)) + .redirectErrorStream(true).start()); + } + for (Process process : processes) { + assertTrue("ID writer timed out", process.waitFor(30, TimeUnit.SECONDS)); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim(); + assertEquals(output, 0, process.exitValue()); + assertEquals(Files.readString(path).trim(), output); + } + } finally { + for (Process process : processes) { + process.destroyForcibly(); + } + } + } + + public static class IdWriter { + public static void main(String[] args) throws IOException { + System.out.println(ManagementServerId.load(Paths.get(args[0]), null, () -> Long.parseLong(args[1]))); + } + } + + private void restoreProperty(String name, String value) { + if (value == null) { + System.clearProperty(name); + } else { + System.setProperty(name, value); + } + } +} From 4a7fa729ef7fbf5abddcc4703fb9aa53ffe15e9d Mon Sep 17 00:00:00 2001 From: Mashrfee Aryan Date: Mon, 19 Oct 2026 10:26:39 -0500 Subject: [PATCH 02/12] Document management server ID storage and recovery Explain the ID file, JVM settings, and upgrade steps for issue #14253. --- INSTALL.md | 27 +++++++++++++++++++++++++++ PendingReleaseNotes | 6 ++++++ 2 files changed, 33 insertions(+) diff --git a/INSTALL.md b/INSTALL.md index 0619b97f21c1..49a1aaf158dd 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -188,6 +188,33 @@ Then: To create packages for noredist add the `-p noredist` option to the package script. All the rpm packages will be created in `dist/rpmbuild/RPMS/x86_64` directory. +## Management server identity + +The management server saves its numeric ID in +`${user.home}/.cloudstack/management-server.id`. Packaged installations run as +`cloud`, whose home is normally `/var/lib/cloudstack/management`. On first use, +the server saves the ID derived from its MAC address. Later starts reuse the +saved ID, even if network interface order changes. + +Keep this file when upgrading or restoring the same management server. Do not +copy it to a different management server. The service user needs read and write +access to the directory, including the adjacent `.lock` file. If the ID cannot +be read, validated, or saved, startup fails. + +These JVM options can be added to `JAVA_OPTS` in +`/etc/default/cloudstack-management`: + +* `-Dmanagement.server.id.file=/path/to/management-server.id` changes the file + location. Use a persistent local directory writable by the service user. +* `-Dmanagement.server.id=123456789` overrides the saved ID with a positive + decimal integer. Each management server must have its own ID. This option does + not change the saved file; removing it restores the saved ID. + +For an existing installation, if interface order has already changed before the +first start with this fix, set `management.server.id` to that server's original +`msid` from `cloud.mshost`. Keep the override on subsequent starts. Existing stale +rows in `cloud.mshost` are not removed by this change. + ## Notes If you will be using Xen as your hypervisor, please download [vhd-util](https://download.cloudstack.org/tools/vhd-util) diff --git a/PendingReleaseNotes b/PendingReleaseNotes index 02d63811e36e..ad914a97124b 100644 --- a/PendingReleaseNotes +++ b/PendingReleaseNotes @@ -40,6 +40,12 @@ example.ver.1 > example.ver.2: Storage to grow to enormous sizes as Linux Distributions keep growing in size while a stripped down Linux should fit on a 2.88MB floppy. +4.22.1.0 > 4.22.2.0: + * Management servers now save their ID locally and reuse it after restarts, + preventing network interface reordering from changing the ID. Keep the ID + file when upgrading or restoring a server. See INSTALL.md for the file + location and JVM options to override the ID or its storage location. + 4.22.0.0 > 4.22.0.1: * Disk-only instance snapshots for KVM UEFI VMs now include a sidecar copy of the active NVRAM state so revert operations restore both disk and firmware From b92ff81ce65129b50a00307d2b6275afbc9b9026 Mon Sep 17 00:00:00 2001 From: Mashrfee Aryan Date: Sat, 31 Oct 2026 22:27:48 -0500 Subject: [PATCH 03/12] Fix interrupted management server ID initialization Flush the initial identity to a temporary sibling file and atomically publish it while holding the existing process lock. Clean up failed writes and verify that initialization can be retried without an invalid identity file. Related to #14253. --- .../utils/identity/ManagementServerId.java | 17 ++++++--- .../identity/ManagementServerIdTest.java | 36 +++++++++++++++++++ 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java index dcebb5d9ad13..fb4f40d252e0 100644 --- a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java @@ -25,6 +25,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.util.function.LongSupplier; @@ -63,12 +64,18 @@ static long load(Path path, String configuredId, LongSupplier initialId) throws } long id = parse(Long.toString(initialId.getAsLong())); - try (FileChannel channel = FileChannel.open(path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) { - ByteBuffer buffer = StandardCharsets.UTF_8.encode(id + "\n"); - while (buffer.hasRemaining()) { - channel.write(buffer); + Path temporary = Files.createTempFile(path.toAbsolutePath().getParent(), "management-server-id-", ".tmp"); + try { + try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) { + ByteBuffer buffer = StandardCharsets.UTF_8.encode(id + "\n"); + while (buffer.hasRemaining()) { + channel.write(buffer); + } + channel.force(true); } - channel.force(true); + Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE); + } finally { + Files.deleteIfExists(temporary); } return id; } diff --git a/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java index 030161895206..a385c085cb2a 100644 --- a/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java +++ b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java @@ -23,6 +23,8 @@ import static org.junit.Assert.assertTrue; import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -30,11 +32,15 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.LongSupplier; +import java.util.stream.Stream; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.mockito.MockedStatic; +import org.mockito.Mockito; import com.cloud.utils.exception.CloudRuntimeException; @@ -110,6 +116,36 @@ public void failsWhenIdentityCannotBeSaved() throws IOException { assertThrows(IOException.class, () -> ManagementServerId.load(path, null, unexpectedLookup())); } + @Test + public void failedInitialWriteDoesNotPublishAnInvalidIdentity() throws IOException { + Path path = idFile(); + AtomicReference underlyingWriter = new AtomicReference<>(); + FileChannel failedWriter = Mockito.mock(FileChannel.class); + Mockito.when(failedWriter.write(Mockito.any(ByteBuffer.class))).thenThrow(new IOException("Interrupted write")); + Mockito.doAnswer(invocation -> { + underlyingWriter.get().close(); + return null; + }).when(failedWriter).close(); + + try (MockedStatic channels = Mockito.mockStatic(FileChannel.class, invocation -> { + FileChannel channel = (FileChannel) invocation.callRealMethod(); + Path openedPath = invocation.getArgument(0); + if (openedPath.getFileName().toString().endsWith(".lock")) { + return channel; + } + underlyingWriter.compareAndSet(null, channel); + return failedWriter; + })) { + assertThrows(IOException.class, () -> ManagementServerId.load(path, null, () -> 42L)); + } + + assertFalse(Files.exists(path)); + try (Stream files = Files.list(path.getParent())) { + assertEquals(1L, files.count()); // Only the interprocess lock remains. + } + assertEquals(43L, ManagementServerId.load(path, null, () -> 43L)); + } + @Test public void readsWhitespaceAndFullLongIds() throws IOException { Path path = folder.newFile("id").toPath(); From 81987abfa78263f6e5b759250fbea822ce699102 Mon Sep 17 00:00:00 2001 From: Mashrfee Aryan Date: Sat, 31 Oct 2026 22:27:49 -0500 Subject: [PATCH 04/12] Use the persistent management server ID consistently Route the remaining management identity consumers through ManagementServerNode instead of reading the current MAC address. Cover the management service ID and disk statistics ownership when the saved identity differs from the MAC. Related to #14253. --- .../CloudZonesStartupProcessor.java | 7 +- .../network/NetworkUsageManagerImpl.java | 5 +- .../VirtualNetworkApplianceManagerImpl.java | 3 +- .../cloud/server/ManagementServerImpl.java | 3 +- .../java/com/cloud/server/StatsCollector.java | 3 +- .../server/ManagementServerIdentityTest.java | 83 +++++++++++++++++++ 6 files changed, 92 insertions(+), 12 deletions(-) create mode 100644 server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java diff --git a/server/src/main/java/com/cloud/hypervisor/CloudZonesStartupProcessor.java b/server/src/main/java/com/cloud/hypervisor/CloudZonesStartupProcessor.java index f2704f35fcdd..83000f1967d2 100644 --- a/server/src/main/java/com/cloud/hypervisor/CloudZonesStartupProcessor.java +++ b/server/src/main/java/com/cloud/hypervisor/CloudZonesStartupProcessor.java @@ -22,6 +22,8 @@ import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.utils.identity.ManagementServerNode; + import org.springframework.stereotype.Component; import com.cloud.agent.AgentManager; @@ -38,7 +40,6 @@ import com.cloud.host.HostVO; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.net.MacAddress; import com.cloud.utils.net.NetUtils; /** @@ -60,9 +61,7 @@ public class CloudZonesStartupProcessor extends AdapterBase implements StartupCo public boolean configure(String name, Map params) throws ConfigurationException { _agentManager.registerForInitialConnects(this, false); if (_nodeId == -1) { - // FIXME: We really should not do this like this. It should be done - // at config time and is stored as a config variable. - _nodeId = MacAddress.getMacAddress().toLong(); + _nodeId = ManagementServerNode.getManagementServerId(); } return true; } diff --git a/server/src/main/java/com/cloud/network/NetworkUsageManagerImpl.java b/server/src/main/java/com/cloud/network/NetworkUsageManagerImpl.java index 0aee5f234969..37bc183058cd 100644 --- a/server/src/main/java/com/cloud/network/NetworkUsageManagerImpl.java +++ b/server/src/main/java/com/cloud/network/NetworkUsageManagerImpl.java @@ -28,6 +28,8 @@ import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.utils.identity.ManagementServerNode; + import org.springframework.stereotype.Component; import org.apache.cloudstack.api.command.admin.usage.AddTrafficMonitorCmd; @@ -88,7 +90,6 @@ import com.cloud.utils.db.TransactionCallbackNoReturn; import com.cloud.utils.db.TransactionStatus; import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.MacAddress; @Component public class NetworkUsageManagerImpl extends ManagerBase implements NetworkUsageService, NetworkUsageManager, ResourceStateAdapter { @@ -251,7 +252,7 @@ protected class DirectNetworkStatsListener implements Listener { private int _interval; - private final long mgmtSrvrId = MacAddress.getMacAddress().toLong(); + private final long mgmtSrvrId = ManagementServerNode.getManagementServerId(); protected DirectNetworkStatsListener(int interval) { _interval = interval; diff --git a/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index e2415e200768..3d3249f212f3 100644 --- a/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -250,7 +250,6 @@ import com.cloud.utils.fsm.StateListener; import com.cloud.utils.fsm.StateMachine2; import com.cloud.utils.net.Ip; -import com.cloud.utils.net.MacAddress; import com.cloud.utils.net.NetUtils; import com.cloud.vm.DomainRouterVO; import com.cloud.vm.Nic; @@ -365,7 +364,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V private int _routerExtraPublicNics = 2; private int _usageAggregationRange = 1440; private String _usageTimeZone = "GMT"; - private final long mgmtSrvrId = MacAddress.getMacAddress().toLong(); + private final long mgmtSrvrId = ManagementServerNode.getManagementServerId(); private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5; // 5 seconds private boolean _dailyOrHourly = false; diff --git a/server/src/main/java/com/cloud/server/ManagementServerImpl.java b/server/src/main/java/com/cloud/server/ManagementServerImpl.java index 95e688b5d8cb..7d16e8fbf71b 100644 --- a/server/src/main/java/com/cloud/server/ManagementServerImpl.java +++ b/server/src/main/java/com/cloud/server/ManagementServerImpl.java @@ -847,7 +847,6 @@ import com.cloud.utils.db.TransactionStatus; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.StateMachine2; -import com.cloud.utils.net.MacAddress; import com.cloud.utils.net.NetUtils; import com.cloud.utils.security.CertificateHelper; import com.cloud.utils.ssh.SSHKeysHelper; @@ -1200,7 +1199,7 @@ public DetailVO findDetail(final long hostId, final String name) { @Override public long getId() { - return MacAddress.getMacAddress().toLong(); + return ManagementServerNode.getManagementServerId(); } protected void checkPortParameters(final String publicPort, final String privatePort, final String privateIp, final String proto) { diff --git a/server/src/main/java/com/cloud/server/StatsCollector.java b/server/src/main/java/com/cloud/server/StatsCollector.java index 3eec27d4f54d..b224a7f1a2fb 100644 --- a/server/src/main/java/com/cloud/server/StatsCollector.java +++ b/server/src/main/java/com/cloud/server/StatsCollector.java @@ -150,7 +150,6 @@ import com.cloud.utils.db.TransactionCallbackNoReturn; import com.cloud.utils.db.TransactionStatus; import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.MacAddress; import com.cloud.utils.script.Script; import com.cloud.vm.NicVO; import com.cloud.vm.UserVmManager; @@ -391,7 +390,7 @@ public String toString() { private ScheduledExecutorService _diskStatsUpdateExecutor; private int _usageAggregationRange = 1440; private String _usageTimeZone = "GMT"; - private final long mgmtSrvrId = MacAddress.getMacAddress().toLong(); + private final long mgmtSrvrId = ManagementServerNode.getManagementServerId(); private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5; // 5 seconds private boolean _dailyOrHourly = false; protected long managementServerNodeId = ManagementServerNode.getManagementServerId(); diff --git a/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java b/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java new file mode 100644 index 000000000000..7b62ed97cbb4 --- /dev/null +++ b/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java @@ -0,0 +1,83 @@ +// 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 com.cloud.server; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.junit.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; + +import com.cloud.cluster.ManagementServerHostVO; +import com.cloud.cluster.dao.ManagementServerHostDao; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallbackNoReturn; +import com.cloud.utils.net.MacAddress; + +public class ManagementServerIdentityTest { + private static final long SAVED_ID = 123L; + private static final long CHANGED_MAC_ID = 456L; + + @Test + public void managementServiceReportsSavedIdAfterMacChanges() { + try (MockedStatic node = mockStatic(ManagementServerNode.class); + MockedStatic mac = mockStatic(MacAddress.class)) { + node.when(ManagementServerNode::getManagementServerId).thenReturn(SAVED_ID); + mac.when(MacAddress::getMacAddress).thenReturn(new MacAddress(CHANGED_MAC_ID)); + + ManagementServerImpl server = mock(ManagementServerImpl.class, Mockito.CALLS_REAL_METHODS); + assertEquals(SAVED_ID, server.getId()); + } + } + + @Test + public void owningServerStillUpdatesDiskStatsAfterMacChanges() { + StatsCollector previous = StatsCollector.getInstance(); + try (MockedStatic node = mockStatic(ManagementServerNode.class); + MockedStatic mac = mockStatic(MacAddress.class); + MockedStatic locks = mockStatic(GlobalLock.class); + MockedStatic transactions = mockStatic(Transaction.class)) { + node.when(ManagementServerNode::getManagementServerId).thenReturn(SAVED_ID); + mac.when(MacAddress::getMacAddress).thenReturn(new MacAddress(CHANGED_MAC_ID)); + GlobalLock lock = mock(GlobalLock.class); + locks.when(() -> GlobalLock.getInternLock("vm.disk.stats")).thenReturn(lock); + when(lock.lock(5)).thenReturn(true); + + ManagementServerHostVO host = new ManagementServerHostVO(); + host.setMsid(SAVED_ID); + ManagementServerHostDao dao = mock(ManagementServerHostDao.class); + when(dao.findOneInUpState(any(Filter.class))).thenReturn(host); + StatsCollector collector = new StatsCollector(); + ReflectionTestUtils.setField(collector, "managementServerHostDao", dao); + + collector.new VmDiskStatsUpdaterTask().runInContext(); + + transactions.verify(() -> Transaction.execute(any(TransactionCallbackNoReturn.class))); + } finally { + ReflectionTestUtils.setField(StatsCollector.class, "s_instance", previous); + } + } +} From 79800388b3344dfdb993843a5d5343fb8e05bf2d Mon Sep 17 00:00:00 2001 From: Mashrfee Aryan Date: Sat, 31 Oct 2026 22:27:50 -0500 Subject: [PATCH 05/12] Keep active management IPs out of agent avoid lists Build the avoid list from one snapshot of nonremoved management server records. An Up record takes precedence over stale non-Up identities sharing its IP; unavailable addresses remain avoided without duplicates. Retain database records and document the recovery behavior. Related to #14253. --- INSTALL.md | 3 +- .../dao/ManagementServerHostDaoImpl.java | 26 ++++--- .../dao/ManagementServerHostDaoImplTest.java | 71 +++++++++++++++++++ 3 files changed, 89 insertions(+), 11 deletions(-) create mode 100644 framework/cluster/src/test/java/com/cloud/cluster/dao/ManagementServerHostDaoImplTest.java diff --git a/INSTALL.md b/INSTALL.md index 49a1aaf158dd..da9d5de52357 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -213,7 +213,8 @@ These JVM options can be added to `JAVA_OPTS` in For an existing installation, if interface order has already changed before the first start with this fix, set `management.server.id` to that server's original `msid` from `cloud.mshost`. Keep the override on subsequent starts. Existing stale -rows in `cloud.mshost` are not removed by this change. +rows in `cloud.mshost` are retained, but an old non-Up row no longer causes agents +to avoid an IP address that also has an Up management server. ## Notes diff --git a/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java b/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java index ec943a9c26be..5bfc45efabfb 100644 --- a/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java +++ b/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java @@ -21,7 +21,10 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; +import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; import java.util.TimeZone; @@ -35,7 +38,6 @@ import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.TransactionLegacy; @@ -47,7 +49,6 @@ public class ManagementServerHostDaoImpl extends GenericDaoBase ActiveSearch; private final SearchBuilder InactiveSearch; private final SearchBuilder StateSearch; - protected GenericSearchBuilder NonUpStateMsSearch; @Override public void invalidateRunSession(long id, long runid) { @@ -229,11 +230,6 @@ protected ManagementServerHostDaoImpl() { StateSearch.and("state", StateSearch.entity().getState(), SearchCriteria.Op.IN); StateSearch.and("runid", StateSearch.entity().getRunid(), SearchCriteria.Op.GT); StateSearch.done(); - - NonUpStateMsSearch = createSearchBuilder(String.class); - NonUpStateMsSearch.selectFields(NonUpStateMsSearch.entity().getServiceIP()); - NonUpStateMsSearch.and("state", NonUpStateMsSearch.entity().getState(), SearchCriteria.Op.NLIKE); - NonUpStateMsSearch.done(); } @Override @@ -269,9 +265,19 @@ public List listBy(ManagementServerHost.State... states) @Override public List listNonUpStateMsIPs() { - SearchCriteria sc = NonUpStateMsSearch.create(); - sc.addAnd("state", SearchCriteria.Op.NLIKE, State.Up); - return customSearch(sc, null); + Set upIPs = new HashSet<>(); + Set nonUpIPs = new LinkedHashSet<>(); + // Read one snapshot, excluding removed records. An old identity must not + // make agents avoid an address that still has an Up management server. + for (ManagementServerHostVO host : listAll()) { + if (State.Up.equals(host.getState())) { + upIPs.add(host.getServiceIP()); + } else { + nonUpIPs.add(host.getServiceIP()); + } + } + nonUpIPs.removeAll(upIPs); + return new ArrayList<>(nonUpIPs); } @Override diff --git a/framework/cluster/src/test/java/com/cloud/cluster/dao/ManagementServerHostDaoImplTest.java b/framework/cluster/src/test/java/com/cloud/cluster/dao/ManagementServerHostDaoImplTest.java new file mode 100644 index 000000000000..43a17b634495 --- /dev/null +++ b/framework/cluster/src/test/java/com/cloud/cluster/dao/ManagementServerHostDaoImplTest.java @@ -0,0 +1,71 @@ +// 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 com.cloud.cluster.dao; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.apache.cloudstack.management.ManagementServerHost.State; +import org.junit.Test; + +import com.cloud.cluster.ManagementServerHostVO; + +public class ManagementServerHostDaoImplTest { + private final ManagementServerHostDaoImpl dao = spy(new ManagementServerHostDaoImpl()); + + @Test + public void staleDownIdentityDoesNotBlockAnUpServerAtTheSameIp() { + ManagementServerHostVO down = host("10.0.0.1", State.Down); + ManagementServerHostVO up = host("10.0.0.1", State.Up); + assertAvoided(Arrays.asList(down, up)); + assertAvoided(Arrays.asList(up, down)); + } + + @Test + public void unavailableAddressesRemainAvoidedWithoutDuplicates() { + assertAvoided(Arrays.asList(host("10.0.0.1", State.Down), host("10.0.0.1", State.Down), + host("10.0.0.2", State.Maintenance), host("10.0.0.3", State.Up)), "10.0.0.1", "10.0.0.2"); + } + + @Test + public void upServerTakesPrecedenceOverAnOldMaintenanceRecord() { + assertAvoided(Arrays.asList(host("10.0.0.1", State.Maintenance), host("10.0.0.1", State.Up))); + } + + @Test + public void emptyServerListHasNoAvoidedAddresses() { + assertAvoided(Collections.emptyList()); + } + + private void assertAvoided(List hosts, String... expected) { + doReturn(hosts).when(dao).listAll(); + assertEquals(Arrays.asList(expected), dao.listNonUpStateMsIPs()); + } + + private ManagementServerHostVO host(String ip, State state) { + ManagementServerHostVO host = new ManagementServerHostVO(); + host.setServiceIP(ip); + host.setState(state); + return host; + } +} From c22a289db2dfe9847d286515696bdf085a7a2f6c Mon Sep 17 00:00:00 2001 From: Mashrfee Aryan Date: Sun, 1 Nov 2026 12:52:39 -0600 Subject: [PATCH 06/12] Clarify management server identity comments and documentation Explain the persistent ID flow, identity consumers, and regression tests with short comments without ending periods. Keep installation instructions concise and document preserving the ID file, configuration overrides, and recovery for existing installations. Update release notes for stable IDs and active IP handling. Restore CloudZonesStartupProcessor to its pre-fix version because its local node ID is unused. Keep its existing configure() behavior and exclude the file from the overall PR diff. --- INSTALL.md | 42 ++++++++----------- PendingReleaseNotes | 9 ++-- .../dao/ManagementServerHostDaoImpl.java | 10 ++++- .../dao/ManagementServerHostDaoImplTest.java | 7 ++++ .../CloudZonesStartupProcessor.java | 7 ++-- .../network/NetworkUsageManagerImpl.java | 1 + .../VirtualNetworkApplianceManagerImpl.java | 1 + .../cloud/server/ManagementServerImpl.java | 1 + .../java/com/cloud/server/StatsCollector.java | 1 + .../server/ManagementServerIdentityTest.java | 6 +++ .../utils/identity/ManagementServerId.java | 17 ++++++++ .../utils/identity/ManagementServerNode.java | 6 +++ .../identity/ManagementServerIdTest.java | 19 ++++++++- 13 files changed, 92 insertions(+), 35 deletions(-) diff --git a/INSTALL.md b/INSTALL.md index da9d5de52357..76e2a389eee8 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -190,31 +190,23 @@ All the rpm packages will be created in `dist/rpmbuild/RPMS/x86_64` directory. ## Management server identity -The management server saves its numeric ID in -`${user.home}/.cloudstack/management-server.id`. Packaged installations run as -`cloud`, whose home is normally `/var/lib/cloudstack/management`. On first use, -the server saves the ID derived from its MAC address. Later starts reuse the -saved ID, even if network interface order changes. - -Keep this file when upgrading or restoring the same management server. Do not -copy it to a different management server. The service user needs read and write -access to the directory, including the adjacent `.lock` file. If the ID cannot -be read, validated, or saved, startup fails. - -These JVM options can be added to `JAVA_OPTS` in -`/etc/default/cloudstack-management`: - -* `-Dmanagement.server.id.file=/path/to/management-server.id` changes the file - location. Use a persistent local directory writable by the service user. -* `-Dmanagement.server.id=123456789` overrides the saved ID with a positive - decimal integer. Each management server must have its own ID. This option does - not change the saved file; removing it restores the saved ID. - -For an existing installation, if interface order has already changed before the -first start with this fix, set `management.server.id` to that server's original -`msid` from `cloud.mshost`. Keep the override on subsequent starts. Existing stale -rows in `cloud.mshost` are retained, but an old non-Up row no longer causes agents -to avoid an IP address that also has an Up management server. +The server saves its ID in `${user.home}/.cloudstack/management-server.id` +and reuses it after restarts. Keep this file when upgrading or restoring the +same server. Do not copy it to a different management server. + +The service account needs write access to the directory and its `.lock` file. +Startup fails if the ID cannot be read, validated, or saved. + +These options can be added to `JAVA_OPTS` in `/etc/default/cloudstack-management`: + +* `-Dmanagement.server.id.file=/path/to/management-server.id` chooses a different + persistent local file location. +* `-Dmanagement.server.id=123456789` overrides the ID with a positive number + unique to this server. It does not change the saved file. + +If interface order already changed before upgrading, set `management.server.id` +to this server's original `msid` from `cloud.mshost` before the first start. +Keep that override configured on later starts. ## Notes diff --git a/PendingReleaseNotes b/PendingReleaseNotes index ad914a97124b..3a0ee3a836c4 100644 --- a/PendingReleaseNotes +++ b/PendingReleaseNotes @@ -41,10 +41,11 @@ example.ver.1 > example.ver.2: size while a stripped down Linux should fit on a 2.88MB floppy. 4.22.1.0 > 4.22.2.0: - * Management servers now save their ID locally and reuse it after restarts, - preventing network interface reordering from changing the ID. Keep the ID - file when upgrading or restoring a server. See INSTALL.md for the file - location and JVM options to override the ID or its storage location. + * Management servers now reuse a saved ID after restarts, so network interface + reordering does not change their identity. Keep the ID file during upgrades + and restores. See INSTALL.md for the file location and ID settings. + * Old non-Up management server records no longer cause agents to avoid an IP + that also has an Up record. 4.22.0.0 > 4.22.0.1: * Disk-only instance snapshots for KVM UEFI VMs now include a sidecar copy of diff --git a/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java b/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java index 5bfc45efabfb..99610747ab97 100644 --- a/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java +++ b/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java @@ -263,20 +263,26 @@ public List listBy(ManagementServerHost.State... states) return listBy(sc); } + // The saved ID stops future ID changes but leaves old records behind + // This method handles duplicate records that already exist + // Old Down records must not make agents skip an address that also has an Up record @Override public List listNonUpStateMsIPs() { Set upIPs = new HashSet<>(); Set nonUpIPs = new LinkedHashSet<>(); - // Read one snapshot, excluding removed records. An old identity must not - // make agents avoid an address that still has an Up management server. + // Read server records that have not been removed for (ManagementServerHostVO host : listAll()) { if (State.Up.equals(host.getState())) { + // Collect addresses marked Up upIPs.add(host.getServiceIP()); } else { + // Collect addresses in other states nonUpIPs.add(host.getServiceIP()); } } + // Keep every Up address out of the avoid list nonUpIPs.removeAll(upIPs); + // Give agents the remaining addresses to skip return new ArrayList<>(nonUpIPs); } diff --git a/framework/cluster/src/test/java/com/cloud/cluster/dao/ManagementServerHostDaoImplTest.java b/framework/cluster/src/test/java/com/cloud/cluster/dao/ManagementServerHostDaoImplTest.java index 43a17b634495..7a2ea02877e1 100644 --- a/framework/cluster/src/test/java/com/cloud/cluster/dao/ManagementServerHostDaoImplTest.java +++ b/framework/cluster/src/test/java/com/cloud/cluster/dao/ManagementServerHostDaoImplTest.java @@ -30,9 +30,11 @@ import com.cloud.cluster.ManagementServerHostVO; +// Checks that old server records do not make agents skip an available address public class ManagementServerHostDaoImplTest { private final ManagementServerHostDaoImpl dao = spy(new ManagementServerHostDaoImpl()); + // Do not avoid an address if one record says Up and an old record says Down @Test public void staleDownIdentityDoesNotBlockAnUpServerAtTheSameIp() { ManagementServerHostVO down = host("10.0.0.1", State.Down); @@ -41,27 +43,32 @@ public void staleDownIdentityDoesNotBlockAnUpServerAtTheSameIp() { assertAvoided(Arrays.asList(up, down)); } + // Keep unavailable addresses in the avoid list and include each address only once @Test public void unavailableAddressesRemainAvoidedWithoutDuplicates() { assertAvoided(Arrays.asList(host("10.0.0.1", State.Down), host("10.0.0.1", State.Down), host("10.0.0.2", State.Maintenance), host("10.0.0.3", State.Up)), "10.0.0.1", "10.0.0.2"); } + // Allow an address marked Up even if an old record says it is in maintenance @Test public void upServerTakesPrecedenceOverAnOldMaintenanceRecord() { assertAvoided(Arrays.asList(host("10.0.0.1", State.Maintenance), host("10.0.0.1", State.Up))); } + // No server records means there are no addresses to avoid @Test public void emptyServerListHasNoAvoidedAddresses() { assertAvoided(Collections.emptyList()); } + // Run the avoid-list code with pretend records and check the returned addresses private void assertAvoided(List hosts, String... expected) { doReturn(hosts).when(dao).listAll(); assertEquals(Arrays.asList(expected), dao.listNonUpStateMsIPs()); } + // Make a pretend server record with an address and a state private ManagementServerHostVO host(String ip, State state) { ManagementServerHostVO host = new ManagementServerHostVO(); host.setServiceIP(ip); diff --git a/server/src/main/java/com/cloud/hypervisor/CloudZonesStartupProcessor.java b/server/src/main/java/com/cloud/hypervisor/CloudZonesStartupProcessor.java index 83000f1967d2..f2704f35fcdd 100644 --- a/server/src/main/java/com/cloud/hypervisor/CloudZonesStartupProcessor.java +++ b/server/src/main/java/com/cloud/hypervisor/CloudZonesStartupProcessor.java @@ -22,8 +22,6 @@ import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.cloudstack.utils.identity.ManagementServerNode; - import org.springframework.stereotype.Component; import com.cloud.agent.AgentManager; @@ -40,6 +38,7 @@ import com.cloud.host.HostVO; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.net.MacAddress; import com.cloud.utils.net.NetUtils; /** @@ -61,7 +60,9 @@ public class CloudZonesStartupProcessor extends AdapterBase implements StartupCo public boolean configure(String name, Map params) throws ConfigurationException { _agentManager.registerForInitialConnects(this, false); if (_nodeId == -1) { - _nodeId = ManagementServerNode.getManagementServerId(); + // FIXME: We really should not do this like this. It should be done + // at config time and is stored as a config variable. + _nodeId = MacAddress.getMacAddress().toLong(); } return true; } diff --git a/server/src/main/java/com/cloud/network/NetworkUsageManagerImpl.java b/server/src/main/java/com/cloud/network/NetworkUsageManagerImpl.java index 37bc183058cd..fa669acac024 100644 --- a/server/src/main/java/com/cloud/network/NetworkUsageManagerImpl.java +++ b/server/src/main/java/com/cloud/network/NetworkUsageManagerImpl.java @@ -252,6 +252,7 @@ protected class DirectNetworkStatsListener implements Listener { private int _interval; + // Use the saved ID to check which traffic monitors this server is in charge of private final long mgmtSrvrId = ManagementServerNode.getManagementServerId(); protected DirectNetworkStatsListener(int interval) { diff --git a/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 3d3249f212f3..b057d53f01b0 100644 --- a/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -364,6 +364,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V private int _routerExtraPublicNics = 2; private int _usageAggregationRange = 1440; private String _usageTimeZone = "GMT"; + // Use the saved ID to find the routers this server is in charge of private final long mgmtSrvrId = ManagementServerNode.getManagementServerId(); private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5; // 5 seconds private boolean _dailyOrHourly = false; diff --git a/server/src/main/java/com/cloud/server/ManagementServerImpl.java b/server/src/main/java/com/cloud/server/ManagementServerImpl.java index 7d16e8fbf71b..a417ff84a3a3 100644 --- a/server/src/main/java/com/cloud/server/ManagementServerImpl.java +++ b/server/src/main/java/com/cloud/server/ManagementServerImpl.java @@ -1197,6 +1197,7 @@ public DetailVO findDetail(final long hostId, final String name) { return _detailsDao.findDetail(hostId, name); } + // Return the persistent server ID shared by the other CloudStack components @Override public long getId() { return ManagementServerNode.getManagementServerId(); diff --git a/server/src/main/java/com/cloud/server/StatsCollector.java b/server/src/main/java/com/cloud/server/StatsCollector.java index b224a7f1a2fb..ee606fb838f8 100644 --- a/server/src/main/java/com/cloud/server/StatsCollector.java +++ b/server/src/main/java/com/cloud/server/StatsCollector.java @@ -390,6 +390,7 @@ public String toString() { private ScheduledExecutorService _diskStatsUpdateExecutor; private int _usageAggregationRange = 1440; private String _usageTimeZone = "GMT"; + // Use the saved ID to check which stats jobs this server should do private final long mgmtSrvrId = ManagementServerNode.getManagementServerId(); private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5; // 5 seconds private boolean _dailyOrHourly = false; diff --git a/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java b/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java index 7b62ed97cbb4..00c3d9373ebb 100644 --- a/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java +++ b/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java @@ -37,10 +37,13 @@ import com.cloud.utils.db.TransactionCallbackNoReturn; import com.cloud.utils.net.MacAddress; +// Check that the server and its stats jobs use the saved ID public class ManagementServerIdentityTest { + // Use different values for the saved ID and the ID from the network card private static final long SAVED_ID = 123L; private static final long CHANGED_MAC_ID = 456L; + // Return the saved ID even when the network card gives a different ID @Test public void managementServiceReportsSavedIdAfterMacChanges() { try (MockedStatic node = mockStatic(ManagementServerNode.class); @@ -53,6 +56,7 @@ public void managementServiceReportsSavedIdAfterMacChanges() { } } + // Still start the disk stats job when the saved ID says this server is in charge @Test public void owningServerStillUpdatesDiskStatsAfterMacChanges() { StatsCollector previous = StatsCollector.getInstance(); @@ -66,6 +70,7 @@ public void owningServerStillUpdatesDiskStatsAfterMacChanges() { locks.when(() -> GlobalLock.getInternLock("vm.disk.stats")).thenReturn(lock); when(lock.lock(5)).thenReturn(true); + // Pretend the database says this server should do the job ManagementServerHostVO host = new ManagementServerHostVO(); host.setMsid(SAVED_ID); ManagementServerHostDao dao = mock(ManagementServerHostDao.class); @@ -77,6 +82,7 @@ public void owningServerStillUpdatesDiskStatsAfterMacChanges() { transactions.verify(() -> Transaction.execute(any(TransactionCallbackNoReturn.class))); } finally { + // Put the old stats collector back so other tests are not affected ReflectionTestUtils.setField(StatsCollector.class, "s_instance", previous); } } diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java index fb4f40d252e0..edeb78e2f431 100644 --- a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java @@ -32,38 +32,51 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.MacAddress; +// Keeps the management server ID the same across restarts final class ManagementServerId { private ManagementServerId() { } + // Find the ID file and load the ID static long get() { Path path = Paths.get(System.getProperty("management.server.id.file", Paths.get(System.getProperty("user.home"), ".cloudstack", "management-server.id").toString())); try { + // Use the ID from management.server.id if it is set + // Otherwise, read the saved ID from the file at path + // If the file does not exist, create an ID from the MAC address and save it return load(path, System.getProperty("management.server.id"), () -> MacAddress.getMacAddress().toLong()); } catch (IOException | IllegalArgumentException e) { + // Stop with a clear error instead of silently choosing a different identity throw new CloudRuntimeException("Unable to load the management server ID from " + path, e); } } static long load(Path path, String configuredId, LongSupplier initialId) throws IOException { + // An operator-provided ID takes priority without overwriting the saved file if (configuredId != null) { return parse(configuredId); } + // Ensure the directory exists, then lock the neighboring .lock file so + // two processes cannot initialize the same identity file at the same time Files.createDirectories(path.toAbsolutePath().getParent()); try (FileChannel lockChannel = FileChannel.open(path.resolveSibling(path.getFileName() + ".lock"), StandardOpenOption.CREATE, StandardOpenOption.WRITE); FileLock lock = lockChannel.lock()) { + // Reuse the saved ID without checking network interfaces again if (Files.exists(path)) { + // An ID is a short number; reject an unexpectedly large file if (Files.size(path) > 64) { throw new IllegalArgumentException("Invalid management server ID file"); } return parse(new String(Files.readAllBytes(path), StandardCharsets.UTF_8)); } + // First startup: obtain the initial MAC-derived ID and validate it long id = parse(Long.toString(initialId.getAsLong())); + // Write in the same directory so the completed file can be renamed atomically Path temporary = Files.createTempFile(path.toAbsolutePath().getParent(), "management-server-id-", ".tmp"); try { try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) { @@ -71,16 +84,20 @@ static long load(Path path, String configuredId, LongSupplier initialId) throws while (buffer.hasRemaining()) { channel.write(buffer); } + // Flush the complete ID to storage before publishing it channel.force(true); } + // Make the completed file appear under its final name in one operation Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE); } finally { + // Clean up after a failed save; a successful move already removed this name Files.deleteIfExists(temporary); } return id; } } + // Ignore surrounding whitespace and require a positive whole number that fits in a Java long private static long parse(String value) { long id = Long.parseLong(value.trim()); if (id <= 0) { diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java index cc85ca18c02b..e9df0f991573 100644 --- a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java @@ -26,14 +26,18 @@ import com.cloud.utils.component.SystemIntegrityChecker; import com.cloud.utils.exception.CloudRuntimeException; +// Holds the management server ID and shares it with other CloudStack components public class ManagementServerNode extends AdapterBase implements SystemIntegrityChecker { + // Load the ID once and keep the same value for the life of this process private static final long s_nodeId = ManagementServerId.get(); + // Register this component to run early during CloudStack startup public ManagementServerNode() { setRunLevel(ComponentLifecycle.RUN_LEVEL_FRAMEWORK_BOOTSTRAP); } + // A valid server ID must be greater than zero @Override public void check() { if (s_nodeId <= 0) { @@ -41,10 +45,12 @@ public void check() { } } + // Other components call this to get the same server ID public static long getManagementServerId() { return s_nodeId; } + // Check the ID during startup. Log an error and stop if the check fails @Override public boolean start() { try { diff --git a/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java index a385c085cb2a..8962150ec4ff 100644 --- a/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java +++ b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java @@ -46,19 +46,23 @@ public class ManagementServerIdTest { + // Give each test its own temporary folder @Rule public TemporaryFolder folder = new TemporaryFolder(); + // Choose where this test will save its ID private Path idFile() { return folder.getRoot().toPath().resolve("identity/management-server.id"); } + // Fail the test if the code asks for a new ID when it should not private LongSupplier unexpectedLookup() { return () -> { throw new AssertionError("Network interfaces must not be consulted"); }; } + // Keep the saved ID even when the network card would give a different ID @Test public void preservesInitialIdWhenNetworkInterfacesChange() throws IOException { Path path = idFile(); @@ -67,6 +71,7 @@ public void preservesInitialIdWhenNetworkInterfacesChange() throws IOException { assertEquals(130014950130305L, ManagementServerId.load(path, null, unexpectedLookup())); } + // Use the chosen ID first and keep the saved ID for later @Test public void configuredIdTakesPrecedenceOverSavedId() throws IOException { Path path = idFile(); @@ -75,12 +80,14 @@ public void configuredIdTakesPrecedenceOverSavedId() throws IOException { assertEquals(42L, ManagementServerId.load(path, null, unexpectedLookup())); } + // A chosen ID still works when we cannot save a file @Test public void configuredIdDoesNotRequireWritableStorage() throws IOException { Path path = folder.newFile("not-a-directory").toPath().resolve("id"); assertEquals(123L, ManagementServerId.load(path, "123", unexpectedLookup())); } + // Reject bad IDs from the settings and do not save them @Test public void rejectsInvalidConfiguredIds() { for (String value : new String[] {"", "0", "-1", "invalid", "9223372036854775808"}) { @@ -90,6 +97,7 @@ public void rejectsInvalidConfiguredIds() { assertFalse(Files.exists(idFile())); } + // Reject a bad saved ID without changing its file @Test public void rejectsInvalidSavedIdsWithoutReplacingThem() throws IOException { Path path = folder.newFile("id").toPath(); @@ -101,6 +109,7 @@ public void rejectsInvalidSavedIdsWithoutReplacingThem() throws IOException { } } + // Do not save a new ID if it is zero or negative @Test public void rejectsInvalidInitialIdsWithoutSavingThem() { for (long value : new long[] {0L, -1L}) { @@ -110,16 +119,19 @@ public void rejectsInvalidInitialIdsWithoutSavingThem() { assertFalse(Files.exists(idFile())); } + // Report an error when the ID file cannot be saved @Test public void failsWhenIdentityCannotBeSaved() throws IOException { Path path = folder.newFile("not-a-directory").toPath().resolve("id"); assertThrows(IOException.class, () -> ManagementServerId.load(path, null, unexpectedLookup())); } + // A failed write leaves no broken ID file and a later try can succeed @Test public void failedInitialWriteDoesNotPublishAnInvalidIdentity() throws IOException { Path path = idFile(); AtomicReference underlyingWriter = new AtomicReference<>(); + // Make the file writer fail on purpose FileChannel failedWriter = Mockito.mock(FileChannel.class); Mockito.when(failedWriter.write(Mockito.any(ByteBuffer.class))).thenThrow(new IOException("Interrupted write")); Mockito.doAnswer(invocation -> { @@ -141,11 +153,12 @@ public void failedInitialWriteDoesNotPublishAnInvalidIdentity() throws IOExcepti assertFalse(Files.exists(path)); try (Stream files = Files.list(path.getParent())) { - assertEquals(1L, files.count()); // Only the interprocess lock remains. + assertEquals(1L, files.count()); // Only the interprocess lock remains } assertEquals(43L, ManagementServerId.load(path, null, () -> 43L)); } + // Allow spaces around a valid ID and accept the biggest allowed number @Test public void readsWhitespaceAndFullLongIds() throws IOException { Path path = folder.newFile("id").toPath(); @@ -153,6 +166,7 @@ public void readsWhitespaceAndFullLongIds() throws IOException { assertEquals(Long.MAX_VALUE, ManagementServerId.load(path, null, unexpectedLookup())); } + // Use the chosen file and ID settings and report a bad saved file @Test public void usesJvmSettingsAndReportsInvalidStorage() throws IOException { String previousFile = System.getProperty("management.server.id.file"); @@ -176,6 +190,7 @@ public void usesJvmSettingsAndReportsInvalidStorage() throws IOException { } } + // Three programs using the same file must all get the same ID @Test public void concurrentProcessesUseTheSameId() throws Exception { Path path = idFile(); @@ -199,12 +214,14 @@ public void concurrentProcessesUseTheSameId() throws Exception { } } + // A small helper program that loads an ID and prints it public static class IdWriter { public static void main(String[] args) throws IOException { System.out.println(ManagementServerId.load(Paths.get(args[0]), null, () -> Long.parseLong(args[1]))); } } + // Put the settings back so one test does not affect another private void restoreProperty(String name, String value) { if (value == null) { System.clearProperty(name); From 91d9d3d8bbe15691fb90c58969d7239901d5ac1e Mon Sep 17 00:00:00 2001 From: Mashrfee Aryan Date: Thu, 5 Nov 2026 18:09:26 -0600 Subject: [PATCH 07/12] Recover existing management server IDs on upgrade --- INSTALL.md | 12 +- PendingReleaseNotes | 3 +- .../db/ManagementServerIdProviderImpl.java | 67 ++++++++ ....utils.identity.ManagementServerIdProvider | 18 +++ .../db/ManagementServerIdRecoveryTest.java | 143 ++++++++++++++++++ .../utils/identity/ManagementServerId.java | 16 +- .../identity/ManagementServerIdProvider.java | 25 +++ .../utils/identity/ManagementServerNode.java | 11 +- .../identity/ManagementServerIdTest.java | 61 ++++++++ 9 files changed, 345 insertions(+), 11 deletions(-) create mode 100644 framework/db/src/main/java/com/cloud/utils/db/ManagementServerIdProviderImpl.java create mode 100644 framework/db/src/main/resources/META-INF/services/org.apache.cloudstack.utils.identity.ManagementServerIdProvider create mode 100644 framework/db/src/test/java/com/cloud/utils/db/ManagementServerIdRecoveryTest.java create mode 100644 utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerIdProvider.java diff --git a/INSTALL.md b/INSTALL.md index 76e2a389eee8..8a0f1d176b98 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -204,9 +204,15 @@ These options can be added to `JAVA_OPTS` in `/etc/default/cloudstack-management * `-Dmanagement.server.id=123456789` overrides the ID with a positive number unique to this server. It does not change the saved file. -If interface order already changed before upgrading, set `management.server.id` -to this server's original `msid` from `cloud.mshost` before the first start. -Keep that override configured on later starts. +On the first start without an ID file, the server looks in `cloud.mshost` for +non-removed records matching `cluster.node.IP` (default `127.0.0.1`). It saves +and reuses the `msid` with the latest `last_update`. Only a server with no +matching records gets an initial ID from a network card. Database lookup +failures stop startup rather than saving a different ID. + +If different IDs share the latest timestamp, startup stops. Check the matching +records and use `management.server.id` to choose the intended ID. This override +does not create an ID file, so keep it configured on later starts. ## Notes diff --git a/PendingReleaseNotes b/PendingReleaseNotes index 3a0ee3a836c4..db15347eecdc 100644 --- a/PendingReleaseNotes +++ b/PendingReleaseNotes @@ -43,7 +43,8 @@ example.ver.1 > example.ver.2: 4.22.1.0 > 4.22.2.0: * Management servers now reuse a saved ID after restarts, so network interface reordering does not change their identity. Keep the ID file during upgrades - and restores. See INSTALL.md for the file location and ID settings. + and restores. On the first start without a file, reuse the most recently + used ID for this server IP from mshost. See INSTALL.md for details. * Old non-Up management server records no longer cause agents to avoid an IP that also has an Up record. diff --git a/framework/db/src/main/java/com/cloud/utils/db/ManagementServerIdProviderImpl.java b/framework/db/src/main/java/com/cloud/utils/db/ManagementServerIdProviderImpl.java new file mode 100644 index 000000000000..0fc1c2bc8d29 --- /dev/null +++ b/framework/db/src/main/java/com/cloud/utils/db/ManagementServerIdProviderImpl.java @@ -0,0 +1,67 @@ +// 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 com.cloud.utils.db; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.Objects; +import java.util.OptionalLong; + +import org.apache.cloudstack.utils.identity.ManagementServerIdProvider; + +import com.cloud.utils.exception.CloudRuntimeException; + +// Finds the last ID used by this management server before the ID file existed +public class ManagementServerIdProviderImpl implements ManagementServerIdProvider { + static final String FIND_EXISTING_ID = "SELECT msid, last_update FROM mshost " + + "WHERE service_ip = ? AND removed IS NULL ORDER BY last_update DESC, msid ASC LIMIT 2"; + + @Override + public OptionalLong findExistingId() { + // Use the same IP setting and default as the cluster manager + String serviceIp = DbProperties.getDbProperties().getProperty("cluster.node.IP", "127.0.0.1").trim(); + try (TransactionLegacy transaction = TransactionLegacy.open("RecoverManagementServerId"); + PreparedStatement statement = transaction.prepareStatement(FIND_EXISTING_ID)) { + statement.setString(1, serviceIp); + try (ResultSet records = statement.executeQuery()) { + return selectId(records); + } + } catch (SQLException e) { + // A broken database connection must not make us save a new ID + throw new CloudRuntimeException("Unable to recover the management server ID for " + serviceIp, e); + } + } + + static OptionalLong selectId(ResultSet records) throws SQLException { + if (!records.next()) { + return OptionalLong.empty(); + } + long msid = records.getLong("msid"); + Timestamp lastUpdate = records.getTimestamp("last_update"); + // The query puts the most recently used ID first + // If two IDs are equally recent, ask the admin to choose instead of guessing + if (records.next() && records.getLong("msid") != msid + && Objects.equals(lastUpdate, records.getTimestamp("last_update"))) { + throw new CloudRuntimeException("Multiple management server IDs have the same latest last_update; " + + "set management.server.id to the intended msid from mshost"); + } + return OptionalLong.of(msid); + } +} diff --git a/framework/db/src/main/resources/META-INF/services/org.apache.cloudstack.utils.identity.ManagementServerIdProvider b/framework/db/src/main/resources/META-INF/services/org.apache.cloudstack.utils.identity.ManagementServerIdProvider new file mode 100644 index 000000000000..f5494445ffc1 --- /dev/null +++ b/framework/db/src/main/resources/META-INF/services/org.apache.cloudstack.utils.identity.ManagementServerIdProvider @@ -0,0 +1,18 @@ +# 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. + +com.cloud.utils.db.ManagementServerIdProviderImpl diff --git a/framework/db/src/test/java/com/cloud/utils/db/ManagementServerIdRecoveryTest.java b/framework/db/src/test/java/com/cloud/utils/db/ManagementServerIdRecoveryTest.java new file mode 100644 index 000000000000..1f07e545cd17 --- /dev/null +++ b/framework/db/src/test/java/com/cloud/utils/db/ManagementServerIdRecoveryTest.java @@ -0,0 +1,143 @@ +// 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 com.cloud.utils.db; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.Properties; +import java.util.ServiceLoader; + +import org.junit.Test; +import org.mockito.MockedStatic; + +import org.apache.cloudstack.utils.identity.ManagementServerIdProvider; + +import com.cloud.utils.exception.CloudRuntimeException; + +public class ManagementServerIdRecoveryTest { + private final ResultSet records = mock(ResultSet.class); + + // A new server has no old ID to recover + @Test + public void noMatchingRecordsReturnsEmpty() throws SQLException { + assertFalse(ManagementServerIdProviderImpl.selectId(records).isPresent()); + } + + // Keep the old ID even when it has no saved update time + @Test + public void singleRecordReturnsMsid() throws SQLException { + when(records.next()).thenReturn(true, false); + when(records.getLong("msid")).thenReturn(111L); + assertEquals(111L, ManagementServerIdProviderImpl.selectId(records).getAsLong()); + } + + // Reuse the newest ID when older copies of this server exist + @Test + public void newestRecordWins() throws SQLException { + when(records.next()).thenReturn(true, true); + when(records.getLong("msid")).thenReturn(222L, 111L); + when(records.getTimestamp("last_update")).thenReturn(new Timestamp(2000), new Timestamp(1000)); + assertEquals(222L, ManagementServerIdProviderImpl.selectId(records).getAsLong()); + } + + // An old record with no update time does not beat a dated record + @Test + public void datedRecordWinsOverUnknownTime() throws SQLException { + when(records.next()).thenReturn(true, true); + when(records.getLong("msid")).thenReturn(222L, 111L); + when(records.getTimestamp("last_update")).thenReturn(new Timestamp(2000), null); + assertEquals(222L, ManagementServerIdProviderImpl.selectId(records).getAsLong()); + } + + // Do not guess when different IDs have the same latest update time + @Test + public void rejectsTiedLatestTimes() throws SQLException { + when(records.next()).thenReturn(true, true); + when(records.getLong("msid")).thenReturn(111L, 222L); + when(records.getTimestamp("last_update")).thenReturn(new Timestamp(2000)); + assertThrows(CloudRuntimeException.class, () -> ManagementServerIdProviderImpl.selectId(records)); + } + + // Missing update times cannot tell us which of two IDs was used last + @Test + public void rejectsMultipleUnknownTimes() throws SQLException { + when(records.next()).thenReturn(true, true); + when(records.getLong("msid")).thenReturn(111L, 222L); + assertThrows(CloudRuntimeException.class, () -> ManagementServerIdProviderImpl.selectId(records)); + } + + // Look up the configured server IP and exclude removed records in the query + @Test + public void queriesConfiguredIpUsingLatestNonRemovedRecords() throws SQLException { + Properties properties = new Properties(); + properties.setProperty("cluster.node.IP", " 192.0.2.10 "); + checkLookup(properties, "192.0.2.10", false); + } + + // Keep the same default IP as the existing cluster manager + @Test + public void usesDefaultIpWhenNotConfigured() throws SQLException { + checkLookup(new Properties(), "127.0.0.1", false); + } + + // Database failures must stop recovery instead of pretending this is a new server + @Test + public void reportsDatabaseFailure() throws SQLException { + checkLookup(new Properties(), "127.0.0.1", true); + } + + private void checkLookup(Properties properties, String expectedIp, boolean fail) throws SQLException { + TransactionLegacy transaction = mock(TransactionLegacy.class); + PreparedStatement statement = mock(PreparedStatement.class); + try (MockedStatic db = mockStatic(DbProperties.class); + MockedStatic transactions = mockStatic(TransactionLegacy.class)) { + db.when(DbProperties::getDbProperties).thenReturn(properties); + transactions.when(() -> TransactionLegacy.open("RecoverManagementServerId")).thenReturn(transaction); + when(transaction.prepareStatement(ManagementServerIdProviderImpl.FIND_EXISTING_ID)).thenReturn(statement); + if (fail) { + when(statement.executeQuery()).thenThrow(new SQLException("Unavailable")); + assertThrows(CloudRuntimeException.class, () -> new ManagementServerIdProviderImpl().findExistingId()); + } else { + when(statement.executeQuery()).thenReturn(records); + when(records.next()).thenReturn(true, false); + when(records.getLong("msid")).thenReturn(111L); + assertEquals(111L, new ManagementServerIdProviderImpl().findExistingId().getAsLong()); + } + verify(statement).setString(1, expectedIp); + verify(statement).close(); + verify(transaction).close(); + } + } + + // Make sure the ID helper can discover the real database lookup + @Test + public void databaseProviderIsDiscoverable() { + assertEquals(ManagementServerIdProviderImpl.class, + ServiceLoader.load(ManagementServerIdProvider.class).findFirst().get().getClass()); + } +} diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java index edeb78e2f431..81244272d6e1 100644 --- a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java @@ -27,6 +27,8 @@ import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; +import java.util.OptionalLong; +import java.util.ServiceLoader; import java.util.function.LongSupplier; import com.cloud.utils.exception.CloudRuntimeException; @@ -45,14 +47,22 @@ static long get() { try { // Use the ID from management.server.id if it is set // Otherwise, read the saved ID from the file at path - // If the file does not exist, create an ID from the MAC address and save it - return load(path, System.getProperty("management.server.id"), () -> MacAddress.getMacAddress().toLong()); + // If the file does not exist, look for the old ID in the database first + return load(path, System.getProperty("management.server.id"), ManagementServerId::initialId); } catch (IOException | IllegalArgumentException e) { // Stop with a clear error instead of silently choosing a different identity throw new CloudRuntimeException("Unable to load the management server ID from " + path, e); } } + // Recover the old server ID before asking a network card for a new one + private static long initialId() { + ManagementServerIdProvider provider = ServiceLoader.load(ManagementServerIdProvider.class) + .findFirst().orElseThrow(() -> new CloudRuntimeException("Management server ID database lookup is unavailable")); + OptionalLong existingId = provider.findExistingId(); + return existingId.isPresent() ? existingId.getAsLong() : MacAddress.getMacAddress().toLong(); + } + static long load(Path path, String configuredId, LongSupplier initialId) throws IOException { // An operator-provided ID takes priority without overwriting the saved file if (configuredId != null) { @@ -74,7 +84,7 @@ static long load(Path path, String configuredId, LongSupplier initialId) throws return parse(new String(Files.readAllBytes(path), StandardCharsets.UTF_8)); } - // First startup: obtain the initial MAC-derived ID and validate it + // With no saved file, recover the old ID or create one for a new server long id = parse(Long.toString(initialId.getAsLong())); // Write in the same directory so the completed file can be renamed atomically Path temporary = Files.createTempFile(path.toAbsolutePath().getParent(), "management-server-id-", ".tmp"); diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerIdProvider.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerIdProvider.java new file mode 100644 index 000000000000..065e725578a2 --- /dev/null +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerIdProvider.java @@ -0,0 +1,25 @@ +// 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.cloudstack.utils.identity; + +import java.util.OptionalLong; + +// Lets the database module find an old ID without making utils depend on it +public interface ManagementServerIdProvider { + OptionalLong findExistingId(); +} diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java index e9df0f991573..ec27a966ec60 100644 --- a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java @@ -29,8 +29,8 @@ // Holds the management server ID and shares it with other CloudStack components public class ManagementServerNode extends AdapterBase implements SystemIntegrityChecker { - // Load the ID once and keep the same value for the life of this process - private static final long s_nodeId = ManagementServerId.get(); + // Keep the ID after it has been loaded successfully + private static Long s_nodeId; // Register this component to run early during CloudStack startup public ManagementServerNode() { @@ -40,13 +40,16 @@ public ManagementServerNode() { // A valid server ID must be greater than zero @Override public void check() { - if (s_nodeId <= 0) { + if (getManagementServerId() <= 0) { throw new CloudRuntimeException("Unable to get the management server node id"); } } // Other components call this to get the same server ID - public static long getManagementServerId() { + public static synchronized long getManagementServerId() { + if (s_nodeId == null) { + s_nodeId = ManagementServerId.get(); + } return s_nodeId; } diff --git a/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java index 8962150ec4ff..a809ec479b2a 100644 --- a/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java +++ b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java @@ -31,6 +31,9 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; +import java.util.Optional; +import java.util.OptionalLong; +import java.util.ServiceLoader; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.LongSupplier; @@ -43,6 +46,7 @@ import org.mockito.Mockito; import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.net.MacAddress; public class ManagementServerIdTest { @@ -190,6 +194,63 @@ public void usesJvmSettingsAndReportsInvalidStorage() throws IOException { } } + // Save the database ID on upgrade even when the network card gives another ID + @Test + public void recoversDatabaseIdBeforeMacAndKeepsItOnRestart() throws IOException { + checkDatabaseRecovery(OptionalLong.of(111L), false); + } + + // Only a server with no matching database record gets a MAC based ID + @Test + public void newServerUsesMacWhenDatabaseHasNoRecord() throws IOException { + checkDatabaseRecovery(OptionalLong.empty(), false); + } + + // Failed database lookups must not leave a new permanent ID file + @Test + public void databaseFailureDoesNotCreateIdFile() throws IOException { + checkDatabaseRecovery(OptionalLong.empty(), true); + } + + @SuppressWarnings("unchecked") + private void checkDatabaseRecovery(OptionalLong recovered, boolean fail) throws IOException { + String previousFile = System.getProperty("management.server.id.file"); + String previousId = System.getProperty("management.server.id"); + Path path = idFile(); + ServiceLoader loader = Mockito.mock(ServiceLoader.class); + ManagementServerIdProvider provider = Mockito.mock(ManagementServerIdProvider.class); + try (MockedStatic services = Mockito.mockStatic(ServiceLoader.class); + MockedStatic mac = Mockito.mockStatic(MacAddress.class)) { + System.setProperty("management.server.id.file", path.toString()); + System.clearProperty("management.server.id"); + services.when(() -> ServiceLoader.load(ManagementServerIdProvider.class)).thenReturn(loader); + Mockito.when(loader.findFirst()).thenReturn(Optional.of(provider)); + if (fail) { + Mockito.when(provider.findExistingId()).thenThrow(new CloudRuntimeException("Database unavailable")); + assertThrows(CloudRuntimeException.class, ManagementServerId::get); + assertFalse(Files.exists(path)); + mac.verifyNoInteractions(); + } else { + Mockito.when(provider.findExistingId()).thenReturn(recovered); + MacAddress address = Mockito.mock(MacAddress.class); + mac.when(MacAddress::getMacAddress).thenReturn(address); + Mockito.when(address.toLong()).thenReturn(222L); + long expected = recovered.orElse(222L); + assertEquals(expected, ManagementServerId.get()); + assertEquals(Long.toString(expected), Files.readString(path).trim()); + Mockito.when(provider.findExistingId()).thenThrow(new AssertionError("Saved IDs must skip the database")); + assertEquals(expected, ManagementServerId.get()); + Mockito.verify(provider).findExistingId(); + if (recovered.isPresent()) { + mac.verifyNoInteractions(); + } + } + } finally { + restoreProperty("management.server.id.file", previousFile); + restoreProperty("management.server.id", previousId); + } + } + // Three programs using the same file must all get the same ID @Test public void concurrentProcessesUseTheSameId() throws Exception { From 952f8935544eca09216558a42489be78e8fc6ccb Mon Sep 17 00:00:00 2001 From: Mashrfee Aryan Date: Thu, 5 Nov 2026 19:03:44 -0600 Subject: [PATCH 08/12] Load the management server ID during startup --- .../cloud/cluster/ClusterManagerImplTest.java | 14 ++- .../core/spring-server-core-misc-context.xml | 2 - .../system/spring-server-system-context.xml | 5 +- ...irtualNetworkApplianceManagerImplTest.java | 95 ++++++++++-------- .../server/ManagementServerIdentityTest.java | 44 +++++++++ .../com/cloud/server/StatsCollectorTest.java | 11 ++- .../cloudstack/ca/CABackgroundTaskTest.java | 6 ++ .../SecondaryStorageManagerImplTest.java | 13 ++- .../SecondaryStorageManagerTest.java | 13 ++- .../utils/identity/ManagementServerNode.java | 21 ++-- .../identity/ManagementServerNodeTest.java | 99 +++++++++++++++++++ 11 files changed, 266 insertions(+), 57 deletions(-) create mode 100644 utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerNodeTest.java diff --git a/framework/cluster/src/test/java/com/cloud/cluster/ClusterManagerImplTest.java b/framework/cluster/src/test/java/com/cloud/cluster/ClusterManagerImplTest.java index 9b1854f73487..0f3aca0e8a19 100644 --- a/framework/cluster/src/test/java/com/cloud/cluster/ClusterManagerImplTest.java +++ b/framework/cluster/src/test/java/com/cloud/cluster/ClusterManagerImplTest.java @@ -17,9 +17,13 @@ package com.cloud.cluster; +import org.mockito.Mockito; + import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; +import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.mockito.MockedStatic; import org.mockito.InjectMocks; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.util.ReflectionTestUtils; @@ -27,7 +31,15 @@ @RunWith(MockitoJUnitRunner.class) public class ClusterManagerImplTest { @InjectMocks - ClusterManagerImpl clusterManager = new ClusterManagerImpl(); + ClusterManagerImpl clusterManager = createManager(); + + // Give this test a server ID without starting CloudStack + private static ClusterManagerImpl createManager() { + try (MockedStatic node = Mockito.mockStatic(ManagementServerNode.class)) { + node.when(ManagementServerNode::getManagementServerId).thenReturn(123L); + return new ClusterManagerImpl(); + } + } @Test public void testGetSelfNodeIP() { diff --git a/server/src/main/resources/META-INF/cloudstack/core/spring-server-core-misc-context.xml b/server/src/main/resources/META-INF/cloudstack/core/spring-server-core-misc-context.xml index c633a3b0abd2..c9e73ac2bbd3 100644 --- a/server/src/main/resources/META-INF/cloudstack/core/spring-server-core-misc-context.xml +++ b/server/src/main/resources/META-INF/cloudstack/core/spring-server-core-misc-context.xml @@ -73,8 +73,6 @@ - - diff --git a/server/src/main/resources/META-INF/cloudstack/system/spring-server-system-context.xml b/server/src/main/resources/META-INF/cloudstack/system/spring-server-system-context.xml index d742c639f71b..7fa4df83b47b 100644 --- a/server/src/main/resources/META-INF/cloudstack/system/spring-server-system-context.xml +++ b/server/src/main/resources/META-INF/cloudstack/system/spring-server-system-context.xml @@ -27,7 +27,10 @@ http://www.springframework.org/schema/context/spring-context.xsd" > - + + + + diff --git a/server/src/test/java/com/cloud/network/router/VirtualNetworkApplianceManagerImplTest.java b/server/src/test/java/com/cloud/network/router/VirtualNetworkApplianceManagerImplTest.java index 0365ae20175e..0faa3822e729 100644 --- a/server/src/test/java/com/cloud/network/router/VirtualNetworkApplianceManagerImplTest.java +++ b/server/src/test/java/com/cloud/network/router/VirtualNetworkApplianceManagerImplTest.java @@ -246,7 +246,15 @@ public class VirtualNetworkApplianceManagerImplTest { private RouterControlHelper _routerControlHelper; @InjectMocks - private VirtualNetworkApplianceManagerImpl virtualNetworkApplianceManagerImpl; + private VirtualNetworkApplianceManagerImpl virtualNetworkApplianceManagerImpl = createManager(); + + // Give this test a server ID without starting CloudStack + private static VirtualNetworkApplianceManagerImpl createManager() { + try (org.mockito.MockedStatic node = Mockito.mockStatic(ManagementServerNode.class)) { + node.when(ManagementServerNode::getManagementServerId).thenReturn(123L); + return new VirtualNetworkApplianceManagerImpl(); + } + } @Mock private NetworkModel _networkModel; @@ -294,47 +302,50 @@ public void testDeployRouterNotRedundant() throws Exception { @Test public void testUpdateSite2SiteVpnConnectionState() throws Exception{ - - DomainRouterVO router = new DomainRouterVO(1L, 1L, 1L, "First testing router", 1L, Hypervisor.HypervisorType.XenServer, 1L, 1L, 1L, 1L, false, VirtualRouter.RedundantState.PRIMARY, true, true, 1L); - router.setState(VirtualMachine.State.Running); - router.setPrivateIpAddress("192.168.50.15"); - - List routers = new ArrayList(); - routers.add(router); - - Site2SiteVpnConnectionVO conn = new Site2SiteVpnConnectionVO(1L, 1L, 1L, 1L, false); - Site2SiteVpnConnectionVO conn1 = new Site2SiteVpnConnectionVO(1L, 1L, 1L, 1L, false); - conn.setState(Site2SiteVpnConnection.State.Disconnected); - conn1.setState(Site2SiteVpnConnection.State.Disconnected); - List conns = new ArrayList(); - conns.add(conn); - conns.add(conn1); - - Site2SiteCustomerGatewayVO gw = new Site2SiteCustomerGatewayVO("Testing gateway", 1L, 1L, "192.168.50.15", "Guest List", "ipsecPsk", "ikePolicy", "espPolicy", 1L, 1L, true, true, false, "ike"); - HostVO hostVo = new HostVO(1L, "Testing host", Host.Type.Routing, "192.168.50.15", "privateNetmask", "privateMacAddress", "publicIpAddress", "publicNetmask", "publicMacAddress", "storageIpAddress", "storageNetmask", "storageMacAddress", "deuxStorageIpAddress", "duxStorageNetmask", "deuxStorageMacAddress", "guid", Status.Up, "version", "iqn", new Date() , 1L, 1L, 1L, 1L, "parent", 20L, Storage.StoragePoolType.Gluster); - hostVo.setManagementServerId(ManagementServerNode.getManagementServerId()); - - ArrayList ipList = new ArrayList<>(); - ipList.add("192.168.50.15"); - - _s2sConnCommand = new CheckS2SVpnConnectionsCommand(ipList); - - when(_s2sVpnMgr.getConnectionsForRouter(router)).thenReturn(conns); - when(_s2sVpnConnectionDao.persist(conn)).thenReturn(null); - when(_s2sCustomerGatewayDao.findById(conn.getCustomerGatewayId())).thenReturn(gw); - when(_hostDao.findById(router.getHostId())).thenReturn(hostVo); - when(_routerControlHelper.getRouterControlIp(router.getId())).thenReturn("192.168.50.15"); - doReturn(_s2sVpnAnswer).when(_agentMgr).easySend(nullable(Long.class), nullable(CheckS2SVpnConnectionsCommand.class)); - when(_s2sVpnAnswer.getResult()).thenReturn(true); - when(_s2sVpnConnectionDao.acquireInLockTable(conn.getId())).thenReturn(conn); - when(_s2sVpnAnswer.isIPPresent("192.168.50.15")).thenReturn(true); - when(_s2sVpnAnswer.isConnected("192.168.50.15")).thenReturn(true); - lenient().doNothing().when(_alertMgr).sendAlert(any(AlertManager.AlertType.class), anyLong(), anyLong(), anyString(), anyString()); - - virtualNetworkApplianceManagerImpl.updateSite2SiteVpnConnectionState(routers); - - for(Site2SiteVpnConnection connection : conns){ - assertEquals(Site2SiteVpnConnection.State.Connected, connection.getState()); + try (org.mockito.MockedStatic node = Mockito.mockStatic(ManagementServerNode.class)) { + node.when(ManagementServerNode::getManagementServerId).thenReturn(123L); + + DomainRouterVO router = new DomainRouterVO(1L, 1L, 1L, "First testing router", 1L, Hypervisor.HypervisorType.XenServer, 1L, 1L, 1L, 1L, false, VirtualRouter.RedundantState.PRIMARY, true, true, 1L); + router.setState(VirtualMachine.State.Running); + router.setPrivateIpAddress("192.168.50.15"); + + List routers = new ArrayList(); + routers.add(router); + + Site2SiteVpnConnectionVO conn = new Site2SiteVpnConnectionVO(1L, 1L, 1L, 1L, false); + Site2SiteVpnConnectionVO conn1 = new Site2SiteVpnConnectionVO(1L, 1L, 1L, 1L, false); + conn.setState(Site2SiteVpnConnection.State.Disconnected); + conn1.setState(Site2SiteVpnConnection.State.Disconnected); + List conns = new ArrayList(); + conns.add(conn); + conns.add(conn1); + + Site2SiteCustomerGatewayVO gw = new Site2SiteCustomerGatewayVO("Testing gateway", 1L, 1L, "192.168.50.15", "Guest List", "ipsecPsk", "ikePolicy", "espPolicy", 1L, 1L, true, true, false, "ike"); + HostVO hostVo = new HostVO(1L, "Testing host", Host.Type.Routing, "192.168.50.15", "privateNetmask", "privateMacAddress", "publicIpAddress", "publicNetmask", "publicMacAddress", "storageIpAddress", "storageNetmask", "storageMacAddress", "deuxStorageIpAddress", "duxStorageNetmask", "deuxStorageMacAddress", "guid", Status.Up, "version", "iqn", new Date() , 1L, 1L, 1L, 1L, "parent", 20L, Storage.StoragePoolType.Gluster); + hostVo.setManagementServerId(ManagementServerNode.getManagementServerId()); + + ArrayList ipList = new ArrayList<>(); + ipList.add("192.168.50.15"); + + _s2sConnCommand = new CheckS2SVpnConnectionsCommand(ipList); + + when(_s2sVpnMgr.getConnectionsForRouter(router)).thenReturn(conns); + when(_s2sVpnConnectionDao.persist(conn)).thenReturn(null); + when(_s2sCustomerGatewayDao.findById(conn.getCustomerGatewayId())).thenReturn(gw); + when(_hostDao.findById(router.getHostId())).thenReturn(hostVo); + when(_routerControlHelper.getRouterControlIp(router.getId())).thenReturn("192.168.50.15"); + doReturn(_s2sVpnAnswer).when(_agentMgr).easySend(nullable(Long.class), nullable(CheckS2SVpnConnectionsCommand.class)); + when(_s2sVpnAnswer.getResult()).thenReturn(true); + when(_s2sVpnConnectionDao.acquireInLockTable(conn.getId())).thenReturn(conn); + when(_s2sVpnAnswer.isIPPresent("192.168.50.15")).thenReturn(true); + when(_s2sVpnAnswer.isConnected("192.168.50.15")).thenReturn(true); + lenient().doNothing().when(_alertMgr).sendAlert(any(AlertManager.AlertType.class), anyLong(), anyLong(), anyString(), anyString()); + + virtualNetworkApplianceManagerImpl.updateSite2SiteVpnConnectionState(routers); + + for(Site2SiteVpnConnection connection : conns){ + assertEquals(Site2SiteVpnConnection.State.Connected, connection.getState()); + } } } diff --git a/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java b/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java index 00c3d9373ebb..82730683e46a 100644 --- a/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java +++ b/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java @@ -18,6 +18,7 @@ package com.cloud.server; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; @@ -28,11 +29,15 @@ import org.mockito.MockedStatic; import org.mockito.Mockito; import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import com.cloud.cluster.ManagementServerHostVO; import com.cloud.cluster.dao.ManagementServerHostDao; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.db.Merovingian2; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.TransactionCallbackNoReturn; import com.cloud.utils.net.MacAddress; @@ -43,6 +48,45 @@ public class ManagementServerIdentityTest { private static final long SAVED_ID = 123L; private static final long CHANGED_MAC_ID = 456L; + // The real Spring setup must start the ID component before the lock controller + @Test + public void springStartsIdentityBeforeFirstConsumer() { + checkSpringStartup(false); + } + + // A bad ID must stop Spring startup before the lock controller uses it + @Test + public void springReportsIdentityFailureBeforeStartingConsumer() { + checkSpringStartup(true); + } + + private void checkSpringStartup(boolean invalid) { + Object previousId = ReflectionTestUtils.getField(ManagementServerNode.class, "s_nodeId"); + String previousSetting = System.getProperty("management.server.id"); + try (MockedStatic locks = mockStatic(Merovingian2.class); + GenericApplicationContext context = new GenericApplicationContext()) { + ReflectionTestUtils.setField(ManagementServerNode.class, "s_nodeId", null); + System.setProperty("management.server.id", invalid ? "invalid" : "123"); + new XmlBeanDefinitionReader(context).loadBeanDefinitions( + "classpath:META-INF/cloudstack/system/spring-server-system-context.xml"); + if (invalid) { + assertThrows(BeanCreationException.class, context::refresh); + locks.verifyNoInteractions(); + } else { + context.refresh(); + assertEquals(123L, ManagementServerNode.getManagementServerId()); + locks.verify(() -> Merovingian2.createLockController(123L)); + } + } finally { + ReflectionTestUtils.setField(ManagementServerNode.class, "s_nodeId", previousId); + if (previousSetting == null) { + System.clearProperty("management.server.id"); + } else { + System.setProperty("management.server.id", previousSetting); + } + } + } + // Return the saved ID even when the network card gives a different ID @Test public void managementServiceReportsSavedIdAfterMacChanges() { diff --git a/server/src/test/java/com/cloud/server/StatsCollectorTest.java b/server/src/test/java/com/cloud/server/StatsCollectorTest.java index cb00d1652c9a..dd2bae907eb6 100644 --- a/server/src/test/java/com/cloud/server/StatsCollectorTest.java +++ b/server/src/test/java/com/cloud/server/StatsCollectorTest.java @@ -18,6 +18,7 @@ // package com.cloud.server; +import org.apache.cloudstack.utils.identity.ManagementServerNode; import static org.mockito.Mockito.when; import java.lang.reflect.Field; @@ -89,7 +90,15 @@ public class StatsCollectorTest { @InjectMocks - private StatsCollector statsCollector = Mockito.spy(new StatsCollector()); + private StatsCollector statsCollector = Mockito.spy(createCollector()); + + // Give this test a server ID without starting CloudStack + private static StatsCollector createCollector() { + try (MockedStatic node = Mockito.mockStatic(ManagementServerNode.class)) { + node.when(ManagementServerNode::getManagementServerId).thenReturn(123L); + return new StatsCollector(); + } + } private static final int GRAPHITE_DEFAULT_PORT = 2003; private static final int INFLUXDB_DEFAULT_PORT = 8086; diff --git a/server/src/test/java/org/apache/cloudstack/ca/CABackgroundTaskTest.java b/server/src/test/java/org/apache/cloudstack/ca/CABackgroundTaskTest.java index 691bd882c078..a06033354b8c 100644 --- a/server/src/test/java/org/apache/cloudstack/ca/CABackgroundTaskTest.java +++ b/server/src/test/java/org/apache/cloudstack/ca/CABackgroundTaskTest.java @@ -35,6 +35,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; +import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; @@ -67,8 +68,12 @@ public class CABackgroundTaskTest { private Map certMap = new HashMap<>(); private CAManagerImpl.CABackgroundTask task; + private MockedStatic node; + @Before public void setUp() throws Exception { + node = Mockito.mockStatic(ManagementServerNode.class); + node.when(ManagementServerNode::getManagementServerId).thenReturn(123L); host.setManagementServerId(ManagementServerNode.getManagementServerId()); task = new CAManagerImpl.CABackgroundTask(caManager, hostDao); final KeyPair keypair = CertUtils.generateRandomKeyPair(1024); @@ -80,6 +85,7 @@ public void setUp() throws Exception { @After public void tearDown() throws Exception { + node.close(); certMap.clear(); Mockito.reset(caManager); Mockito.reset(hostDao); diff --git a/services/secondary-storage/controller/src/test/java/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImplTest.java b/services/secondary-storage/controller/src/test/java/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImplTest.java index 83596b64ec0f..b82b220b1f6f 100644 --- a/services/secondary-storage/controller/src/test/java/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImplTest.java +++ b/services/secondary-storage/controller/src/test/java/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImplTest.java @@ -16,6 +16,7 @@ // under the License. package org.apache.cloudstack.secondarystorage; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.any; @@ -30,6 +31,8 @@ import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.junit.runner.RunWith; +import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.mockito.MockedStatic; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; @@ -61,7 +64,15 @@ public class SecondaryStorageManagerImplTest { @Spy @InjectMocks - private SecondaryStorageManagerImpl secondaryStorageManager; + private SecondaryStorageManagerImpl secondaryStorageManager = createManager(); + + // Give this test a server ID without starting CloudStack + private static SecondaryStorageManagerImpl createManager() { + try (MockedStatic node = Mockito.mockStatic(ManagementServerNode.class)) { + node.when(ManagementServerNode::getManagementServerId).thenReturn(123L); + return new SecondaryStorageManagerImpl(); + } + } @Mock private ServiceOffering serviceOffering; diff --git a/services/secondary-storage/controller/src/test/java/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerTest.java b/services/secondary-storage/controller/src/test/java/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerTest.java index 2d48451f43e9..caf8b1f4d98c 100644 --- a/services/secondary-storage/controller/src/test/java/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerTest.java +++ b/services/secondary-storage/controller/src/test/java/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerTest.java @@ -17,6 +17,7 @@ package org.apache.cloudstack.secondarystorage; + import static org.mockito.AdditionalMatchers.not; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyLong; @@ -34,6 +35,8 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.apache.cloudstack.utils.identity.ManagementServerNode; +import org.mockito.MockedStatic; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; @@ -61,7 +64,15 @@ public class SecondaryStorageManagerTest { NetworkModel _networkModel; @InjectMocks - SecondaryStorageManagerImpl _ssMgr = new SecondaryStorageManagerImpl(); + SecondaryStorageManagerImpl _ssMgr = createManager(); + + // Give this test a server ID without starting CloudStack + private static SecondaryStorageManagerImpl createManager() { + try (MockedStatic node = Mockito.mockStatic(ManagementServerNode.class)) { + node.when(ManagementServerNode::getManagementServerId).thenReturn(123L); + return new SecondaryStorageManagerImpl(); + } + } private AutoCloseable closeable; diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java index ec27a966ec60..90896376aa8a 100644 --- a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java @@ -45,22 +45,27 @@ public void check() { } } - // Other components call this to get the same server ID + // Return the ID loaded by start without reading a file or the database public static synchronized long getManagementServerId() { if (s_nodeId == null) { - s_nodeId = ManagementServerId.get(); + throw new CloudRuntimeException("Management server ID has not been initialized; start ManagementServerNode first"); } return s_nodeId; } - // Check the ID during startup. Log an error and stop if the check fails + // Load the ID during startup before other components need it @Override public boolean start() { - try { - check(); - } catch (Exception e) { - logger.error("System integrity check exception", e); - System.exit(1); + synchronized (ManagementServerNode.class) { + try { + if (s_nodeId == null) { + s_nodeId = ManagementServerId.get(); + } + check(); + } catch (Exception e) { + logger.error("Unable to initialize the management server ID", e); + throw new CloudRuntimeException("Unable to initialize the management server ID", e); + } } return true; } diff --git a/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerNodeTest.java b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerNodeTest.java new file mode 100644 index 000000000000..5e0f7fcdb5c7 --- /dev/null +++ b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerNodeTest.java @@ -0,0 +1,99 @@ +// 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.cloudstack.utils.identity; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; + +import java.lang.reflect.Field; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.MockedStatic; + +import com.cloud.utils.exception.CloudRuntimeException; + +public class ManagementServerNodeTest { + private Field idField; + private Object previousId; + + @Before + public void clearId() throws Exception { + idField = ManagementServerNode.class.getDeclaredField("s_nodeId"); + idField.setAccessible(true); + previousId = idField.get(null); + idField.set(null, null); + } + + @After + public void restoreId() throws Exception { + idField.set(null, previousId); + } + + // Creating the component and asking too early must not read the ID + @Test + public void getterDoesNotLoadIdBeforeStart() { + try (MockedStatic ids = mockStatic(ManagementServerId.class)) { + new ManagementServerNode(); + assertThrows(CloudRuntimeException.class, ManagementServerNode::getManagementServerId); + ids.verifyNoInteractions(); + } + } + + // Starting loads the ID once and shares it with every later caller + @Test + public void startLoadsIdOnlyOnce() { + try (MockedStatic ids = mockStatic(ManagementServerId.class)) { + ids.when(ManagementServerId::get).thenReturn(111L, 222L); + ManagementServerNode node = new ManagementServerNode(); + assertTrue(node.start()); + assertEquals(111L, ManagementServerNode.getManagementServerId()); + assertTrue(node.start()); + assertEquals(111L, ManagementServerNode.getManagementServerId()); + ids.verify(ManagementServerId::get, times(1)); + } + } + + // A failed read gives a startup error and does not break the Java class + @Test + public void failedStartCanBeRetried() { + try (MockedStatic ids = mockStatic(ManagementServerId.class)) { + CloudRuntimeException failure = new CloudRuntimeException("Cannot read ID file"); + ids.when(ManagementServerId::get).thenThrow(failure).thenReturn(111L); + ManagementServerNode node = new ManagementServerNode(); + CloudRuntimeException error = assertThrows(CloudRuntimeException.class, node::start); + assertEquals(failure, error.getCause()); + assertThrows(CloudRuntimeException.class, ManagementServerNode::getManagementServerId); + assertTrue(node.start()); + assertEquals(111L, ManagementServerNode.getManagementServerId()); + } + } + + // Checking an unstarted component must not secretly load the ID + @Test + public void integrityCheckDoesNotLoadId() { + try (MockedStatic ids = mockStatic(ManagementServerId.class)) { + assertThrows(CloudRuntimeException.class, () -> new ManagementServerNode().check()); + ids.verifyNoInteractions(); + } + } +} From fca0ad4dcca2c249f1319501dd958f3bfc4ba752 Mon Sep 17 00:00:00 2001 From: Mashrfee Aryan Date: Thu, 5 Nov 2026 19:57:40 -0600 Subject: [PATCH 09/12] Check for copied server IDs and let admins reset them --- INSTALL.md | 30 +++ PendingReleaseNotes | 3 + .../db/ManagementServerIdProviderImpl.java | 22 ++- .../db/ManagementServerIdRecoveryTest.java | 43 +++++ .../server/ManagementServerIdentityTest.java | 58 +++++- .../utils/identity/ManagementServerId.java | 109 ++++++++--- .../identity/ManagementServerIdProvider.java | 6 + .../identity/ManagementServerIdTest.java | 172 +++++++++++++++++- 8 files changed, 417 insertions(+), 26 deletions(-) diff --git a/INSTALL.md b/INSTALL.md index 8a0f1d176b98..7e2b9d58642a 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -214,6 +214,36 @@ If different IDs share the latest timestamp, startup stops. Check the matching records and use `management.server.id` to choose the intended ID. This override does not create an ID file, so keep it configured on later starts. +### Copied servers and IP changes + +At startup, the server checks the chosen ID against `cloud.mshost`. If the ID +is recorded with a different IP from `cluster.node.IP`, startup stops before +registration and logs the ID, both IPs, and the settings below. The ID file and +the database record stay unchanged until you make a choice. A database failure +also stops startup. This check does not identify clones using the same IP, or +IDs absent from this database; existing same-IP conflict checks still apply. + +Add the appropriate option to `JAVA_OPTS` before starting the service again: + +* **New cloned server:** set `-Dmanagement.server.id.reset.from=111`, replacing + `111` with the copied ID shown in the log. Remove any `management.server.id` + override first. The server creates a random positive ID not found in `mshost` + and atomically replaces its local ID file. It does not change the original + server's record. The setting only replaces that named old ID, so keeping it + temporarily does not create another ID on later starts. Remove it after a + successful start. Run the clone with its own IP and its own local disk, never + with the original server's shared ID file. A copied explicit ID override must + also be removed or deliberately replaced with a unique one. +* **Same server moved to a new IP:** stop the original instance, then set + `-Dmanagement.server.id.previous.ip=192.0.2.1`, using the recorded old IP shown + in the log. The server keeps its ID and normal registration updates its IP. + Remove this confirmation after a successful start. A different recorded old + IP will still be rejected. + +These are startup settings, not an interactive prompt. Do not reset the ID of +the original server during an ordinary restart or upgrade. Keep the copied ID +file until you make the choice; deleting it can trigger recovery from `mshost`. + ## Notes If you will be using Xen as your hypervisor, please download [vhd-util](https://download.cloudstack.org/tools/vhd-util) diff --git a/PendingReleaseNotes b/PendingReleaseNotes index db15347eecdc..be0dea9c0f5c 100644 --- a/PendingReleaseNotes +++ b/PendingReleaseNotes @@ -45,6 +45,9 @@ example.ver.1 > example.ver.2: reordering does not change their identity. Keep the ID file during upgrades and restores. On the first start without a file, reuse the most recently used ID for this server IP from mshost. See INSTALL.md for details. + * Management server startup rejects IDs recorded at a different IP until an + operator confirms an IP move or requests a fresh ID for a cloned server. + See INSTALL.md for the startup settings and detection limits. * Old non-Up management server records no longer cause agents to avoid an IP that also has an Up record. diff --git a/framework/db/src/main/java/com/cloud/utils/db/ManagementServerIdProviderImpl.java b/framework/db/src/main/java/com/cloud/utils/db/ManagementServerIdProviderImpl.java index 0fc1c2bc8d29..7fbd367adcf2 100644 --- a/framework/db/src/main/java/com/cloud/utils/db/ManagementServerIdProviderImpl.java +++ b/framework/db/src/main/java/com/cloud/utils/db/ManagementServerIdProviderImpl.java @@ -23,6 +23,7 @@ import java.sql.Timestamp; import java.util.Objects; import java.util.OptionalLong; +import java.util.Optional; import org.apache.cloudstack.utils.identity.ManagementServerIdProvider; @@ -36,7 +37,7 @@ public class ManagementServerIdProviderImpl implements ManagementServerIdProvide @Override public OptionalLong findExistingId() { // Use the same IP setting and default as the cluster manager - String serviceIp = DbProperties.getDbProperties().getProperty("cluster.node.IP", "127.0.0.1").trim(); + String serviceIp = getServiceIp(); try (TransactionLegacy transaction = TransactionLegacy.open("RecoverManagementServerId"); PreparedStatement statement = transaction.prepareStatement(FIND_EXISTING_ID)) { statement.setString(1, serviceIp); @@ -49,6 +50,25 @@ public OptionalLong findExistingId() { } } + @Override + public String getServiceIp() { + return DbProperties.getDbProperties().getProperty("cluster.node.IP", "127.0.0.1").trim(); + } + + @Override + public Optional findServiceIp(long id) { + // Read only so a rejected clone cannot change the original server record + try (TransactionLegacy transaction = TransactionLegacy.open("CheckManagementServerIdentity"); + PreparedStatement statement = transaction.prepareStatement("SELECT service_ip FROM mshost WHERE msid = ?")) { + statement.setLong(1, id); + try (ResultSet records = statement.executeQuery()) { + return records.next() ? Optional.of(records.getString("service_ip").trim()) : Optional.empty(); + } + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to check the recorded IP for management server ID " + id, e); + } + } + static OptionalLong selectId(ResultSet records) throws SQLException { if (!records.next()) { return OptionalLong.empty(); diff --git a/framework/db/src/test/java/com/cloud/utils/db/ManagementServerIdRecoveryTest.java b/framework/db/src/test/java/com/cloud/utils/db/ManagementServerIdRecoveryTest.java index 1f07e545cd17..f6af58f8cf5d 100644 --- a/framework/db/src/test/java/com/cloud/utils/db/ManagementServerIdRecoveryTest.java +++ b/framework/db/src/test/java/com/cloud/utils/db/ManagementServerIdRecoveryTest.java @@ -134,6 +134,49 @@ private void checkLookup(Properties properties, String expectedIp, boolean fail) } } + // Read the recorded IP without changing the server record + @Test + public void readsIpForExistingId() throws SQLException { + checkRecordedIp(true, false); + } + + // A fresh ID has no recorded IP yet + @Test + public void missingIdHasNoRecordedIp() throws SQLException { + checkRecordedIp(false, false); + } + + // A broken lookup must not let a possible clone continue + @Test + public void recordedIpLookupFailureStopsStartup() throws SQLException { + checkRecordedIp(false, true); + } + + private void checkRecordedIp(boolean exists, boolean fail) throws SQLException { + TransactionLegacy transaction = mock(TransactionLegacy.class); + PreparedStatement statement = mock(PreparedStatement.class); + try (MockedStatic transactions = mockStatic(TransactionLegacy.class)) { + transactions.when(() -> TransactionLegacy.open("CheckManagementServerIdentity")).thenReturn(transaction); + when(transaction.prepareStatement("SELECT service_ip FROM mshost WHERE msid = ?")).thenReturn(statement); + if (fail) { + when(statement.executeQuery()).thenThrow(new SQLException("Unavailable")); + assertThrows(CloudRuntimeException.class, () -> new ManagementServerIdProviderImpl().findServiceIp(111L)); + } else { + when(statement.executeQuery()).thenReturn(records); + when(records.next()).thenReturn(exists); + if (exists) { + when(records.getString("service_ip")).thenReturn(" 192.0.2.1 "); + assertEquals("192.0.2.1", new ManagementServerIdProviderImpl().findServiceIp(111L).get()); + } else { + assertFalse(new ManagementServerIdProviderImpl().findServiceIp(111L).isPresent()); + } + } + verify(statement).setLong(1, 111L); + verify(statement).close(); + verify(transaction).close(); + } + } + // Make sure the ID helper can discover the real database lookup @Test public void databaseProviderIsDiscoverable() { diff --git a/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java b/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java index 82730683e46a..89f39718e9c6 100644 --- a/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java +++ b/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java @@ -25,6 +25,12 @@ import static org.mockito.Mockito.when; import org.apache.cloudstack.utils.identity.ManagementServerNode; +import java.util.Properties; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import com.cloud.utils.db.DbProperties; +import com.cloud.utils.db.TransactionLegacy; import org.junit.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -60,16 +66,57 @@ public void springReportsIdentityFailureBeforeStartingConsumer() { checkSpringStartup(true); } + // A copied explicit ID must stop startup before the lock controller runs + @Test + public void springRejectsCopiedIdBeforeFirstConsumer() { + checkSpringStartup(false, "192.0.2.1", null, true); + } + + // Confirming the recorded old IP lets the same server keep its ID + @Test + public void springAllowsConfirmedIpMove() { + checkSpringStartup(false, "192.0.2.1", "192.0.2.1", false); + } + + // Confirming an unrelated IP must not bypass the conflict check + @Test + public void springRejectsWrongIpConfirmation() { + checkSpringStartup(false, "192.0.2.1", "192.0.2.3", true); + } + private void checkSpringStartup(boolean invalid) { + checkSpringStartup(invalid, null, null, invalid); + } + + private void checkSpringStartup(boolean invalid, String recordedIp, String confirmation, boolean expectFailure) { Object previousId = ReflectionTestUtils.getField(ManagementServerNode.class, "s_nodeId"); String previousSetting = System.getProperty("management.server.id"); - try (MockedStatic locks = mockStatic(Merovingian2.class); + String previousIp = System.getProperty("management.server.id.previous.ip"); + Properties properties = new Properties(); + properties.setProperty("cluster.node.IP", "192.0.2.2"); + TransactionLegacy transaction = mock(TransactionLegacy.class); + PreparedStatement statement = mock(PreparedStatement.class); + ResultSet records = mock(ResultSet.class); + try (MockedStatic db = mockStatic(DbProperties.class); + MockedStatic transactions = mockStatic(TransactionLegacy.class); + MockedStatic locks = mockStatic(Merovingian2.class); GenericApplicationContext context = new GenericApplicationContext()) { + db.when(DbProperties::getDbProperties).thenReturn(properties); + transactions.when(() -> TransactionLegacy.open("CheckManagementServerIdentity")).thenReturn(transaction); + when(transaction.prepareStatement("SELECT service_ip FROM mshost WHERE msid = ?")).thenReturn(statement); + when(statement.executeQuery()).thenReturn(records); + when(records.next()).thenReturn(recordedIp != null); + when(records.getString("service_ip")).thenReturn(recordedIp); ReflectionTestUtils.setField(ManagementServerNode.class, "s_nodeId", null); System.setProperty("management.server.id", invalid ? "invalid" : "123"); + if (confirmation == null) { + System.clearProperty("management.server.id.previous.ip"); + } else { + System.setProperty("management.server.id.previous.ip", confirmation); + } new XmlBeanDefinitionReader(context).loadBeanDefinitions( "classpath:META-INF/cloudstack/system/spring-server-system-context.xml"); - if (invalid) { + if (expectFailure) { assertThrows(BeanCreationException.class, context::refresh); locks.verifyNoInteractions(); } else { @@ -77,8 +124,15 @@ private void checkSpringStartup(boolean invalid) { assertEquals(123L, ManagementServerNode.getManagementServerId()); locks.verify(() -> Merovingian2.createLockController(123L)); } + } catch (SQLException e) { + throw new AssertionError(e); } finally { ReflectionTestUtils.setField(ManagementServerNode.class, "s_nodeId", previousId); + if (previousIp == null) { + System.clearProperty("management.server.id.previous.ip"); + } else { + System.setProperty("management.server.id.previous.ip", previousIp); + } if (previousSetting == null) { System.clearProperty("management.server.id"); } else { diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java index 81244272d6e1..ee28c8afabc8 100644 --- a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java @@ -27,9 +27,12 @@ import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; +import java.security.SecureRandom; +import java.util.Optional; import java.util.OptionalLong; import java.util.ServiceLoader; import java.util.function.LongSupplier; +import java.util.function.LongConsumer; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.MacAddress; @@ -48,7 +51,10 @@ static long get() { // Use the ID from management.server.id if it is set // Otherwise, read the saved ID from the file at path // If the file does not exist, look for the old ID in the database first - return load(path, System.getProperty("management.server.id"), ManagementServerId::initialId); + return load(path, System.getProperty("management.server.id"), ManagementServerId::initialId, + id -> validate(id, database(), System.getProperty("management.server.id.previous.ip")), + System.getProperty("management.server.id.reset.from"), + () -> freshId(database(), new SecureRandom()::nextLong)); } catch (IOException | IllegalArgumentException e) { // Stop with a clear error instead of silently choosing a different identity throw new CloudRuntimeException("Unable to load the management server ID from " + path, e); @@ -57,16 +63,55 @@ static long get() { // Recover the old server ID before asking a network card for a new one private static long initialId() { - ManagementServerIdProvider provider = ServiceLoader.load(ManagementServerIdProvider.class) - .findFirst().orElseThrow(() -> new CloudRuntimeException("Management server ID database lookup is unavailable")); + ManagementServerIdProvider provider = database(); OptionalLong existingId = provider.findExistingId(); return existingId.isPresent() ? existingId.getAsLong() : MacAddress.getMacAddress().toLong(); } + private static ManagementServerIdProvider database() { + return ServiceLoader.load(ManagementServerIdProvider.class).findFirst() + .orElseThrow(() -> new CloudRuntimeException("Management server ID database lookup is unavailable")); + } + + // A different recorded IP needs an explicit choice before startup can continue + static void validate(long id, ManagementServerIdProvider provider, String previousIp) { + Optional recordedIp = provider.findServiceIp(id); + if (recordedIp.isPresent() && !recordedIp.get().equals(provider.getServiceIp()) + && !recordedIp.get().equals(previousIp)) { + throw new CloudRuntimeException("Management server ID " + id + " is recorded at " + recordedIp.get() + + " but this server uses " + provider.getServiceIp() + ". Startup stopped before registration. " + + "For a new cloned server with a copied ID file, set -Dmanagement.server.id.reset.from=" + id + + ". For the same server moved to a new IP, stop the old instance and set " + + "-Dmanagement.server.id.previous.ip=" + recordedIp.get() + ". See INSTALL.md"); + } + } + + // Give a confirmed clone a fresh ID that is not already in the database + static long freshId(ManagementServerIdProvider provider, LongSupplier random) { + for (int attempt = 0; attempt < 16; attempt++) { + long id = random.getAsLong() & Long.MAX_VALUE; + if (id > 0 && !provider.findServiceIp(id).isPresent()) { + return id; + } + } + throw new CloudRuntimeException("Unable to choose an unused management server ID"); + } + static long load(Path path, String configuredId, LongSupplier initialId) throws IOException { - // An operator-provided ID takes priority without overwriting the saved file + return load(path, configuredId, initialId, id -> { }, null, initialId); + } + + static long load(Path path, String configuredId, LongSupplier initialId, LongConsumer validate, + String resetFrom, LongSupplier newId) throws IOException { + // A reset names the copied ID so leaving the setting in place cannot reset it again + Long copiedId = resetFrom == null ? null : parse(resetFrom); if (configuredId != null) { - return parse(configuredId); + if (copiedId != null) { + throw new IllegalArgumentException("Remove management.server.id before using management.server.id.reset.from"); + } + long id = parse(configuredId); + validate.accept(id); + return id; } // Ensure the directory exists, then lock the neighboring .lock file so @@ -81,29 +126,49 @@ static long load(Path path, String configuredId, LongSupplier initialId) throws if (Files.size(path) > 64) { throw new IllegalArgumentException("Invalid management server ID file"); } - return parse(new String(Files.readAllBytes(path), StandardCharsets.UTF_8)); + long savedId = parse(new String(Files.readAllBytes(path), StandardCharsets.UTF_8)); + if (copiedId == null || copiedId.longValue() != savedId) { + validate.accept(savedId); + return savedId; + } + // Only an explicit reset may replace the copied ID + long replacement = parse(Long.toString(newId.getAsLong())); + if (replacement == savedId) { + throw new IllegalArgumentException("A cloned server must receive a different ID"); + } + validate.accept(replacement); + save(path, replacement); + return replacement; + } + if (copiedId != null) { + throw new IllegalArgumentException("management.server.id.reset.from requires an existing copied ID file"); } // With no saved file, recover the old ID or create one for a new server long id = parse(Long.toString(initialId.getAsLong())); - // Write in the same directory so the completed file can be renamed atomically - Path temporary = Files.createTempFile(path.toAbsolutePath().getParent(), "management-server-id-", ".tmp"); - try { - try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) { - ByteBuffer buffer = StandardCharsets.UTF_8.encode(id + "\n"); - while (buffer.hasRemaining()) { - channel.write(buffer); - } - // Flush the complete ID to storage before publishing it - channel.force(true); + validate.accept(id); + save(path, id); + return id; + } + } + + private static void save(Path path, long id) throws IOException { + // Write in the same directory so the completed file can be renamed atomically + Path temporary = Files.createTempFile(path.toAbsolutePath().getParent(), "management-server-id-", ".tmp"); + try { + try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) { + ByteBuffer buffer = StandardCharsets.UTF_8.encode(id + "\n"); + while (buffer.hasRemaining()) { + channel.write(buffer); } - // Make the completed file appear under its final name in one operation - Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE); - } finally { - // Clean up after a failed save; a successful move already removed this name - Files.deleteIfExists(temporary); + // Flush the complete ID to storage before publishing it + channel.force(true); } - return id; + // Make the completed file appear under its final name in one operation + Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } finally { + // Clean up after a failed save; a successful move already removed this name + Files.deleteIfExists(temporary); } } diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerIdProvider.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerIdProvider.java index 065e725578a2..1892eded9545 100644 --- a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerIdProvider.java +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerIdProvider.java @@ -18,8 +18,14 @@ package org.apache.cloudstack.utils.identity; import java.util.OptionalLong; +import java.util.Optional; // Lets the database module find an old ID without making utils depend on it public interface ManagementServerIdProvider { OptionalLong findExistingId(); + + // Find the IP already recorded for an ID, including old removed records + Optional findServiceIp(long id); + + String getServiceIp(); } diff --git a/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java index a809ec479b2a..c552cd8477af 100644 --- a/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java +++ b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java @@ -176,7 +176,7 @@ public void usesJvmSettingsAndReportsInvalidStorage() throws IOException { String previousFile = System.getProperty("management.server.id.file"); String previousId = System.getProperty("management.server.id"); Path path = folder.newFile("id").toPath(); - try { + try (ProviderMock lookup = new ProviderMock()) { System.setProperty("management.server.id.file", path.toString()); System.clearProperty("management.server.id"); Files.writeString(path, "42\n", StandardCharsets.UTF_8); @@ -251,6 +251,176 @@ private void checkDatabaseRecovery(OptionalLong recovered, boolean fail) throws } } + // Keep the ID when the database already records this server IP + @Test + public void matchingIpIsAllowed() { + ManagementServerId.validate(111L, provider("192.0.2.1", "192.0.2.1"), null); + } + + // Stop a possible clone and tell the admin the two choices + @Test + public void differentIpRequiresExplicitChoice() { + CloudRuntimeException error = assertThrows(CloudRuntimeException.class, + () -> ManagementServerId.validate(111L, provider("192.0.2.1", "192.0.2.2"), null)); + assertTrue(error.getMessage().contains("192.0.2.1")); + assertTrue(error.getMessage().contains("192.0.2.2")); + assertTrue(error.getMessage().contains("reset.from=111")); + assertTrue(error.getMessage().contains("previous.ip=192.0.2.1")); + } + + // The original server may keep its ID after confirming its recorded old IP + @Test + public void confirmedIpMoveKeepsIdentity() { + ManagementServerId.validate(111L, provider("192.0.2.1", "192.0.2.2"), "192.0.2.1"); + assertThrows(CloudRuntimeException.class, + () -> ManagementServerId.validate(111L, provider("192.0.2.1", "192.0.2.2"), "192.0.2.3")); + } + + // An ID that has not been registered yet is allowed + @Test + public void unregisteredIdIsAllowed() { + ManagementServerId.validate(222L, provider("192.0.2.1", "192.0.2.2"), null); + } + + // A rejected clone must keep the copied file untouched + @Test + public void rejectedCloneDoesNotChangeSavedId() throws IOException { + Path path = folder.newFile("copied-id").toPath(); + Files.writeString(path, "111\n"); + assertThrows(CloudRuntimeException.class, () -> ManagementServerId.load(path, null, unexpectedLookup(), + id -> ManagementServerId.validate(id, provider("192.0.2.1", "192.0.2.2"), null), null, unexpectedLookup())); + assertEquals("111\n", Files.readString(path)); + } + + // A conflicting first ID must not create a permanent file + @Test + public void rejectedInitialIdDoesNotCreateFile() { + assertThrows(CloudRuntimeException.class, () -> ManagementServerId.load(idFile(), null, () -> 111L, + id -> ManagementServerId.validate(id, provider("192.0.2.1", "192.0.2.2"), null), null, unexpectedLookup())); + assertFalse(Files.exists(idFile())); + } + + // Replace the copied ID once and keep the replacement on later starts + @Test + public void cloneResetIsPersistentAndRepeatSafe() throws IOException { + Path path = folder.newFile("copied-id").toPath(); + Files.writeString(path, "111\n"); + ManagementServerIdProvider lookup = provider("192.0.2.1", "192.0.2.2"); + assertEquals(222L, ManagementServerId.load(path, null, unexpectedLookup(), + id -> ManagementServerId.validate(id, lookup, null), "111", () -> 222L)); + assertEquals("222\n", Files.readString(path)); + assertEquals(222L, ManagementServerId.load(path, null, unexpectedLookup(), + id -> ManagementServerId.validate(id, lookup, null), "111", unexpectedLookup())); + } + + // A reset needs a copied file and must not compete with an explicit ID + @Test + public void rejectsInvalidResetRequests() { + assertThrows(IllegalArgumentException.class, () -> ManagementServerId.load(idFile(), null, + unexpectedLookup(), id -> { }, "111", unexpectedLookup())); + assertThrows(IllegalArgumentException.class, () -> ManagementServerId.load(idFile(), "123", + unexpectedLookup(), id -> { }, "111", unexpectedLookup())); + assertThrows(IllegalArgumentException.class, () -> ManagementServerId.load(idFile(), null, + unexpectedLookup(), id -> { }, "bad", unexpectedLookup())); + assertFalse(Files.exists(idFile())); + } + + // A bad replacement must leave the old file unchanged + @Test + public void rejectedReplacementKeepsOldFile() throws IOException { + Path path = folder.newFile("copied-id").toPath(); + Files.writeString(path, "111\n"); + assertThrows(IllegalArgumentException.class, () -> ManagementServerId.load(path, null, + unexpectedLookup(), id -> { }, "111", () -> 111L)); + assertThrows(CloudRuntimeException.class, () -> ManagementServerId.load(path, null, + unexpectedLookup(), id -> { throw new CloudRuntimeException("Lookup failed"); }, "111", () -> 222L)); + assertEquals("111\n", Files.readString(path)); + } + + // A failed replacement write must preserve the original ID file + @Test + public void failedResetWriteKeepsOldFile() throws IOException { + Path path = folder.newFile("copied-id").toPath(); + Files.writeString(path, "111\n"); + try (MockedStatic channels = Mockito.mockStatic(FileChannel.class, Mockito.CALLS_REAL_METHODS)) { + channels.when(() -> FileChannel.open(Mockito.any(Path.class), Mockito.eq(java.nio.file.StandardOpenOption.WRITE))) + .thenThrow(new IOException("Write failed")); + assertThrows(IOException.class, () -> ManagementServerId.load(path, null, + unexpectedLookup(), id -> { }, "111", () -> 222L)); + } + assertEquals("111\n", Files.readString(path)); + assertEquals(222L, ManagementServerId.load(path, null, unexpectedLookup(), id -> { }, "111", () -> 222L)); + } + + // Skip zero and IDs that are already recorded in the database + @Test + public void choosesUnusedPositiveCloneId() { + ManagementServerIdProvider lookup = provider("192.0.2.1", "192.0.2.2"); + java.util.Iterator values = List.of(0L, 111L, 222L).iterator(); + assertEquals(222L, ManagementServerId.freshId(lookup, () -> values.next())); + assertThrows(CloudRuntimeException.class, () -> ManagementServerId.freshId(lookup, () -> 111L)); + } + + // The real settings must keep a moved server ID or reset a copied ID only once + @Test + public void startupSettingsHandleIpMoveAndCloneReset() throws IOException { + String oldFile = System.getProperty("management.server.id.file"); + String oldId = System.getProperty("management.server.id"); + String oldIp = System.getProperty("management.server.id.previous.ip"); + String oldReset = System.getProperty("management.server.id.reset.from"); + Path path = folder.newFile("copied-id").toPath(); + Files.writeString(path, "111\n"); + try (ProviderMock lookup = new ProviderMock()) { + Mockito.when(lookup.provider.findServiceIp(111L)).thenReturn(Optional.of("192.0.2.1")); + Mockito.when(lookup.provider.getServiceIp()).thenReturn("192.0.2.2"); + System.setProperty("management.server.id.file", path.toString()); + System.clearProperty("management.server.id"); + System.clearProperty("management.server.id.previous.ip"); + System.clearProperty("management.server.id.reset.from"); + assertThrows(CloudRuntimeException.class, ManagementServerId::get); + assertEquals("111\n", Files.readString(path)); + System.setProperty("management.server.id.previous.ip", "192.0.2.1"); + assertEquals(111L, ManagementServerId.get()); + System.clearProperty("management.server.id.previous.ip"); + System.setProperty("management.server.id.reset.from", "111"); + long replacement = ManagementServerId.get(); + assertTrue(replacement > 0 && replacement != 111L); + assertEquals(Long.toString(replacement), Files.readString(path).trim()); + assertEquals(replacement, ManagementServerId.get()); + } finally { + restoreProperty("management.server.id.file", oldFile); + restoreProperty("management.server.id", oldId); + restoreProperty("management.server.id.previous.ip", oldIp); + restoreProperty("management.server.id.reset.from", oldReset); + } + } + + private ManagementServerIdProvider provider(String recordedIp, String currentIp) { + ManagementServerIdProvider lookup = Mockito.mock(ManagementServerIdProvider.class); + Mockito.when(lookup.findServiceIp(111L)).thenReturn(Optional.of(recordedIp)); + Mockito.when(lookup.getServiceIp()).thenReturn(currentIp); + return lookup; + } + + // Supply a fake database lookup without opening a real database connection + private static class ProviderMock implements AutoCloseable { + final ManagementServerIdProvider provider = Mockito.mock(ManagementServerIdProvider.class); + final MockedStatic services; + + @SuppressWarnings("unchecked") + ProviderMock() { + ServiceLoader loader = Mockito.mock(ServiceLoader.class); + Mockito.when(loader.findFirst()).thenReturn(Optional.of(provider)); + services = Mockito.mockStatic(ServiceLoader.class); + services.when(() -> ServiceLoader.load(ManagementServerIdProvider.class)).thenReturn(loader); + } + + @Override + public void close() { + services.close(); + } + } + // Three programs using the same file must all get the same ID @Test public void concurrentProcessesUseTheSameId() throws Exception { From c93ac6cbfd8b29b6a79735624453de05d3bd9e66 Mon Sep 17 00:00:00 2001 From: Mashrfee Aryan Date: Thu, 3 Dec 2026 09:23:29 -0600 Subject: [PATCH 10/12] Mark stale management server records as removed --- INSTALL.md | 14 ++ PendingReleaseNotes | 6 +- .../com/cloud/cluster/ClusterManagerImpl.java | 8 ++ .../cluster/dao/ManagementServerHostDao.java | 3 + .../dao/ManagementServerHostDaoImpl.java | 30 ++++- .../cloud/cluster/ClusterManagerImplTest.java | 120 +++++++++++++++++- .../dao/ManagementServerHostDaoImplTest.java | 54 ++++++++ 7 files changed, 227 insertions(+), 8 deletions(-) diff --git a/INSTALL.md b/INSTALL.md index 7e2b9d58642a..a9d0e03b94d9 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -244,6 +244,20 @@ These are startup settings, not an interactive prompt. Do not reset the ID of the original server during an ordinary restart or upgrade. Keep the copied ID file until you make the choice; deleting it can trigger recovery from `mshost`. +### Old duplicate management server records + +Registration marks old duplicate records as removed when they have the same IP, +a different `msid`, state `Down`, and a heartbeat older than +`cluster.heartbeat.threshold`. A recent peer report saying a record is `Up` +also prevents cleanup. Records without a heartbeat time are left alone. + +The old rows stay in the database so existing references remain valid. Cleanup +also invalidates their old sessions so a delayed heartbeat cannot reactivate +them. The current server, other IPs, Up records, and maintenance records are not +removed. Registration and cleanup share one transaction; a cleanup failure stops +startup. The avoid list still protects a working Up address from duplicate +records that cannot safely be retired. + ## Notes If you will be using Xen as your hypervisor, please download [vhd-util](https://download.cloudstack.org/tools/vhd-util) diff --git a/PendingReleaseNotes b/PendingReleaseNotes index be0dea9c0f5c..fe54af6fa2ad 100644 --- a/PendingReleaseNotes +++ b/PendingReleaseNotes @@ -48,8 +48,10 @@ example.ver.1 > example.ver.2: * Management server startup rejects IDs recorded at a different IP until an operator confirms an IP move or requests a fresh ID for a cloned server. See INSTALL.md for the startup settings and detection limits. - * Old non-Up management server records no longer cause agents to avoid an IP - that also has an Up record. + * Registration now marks stale Down duplicate records for the same management + server IP as removed and invalidates their old sessions. Recent, active, and + maintenance records are preserved. The avoid list still keeps an Up address + usable when duplicate records cannot safely be removed. 4.22.0.0 > 4.22.0.1: * Disk-only instance snapshots for KVM UEFI VMs now include a sidecar copy of diff --git a/framework/cluster/src/main/java/com/cloud/cluster/ClusterManagerImpl.java b/framework/cluster/src/main/java/com/cloud/cluster/ClusterManagerImpl.java index 759948cb9c0c..62c36f0c77e5 100644 --- a/framework/cluster/src/main/java/com/cloud/cluster/ClusterManagerImpl.java +++ b/framework/cluster/src/main/java/com/cloud/cluster/ClusterManagerImpl.java @@ -1080,6 +1080,14 @@ public ManagementServerHostVO doInTransaction(final TransactionStatus status) { } } + // Retire old Down copies only after this server has registered successfully + // Keep registration and cleanup in the same transaction + Date cutoff = new Date(DateUtil.currentGMTTime().getTime() - HeartbeatThreshold.value()); + int retired = _mshostDao.removeStaleDuplicates(_msId, _clusterNodeIP, cutoff); + if (retired > 0) { + logger.info("Retired {} stale management server records for IP {}", retired, _clusterNodeIP); + } + return mshost; } }); diff --git a/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDao.java b/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDao.java index 6c8ffcac78b7..582057b59a26 100644 --- a/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDao.java +++ b/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDao.java @@ -51,6 +51,9 @@ public interface ManagementServerHostDao extends GenericDao listNonUpStateMsIPs(); + // Retire old Down records for the registering server without deleting their history + int removeStaleDuplicates(long currentMsid, String serviceIp, Date cutTime); + /** * Lists msids for which hosts are orphaned, i.e. msids that hosts refer as their owning ms whilst no mshost entry exists with those msids * diff --git a/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java b/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java index 99610747ab97..de684291e251 100644 --- a/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java +++ b/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java @@ -45,6 +45,11 @@ public class ManagementServerHostDaoImpl extends GenericDaoBase implements ManagementServerHostDao { + static final String REMOVE_STALE_DUPLICATES = "UPDATE mshost SET removed = ?, runid = 0 " + + "WHERE service_ip = ? AND msid <> ? AND state = 'Down' AND removed IS NULL " + + "AND last_update < ? AND NOT EXISTS (SELECT 1 FROM mshost_peer p " + + "WHERE p.peer_mshost = mshost.id AND p.peer_state = 'Up' AND p.last_update >= ?)"; + private final SearchBuilder MsIdSearch; private final SearchBuilder ActiveSearch; private final SearchBuilder InactiveSearch; @@ -263,9 +268,28 @@ public List listBy(ManagementServerHost.State... states) return listBy(sc); } - // The saved ID stops future ID changes but leaves old records behind - // This method handles duplicate records that already exist - // Old Down records must not make agents skip an address that also has an Up record + // Clean up duplicates left by the old bug when this server registers + @Override + @DB + public int removeStaleDuplicates(long currentMsid, String serviceIp, Date cutTime) { + TransactionLegacy transaction = TransactionLegacy.currentTxn(); + try (PreparedStatement statement = transaction.prepareStatement(REMOVE_STALE_DUPLICATES)) { + String cutoff = DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime); + statement.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), DateUtil.currentGMTTime())); + statement.setString(2, serviceIp); + statement.setLong(3, currentMsid); + statement.setString(4, cutoff); + statement.setString(5, cutoff); + // The same update rechecks activity and invalidates the old heartbeat session + // Keep the rows themselves so existing references still point to a valid record + return statement.executeUpdate(); + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to retire stale management server records for " + serviceIp, e); + } + } + + // Registration removes stale Down duplicates but leaves recent and maintenance records alone + // Keep an Up address usable even when another record for it cannot be removed safely @Override public List listNonUpStateMsIPs() { Set upIPs = new HashSet<>(); diff --git a/framework/cluster/src/test/java/com/cloud/cluster/ClusterManagerImplTest.java b/framework/cluster/src/test/java/com/cloud/cluster/ClusterManagerImplTest.java index 0f3aca0e8a19..6b8b58cb14e0 100644 --- a/framework/cluster/src/test/java/com/cloud/cluster/ClusterManagerImplTest.java +++ b/framework/cluster/src/test/java/com/cloud/cluster/ClusterManagerImplTest.java @@ -17,17 +17,31 @@ package com.cloud.cluster; -import org.mockito.Mockito; +import java.util.Date; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; +import org.apache.cloudstack.management.ManagementServerHost.State; +import org.apache.cloudstack.utils.identity.ManagementServerNode; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; -import org.apache.cloudstack.utils.identity.ManagementServerNode; -import org.mockito.MockedStatic; import org.mockito.InjectMocks; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.InOrder; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.util.ReflectionTestUtils; +import com.cloud.cluster.dao.ManagementServerHostDao; +import com.cloud.cluster.dao.ManagementServerHostPeerDao; +import com.cloud.utils.DateUtil; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallback; +import com.cloud.utils.db.TransactionStatus; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.net.NetUtils; + @RunWith(MockitoJUnitRunner.class) public class ClusterManagerImplTest { @InjectMocks @@ -47,4 +61,104 @@ public void testGetSelfNodeIP() { ReflectionTestUtils.setField(clusterManager, "_clusterNodeIP", ip); Assert.assertEquals(ip, clusterManager.getSelfNodeIP()); } + // Clean old copies after a new registration and before heartbeat jobs start + @Test + public void newRegistrationCleansStaleDuplicates() { + checkRegistration(false, false, false); + } + + // Updating the saved ID record must also clean old copies + @Test + public void existingRegistrationCleansStaleDuplicates() { + checkRegistration(true, false, false); + } + + // A failed new registration must never remove other server records + @Test + public void failedNewRegistrationSkipsCleanup() { + checkRegistration(false, true, false); + } + + // A failed update must never remove other server records + @Test + public void failedRegistrationUpdateSkipsCleanup() { + checkRegistration(true, true, false); + } + + // Cleanup failure must stop startup before heartbeat jobs are started + @Test + public void failedCleanupStopsStartup() { + checkRegistration(true, false, true); + } + + @SuppressWarnings("unchecked") + private void checkRegistration(boolean existing, boolean registrationFails, boolean cleanupFails) { + ManagementServerHostDao dao = Mockito.mock(ManagementServerHostDao.class); + ManagementServerHostPeerDao peers = Mockito.mock(ManagementServerHostPeerDao.class); + ClusterServiceAdapter adapter = Mockito.mock(ClusterServiceAdapter.class); + ScheduledExecutorService heartbeat = Mockito.mock(ScheduledExecutorService.class); + ExecutorService notifications = Mockito.mock(ExecutorService.class); + ReflectionTestUtils.setField(clusterManager, "_mshostDao", dao); + ReflectionTestUtils.setField(clusterManager, "_mshostPeerDao", peers); + ReflectionTestUtils.setField(clusterManager, "_currentServiceAdapter", adapter); + ReflectionTestUtils.setField(clusterManager, "_heartbeatScheduler", heartbeat); + ReflectionTestUtils.setField(clusterManager, "_notificationExecutor", notifications); + ReflectionTestUtils.setField(clusterManager, "_clusterNodeIP", "192.0.2.1"); + Date now = new Date(1000000); + Date cutoff = new Date(now.getTime() - ClusterManager.HeartbeatThreshold.value()); + ManagementServerHostVO host = new ManagementServerHostVO(123L, 1L, "192.0.2.1", 0, now); + host.setId(7L); + host.setState(State.Down); + Mockito.when(dao.findByMsid(123L)).thenReturn(existing ? host : null); + if (registrationFails) { + if (existing) { + Mockito.doThrow(new CloudRuntimeException("Registration failed")).when(dao).update(Mockito.eq(7L), + Mockito.anyLong(), Mockito.anyString(), Mockito.nullable(String.class), Mockito.eq("192.0.2.1"), + Mockito.anyInt(), Mockito.eq(now), Mockito.eq(State.Up)); + } else { + Mockito.when(dao.persist(Mockito.any(ManagementServerHostVO.class))) + .thenThrow(new CloudRuntimeException("Registration failed")); + } + } else if (!existing) { + Mockito.when(dao.persist(Mockito.any(ManagementServerHostVO.class))).thenAnswer(invocation -> { + ManagementServerHostVO saved = invocation.getArgument(0); + saved.setId(7L); + return saved; + }); + } + if (cleanupFails) { + Mockito.when(dao.removeStaleDuplicates(123L, "192.0.2.1", cutoff)) + .thenThrow(new CloudRuntimeException("Cleanup failed")); + } + try (MockedStatic transactions = Mockito.mockStatic(Transaction.class); + MockedStatic dates = Mockito.mockStatic(DateUtil.class); + MockedStatic network = Mockito.mockStatic(NetUtils.class)) { + dates.when(DateUtil::currentGMTTime).thenReturn(now); + network.when(NetUtils::getCanonicalHostName).thenReturn("test-management-server"); + transactions.when(() -> Transaction.execute(Mockito.any(TransactionCallback.class))) + .thenAnswer(invocation -> ((TransactionCallback) invocation.getArgument(0)) + .doInTransaction(Mockito.mock(TransactionStatus.class))); + if (registrationFails || cleanupFails) { + Assert.assertThrows(CloudRuntimeException.class, clusterManager::start); + Mockito.verifyNoInteractions(heartbeat, notifications, peers); + if (registrationFails) { + Mockito.verify(dao, Mockito.never()).removeStaleDuplicates(Mockito.anyLong(), Mockito.anyString(), Mockito.any(Date.class)); + } + } else { + Assert.assertTrue(clusterManager.start()); + InOrder order = Mockito.inOrder(dao, peers, heartbeat); + if (existing) { + order.verify(dao).update(Mockito.eq(7L), Mockito.anyLong(), Mockito.anyString(), Mockito.nullable(String.class), + Mockito.eq("192.0.2.1"), Mockito.anyInt(), Mockito.eq(now), Mockito.eq(State.Up)); + } else { + order.verify(dao).persist(Mockito.any(ManagementServerHostVO.class)); + } + order.verify(dao).removeStaleDuplicates(123L, "192.0.2.1", cutoff); + order.verify(peers).clearPeerInfo(7L); + order.verify(heartbeat).scheduleAtFixedRate(Mockito.any(Runnable.class), Mockito.anyLong(), Mockito.anyLong(), + Mockito.eq(java.util.concurrent.TimeUnit.MILLISECONDS)); + } + } + } + } diff --git a/framework/cluster/src/test/java/com/cloud/cluster/dao/ManagementServerHostDaoImplTest.java b/framework/cluster/src/test/java/com/cloud/cluster/dao/ManagementServerHostDaoImplTest.java index 7a2ea02877e1..b928accdf6d9 100644 --- a/framework/cluster/src/test/java/com/cloud/cluster/dao/ManagementServerHostDaoImplTest.java +++ b/framework/cluster/src/test/java/com/cloud/cluster/dao/ManagementServerHostDaoImplTest.java @@ -20,8 +20,21 @@ import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.verify; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.junit.Assert.assertThrows; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Date; import java.util.Arrays; +import org.mockito.MockedStatic; +import com.cloud.utils.db.TransactionLegacy; +import com.cloud.utils.exception.CloudRuntimeException; import java.util.Collections; import java.util.List; @@ -62,6 +75,47 @@ public void emptyServerListHasNoAvoidedAddresses() { assertAvoided(Collections.emptyList()); } + // Use the current ID, IP and heartbeat cutoff in the cleanup query + @Test + public void cleanupBindsServerIdentityAndHeartbeatCutoff() throws SQLException { + checkCleanup(4, false); + } + + // Starting again with no old rows is harmless + @Test + public void cleanupWithNoMatchesReturnsZero() throws SQLException { + checkCleanup(0, false); + } + + // A failed cleanup must reach the registration transaction instead of being hidden + @Test + public void cleanupReportsDatabaseFailure() throws SQLException { + checkCleanup(0, true); + } + + private void checkCleanup(int removed, boolean fail) throws SQLException { + TransactionLegacy transaction = mock(TransactionLegacy.class); + PreparedStatement statement = mock(PreparedStatement.class); + try (MockedStatic transactions = mockStatic(TransactionLegacy.class)) { + transactions.when(TransactionLegacy::currentTxn).thenReturn(transaction); + when(transaction.prepareStatement(ManagementServerHostDaoImpl.REMOVE_STALE_DUPLICATES)).thenReturn(statement); + if (fail) { + when(statement.executeUpdate()).thenThrow(new SQLException("Unavailable")); + assertThrows(CloudRuntimeException.class, + () -> dao.removeStaleDuplicates(123L, "192.0.2.1", new Date(1000000))); + } else { + when(statement.executeUpdate()).thenReturn(removed); + assertEquals(removed, dao.removeStaleDuplicates(123L, "192.0.2.1", new Date(1000000))); + } + verify(statement).setString(eq(1), anyString()); + verify(statement).setString(2, "192.0.2.1"); + verify(statement).setLong(3, 123L); + verify(statement).setString(4, "1970-01-01 00:16:40"); + verify(statement).setString(5, "1970-01-01 00:16:40"); + verify(statement).close(); + } + } + // Run the avoid-list code with pretend records and check the returned addresses private void assertAvoided(List hosts, String... expected) { doReturn(hosts).when(dao).listAll(); From 494fdecfb4504d22317055c8f187fbce12671250 Mon Sep 17 00:00:00 2001 From: Mashrfee Aryan Date: Thu, 3 Dec 2026 11:20:51 -0600 Subject: [PATCH 11/12] Improve management server ID comments --- .../dao/ManagementServerHostDaoImpl.java | 11 ++++----- .../network/NetworkUsageManagerImpl.java | 1 - .../VirtualNetworkApplianceManagerImpl.java | 4 +++- .../cloud/server/ManagementServerImpl.java | 4 +++- .../java/com/cloud/server/StatsCollector.java | 1 - .../utils/identity/ManagementServerId.java | 23 ++++++++----------- 6 files changed, 19 insertions(+), 25 deletions(-) diff --git a/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java b/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java index de684291e251..12e4b2e08c2d 100644 --- a/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java +++ b/framework/cluster/src/main/java/com/cloud/cluster/dao/ManagementServerHostDaoImpl.java @@ -288,25 +288,22 @@ public int removeStaleDuplicates(long currentMsid, String serviceIp, Date cutTim } } - // Registration removes stale Down duplicates but leaves recent and maintenance records alone - // Keep an Up address usable even when another record for it cannot be removed safely + /** + * Returns addresses that agents should skip. An Up record keeps its address usable + * even when an older record for that address is still present + */ @Override public List listNonUpStateMsIPs() { Set upIPs = new HashSet<>(); Set nonUpIPs = new LinkedHashSet<>(); - // Read server records that have not been removed for (ManagementServerHostVO host : listAll()) { if (State.Up.equals(host.getState())) { - // Collect addresses marked Up upIPs.add(host.getServiceIP()); } else { - // Collect addresses in other states nonUpIPs.add(host.getServiceIP()); } } - // Keep every Up address out of the avoid list nonUpIPs.removeAll(upIPs); - // Give agents the remaining addresses to skip return new ArrayList<>(nonUpIPs); } diff --git a/server/src/main/java/com/cloud/network/NetworkUsageManagerImpl.java b/server/src/main/java/com/cloud/network/NetworkUsageManagerImpl.java index fa669acac024..37bc183058cd 100644 --- a/server/src/main/java/com/cloud/network/NetworkUsageManagerImpl.java +++ b/server/src/main/java/com/cloud/network/NetworkUsageManagerImpl.java @@ -252,7 +252,6 @@ protected class DirectNetworkStatsListener implements Listener { private int _interval; - // Use the saved ID to check which traffic monitors this server is in charge of private final long mgmtSrvrId = ManagementServerNode.getManagementServerId(); protected DirectNetworkStatsListener(int interval) { diff --git a/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index b057d53f01b0..572311f33be9 100644 --- a/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -364,7 +364,6 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V private int _routerExtraPublicNics = 2; private int _usageAggregationRange = 1440; private String _usageTimeZone = "GMT"; - // Use the saved ID to find the routers this server is in charge of private final long mgmtSrvrId = ManagementServerNode.getManagementServerId(); private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5; // 5 seconds private boolean _dailyOrHourly = false; @@ -1815,6 +1814,9 @@ protected void runInContext() { } } + /** + * Gets alerts from running routers assigned to this management server ID + */ protected void getRouterAlerts() { try { final List routers = _routerDao.listByStateAndManagementServer(VirtualMachine.State.Running, mgmtSrvrId); diff --git a/server/src/main/java/com/cloud/server/ManagementServerImpl.java b/server/src/main/java/com/cloud/server/ManagementServerImpl.java index a417ff84a3a3..7b9ab5455c19 100644 --- a/server/src/main/java/com/cloud/server/ManagementServerImpl.java +++ b/server/src/main/java/com/cloud/server/ManagementServerImpl.java @@ -1197,7 +1197,9 @@ public DetailVO findDetail(final long hostId, final String name) { return _detailsDao.findDetail(hostId, name); } - // Return the persistent server ID shared by the other CloudStack components + /** + * Return the persistent server ID shared by the other CloudStack components + */ @Override public long getId() { return ManagementServerNode.getManagementServerId(); diff --git a/server/src/main/java/com/cloud/server/StatsCollector.java b/server/src/main/java/com/cloud/server/StatsCollector.java index ee606fb838f8..b224a7f1a2fb 100644 --- a/server/src/main/java/com/cloud/server/StatsCollector.java +++ b/server/src/main/java/com/cloud/server/StatsCollector.java @@ -390,7 +390,6 @@ public String toString() { private ScheduledExecutorService _diskStatsUpdateExecutor; private int _usageAggregationRange = 1440; private String _usageTimeZone = "GMT"; - // Use the saved ID to check which stats jobs this server should do private final long mgmtSrvrId = ManagementServerNode.getManagementServerId(); private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5; // 5 seconds private boolean _dailyOrHourly = false; diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java index ee28c8afabc8..6f016bb95985 100644 --- a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java @@ -37,31 +37,30 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.MacAddress; -// Keeps the management server ID the same across restarts +/** + * Keeps the management server ID the same across restarts + */ final class ManagementServerId { private ManagementServerId() { } - // Find the ID file and load the ID + /** + * Loads the configured or saved ID, or recovers the previous ID on first startup after an upgrade + */ static long get() { Path path = Paths.get(System.getProperty("management.server.id.file", Paths.get(System.getProperty("user.home"), ".cloudstack", "management-server.id").toString())); try { - // Use the ID from management.server.id if it is set - // Otherwise, read the saved ID from the file at path - // If the file does not exist, look for the old ID in the database first return load(path, System.getProperty("management.server.id"), ManagementServerId::initialId, id -> validate(id, database(), System.getProperty("management.server.id.previous.ip")), System.getProperty("management.server.id.reset.from"), () -> freshId(database(), new SecureRandom()::nextLong)); } catch (IOException | IllegalArgumentException e) { - // Stop with a clear error instead of silently choosing a different identity throw new CloudRuntimeException("Unable to load the management server ID from " + path, e); } } - // Recover the old server ID before asking a network card for a new one private static long initialId() { ManagementServerIdProvider provider = database(); OptionalLong existingId = provider.findExistingId(); @@ -73,7 +72,9 @@ private static ManagementServerIdProvider database() { .orElseThrow(() -> new CloudRuntimeException("Management server ID database lookup is unavailable")); } - // A different recorded IP needs an explicit choice before startup can continue + /** + * Requires explicit confirmation before reusing an ID recorded at a different IP + */ static void validate(long id, ManagementServerIdProvider provider, String previousIp) { Optional recordedIp = provider.findServiceIp(id); if (recordedIp.isPresent() && !recordedIp.get().equals(provider.getServiceIp()) @@ -86,7 +87,6 @@ static void validate(long id, ManagementServerIdProvider provider, String previo } } - // Give a confirmed clone a fresh ID that is not already in the database static long freshId(ManagementServerIdProvider provider, LongSupplier random) { for (int attempt = 0; attempt < 16; attempt++) { long id = random.getAsLong() & Long.MAX_VALUE; @@ -120,7 +120,6 @@ static long load(Path path, String configuredId, LongSupplier initialId, LongCon try (FileChannel lockChannel = FileChannel.open(path.resolveSibling(path.getFileName() + ".lock"), StandardOpenOption.CREATE, StandardOpenOption.WRITE); FileLock lock = lockChannel.lock()) { - // Reuse the saved ID without checking network interfaces again if (Files.exists(path)) { // An ID is a short number; reject an unexpectedly large file if (Files.size(path) > 64) { @@ -131,7 +130,6 @@ static long load(Path path, String configuredId, LongSupplier initialId, LongCon validate.accept(savedId); return savedId; } - // Only an explicit reset may replace the copied ID long replacement = parse(Long.toString(newId.getAsLong())); if (replacement == savedId) { throw new IllegalArgumentException("A cloned server must receive a different ID"); @@ -144,7 +142,6 @@ static long load(Path path, String configuredId, LongSupplier initialId, LongCon throw new IllegalArgumentException("management.server.id.reset.from requires an existing copied ID file"); } - // With no saved file, recover the old ID or create one for a new server long id = parse(Long.toString(initialId.getAsLong())); validate.accept(id); save(path, id); @@ -164,7 +161,6 @@ private static void save(Path path, long id) throws IOException { // Flush the complete ID to storage before publishing it channel.force(true); } - // Make the completed file appear under its final name in one operation Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } finally { // Clean up after a failed save; a successful move already removed this name @@ -172,7 +168,6 @@ private static void save(Path path, long id) throws IOException { } } - // Ignore surrounding whitespace and require a positive whole number that fits in a Java long private static long parse(String value) { long id = Long.parseLong(value.trim()); if (id <= 0) { From ddbcbf882d007114d024a8ff3af35f9536a4e406 Mon Sep 17 00:00:00 2001 From: Mashrfee Aryan Date: Thu, 3 Dec 2026 11:20:52 -0600 Subject: [PATCH 12/12] Explain why a copied server ID stops startup --- .../cloudstack/utils/identity/ManagementServerId.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java index 6f016bb95985..80829963a3ef 100644 --- a/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java @@ -80,10 +80,13 @@ static void validate(long id, ManagementServerIdProvider provider, String previo if (recordedIp.isPresent() && !recordedIp.get().equals(provider.getServiceIp()) && !recordedIp.get().equals(previousIp)) { throw new CloudRuntimeException("Management server ID " + id + " is recorded at " + recordedIp.get() - + " but this server uses " + provider.getServiceIp() + ". Startup stopped before registration. " - + "For a new cloned server with a copied ID file, set -Dmanagement.server.id.reset.from=" + id - + ". For the same server moved to a new IP, stop the old instance and set " - + "-Dmanagement.server.id.previous.ip=" + recordedIp.get() + ". See INSTALL.md"); + + ", but this server is configured for " + provider.getServiceIp() + ". " + + "CloudStack stopped to avoid using the same ID on two servers if this VM is a clone.\n\n" + + "For a new cloned server with a copied ID file, set\n" + + "-Dmanagement.server.id.reset.from=" + id + "\n\n" + + "For the same server moved to a new IP, stop the old instance and set\n" + + "-Dmanagement.server.id.previous.ip=" + recordedIp.get() + "\n" + + "See INSTALL.md."); } }