diff --git a/INSTALL.md b/INSTALL.md index 0619b97f21c1..a9d0e03b94d9 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -188,6 +188,76 @@ 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 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. + +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. + +### 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`. + +### 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 02d63811e36e..fe54af6fa2ad 100644 --- a/PendingReleaseNotes +++ b/PendingReleaseNotes @@ -40,6 +40,19 @@ 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 reuse a saved ID after restarts, so network interface + 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. + * 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 the active NVRAM state so revert operations restore both disk and firmware 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 ec943a9c26be..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 @@ -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; @@ -43,11 +45,15 @@ 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; private final SearchBuilder StateSearch; - protected GenericSearchBuilder NonUpStateMsSearch; @Override public void invalidateRunSession(long id, long runid) { @@ -229,11 +235,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 @@ -267,11 +268,43 @@ public List listBy(ManagementServerHost.State... states) return listBy(sc); } + // 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); + } + } + + /** + * 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() { - SearchCriteria sc = NonUpStateMsSearch.create(); - sc.addAnd("state", SearchCriteria.Op.NLIKE, State.Up); - return customSearch(sc, null); + Set upIPs = new HashSet<>(); + Set nonUpIPs = new LinkedHashSet<>(); + 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/ClusterManagerImplTest.java b/framework/cluster/src/test/java/com/cloud/cluster/ClusterManagerImplTest.java index 9b1854f73487..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,43 @@ package com.cloud.cluster; +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.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 - 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() { @@ -35,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 new file mode 100644 index 000000000000..b928accdf6d9 --- /dev/null +++ b/framework/cluster/src/test/java/com/cloud/cluster/dao/ManagementServerHostDaoImplTest.java @@ -0,0 +1,132 @@ +// 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 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; + +import org.apache.cloudstack.management.ManagementServerHost.State; +import org.junit.Test; + +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); + ManagementServerHostVO up = host("10.0.0.1", State.Up); + assertAvoided(Arrays.asList(down, up)); + 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()); + } + + // 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(); + 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); + host.setState(state); + return host; + } +} 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..7fbd367adcf2 --- /dev/null +++ b/framework/db/src/main/java/com/cloud/utils/db/ManagementServerIdProviderImpl.java @@ -0,0 +1,87 @@ +// 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 java.util.Optional; + +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 = getServiceIp(); + 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); + } + } + + @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(); + } + 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..f6af58f8cf5d --- /dev/null +++ b/framework/db/src/test/java/com/cloud/utils/db/ManagementServerIdRecoveryTest.java @@ -0,0 +1,186 @@ +// 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(); + } + } + + // 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() { + assertEquals(ManagementServerIdProviderImpl.class, + ServiceLoader.load(ManagementServerIdProvider.class).findFirst().get().getClass()); + } +} 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..572311f33be9 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; @@ -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 95e688b5d8cb..7b9ab5455c19 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; @@ -1198,9 +1197,12 @@ 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 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/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 new file mode 100644 index 000000000000..89f39718e9c6 --- /dev/null +++ b/server/src/test/java/com/cloud/server/ManagementServerIdentityTest.java @@ -0,0 +1,187 @@ +// 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.junit.Assert.assertThrows; +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 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; +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; + +// 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; + + // 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); + } + + // 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"); + 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 (expectFailure) { + assertThrows(BeanCreationException.class, context::refresh); + locks.verifyNoInteractions(); + } else { + context.refresh(); + 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 { + System.setProperty("management.server.id", previousSetting); + } + } + } + + // Return the saved ID even when the network card gives a different ID + @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()); + } + } + + // Still start the disk stats job when the saved ID says this server is in charge + @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); + + // Pretend the database says this server should do the job + 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 { + // Put the old stats collector back so other tests are not affected + ReflectionTestUtils.setField(StatsCollector.class, "s_instance", previous); + } + } +} 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/ManagementServerId.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java new file mode 100644 index 000000000000..80829963a3ef --- /dev/null +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerId.java @@ -0,0 +1,181 @@ +// 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.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; + +/** + * Keeps the management server ID the same across restarts + */ +final class ManagementServerId { + + private ManagementServerId() { + } + + /** + * 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 { + 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) { + throw new CloudRuntimeException("Unable to load the management server ID from " + path, e); + } + } + + private static long initialId() { + 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")); + } + + /** + * 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()) + && !recordedIp.get().equals(previousIp)) { + throw new CloudRuntimeException("Management server ID " + id + " is recorded at " + recordedIp.get() + + ", 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."); + } + } + + 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 { + 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) { + 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 + // 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()) { + 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"); + } + long savedId = parse(new String(Files.readAllBytes(path), StandardCharsets.UTF_8)); + if (copiedId == null || copiedId.longValue() != savedId) { + validate.accept(savedId); + return savedId; + } + 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"); + } + + long id = parse(Long.toString(initialId.getAsLong())); + 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); + } + // Flush the complete ID to storage before publishing it + channel.force(true); + } + 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); + } + } + + 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/ManagementServerIdProvider.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerIdProvider.java new file mode 100644 index 000000000000..1892eded9545 --- /dev/null +++ b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerIdProvider.java @@ -0,0 +1,31 @@ +// 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; +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/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java b/utils/src/main/java/org/apache/cloudstack/utils/identity/ManagementServerNode.java index 32989c3497c5..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 @@ -25,34 +25,47 @@ import com.cloud.utils.component.ComponentLifecycle; import com.cloud.utils.component.SystemIntegrityChecker; import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.MacAddress; +// Holds the management server ID and shares it with other CloudStack components public class ManagementServerNode extends AdapterBase implements SystemIntegrityChecker { - private static final long s_nodeId = MacAddress.getMacAddress().toLong(); + // 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() { setRunLevel(ComponentLifecycle.RUN_LEVEL_FRAMEWORK_BOOTSTRAP); } + // 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"); } } - public static long getManagementServerId() { + // Return the ID loaded by start without reading a file or the database + public static synchronized long getManagementServerId() { + if (s_nodeId == null) { + throw new CloudRuntimeException("Management server ID has not been initialized; start ManagementServerNode first"); + } return s_nodeId; } + // 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/ManagementServerIdTest.java b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java new file mode 100644 index 000000000000..c552cd8477af --- /dev/null +++ b/utils/src/test/java/org/apache/cloudstack/utils/identity/ManagementServerIdTest.java @@ -0,0 +1,463 @@ +// 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.ByteBuffer; +import java.nio.channels.FileChannel; +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.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; +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; +import com.cloud.utils.net.MacAddress; + +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(); + assertEquals(130014950130305L, ManagementServerId.load(path, null, () -> 130014950130305L)); + assertEquals(130014950130305L, ManagementServerId.load(path, null, () -> 42L)); + 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(); + ManagementServerId.load(path, null, () -> 42L); + assertEquals(123L, ManagementServerId.load(path, "123", unexpectedLookup())); + 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"}) { + assertThrows(IllegalArgumentException.class, + () -> ManagementServerId.load(idFile(), value, unexpectedLookup())); + } + 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(); + 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)); + } + } + + // Do not save a new ID if it is zero or negative + @Test + public void rejectsInvalidInitialIdsWithoutSavingThem() { + for (long value : new long[] {0L, -1L}) { + assertThrows(IllegalArgumentException.class, + () -> ManagementServerId.load(idFile(), null, () -> value)); + } + 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 -> { + 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)); + } + + // Allow spaces around a valid ID and accept the biggest allowed number + @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())); + } + + // 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"); + String previousId = System.getProperty("management.server.id"); + Path path = folder.newFile("id").toPath(); + 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); + 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); + } + } + + // 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); + } + } + + // 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 { + 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(); + } + } + } + + // 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); + } else { + System.setProperty(name, value); + } + } +} 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(); + } + } +}