Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions INSTALL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
13 changes: 13 additions & 0 deletions PendingReleaseNotes
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ public interface ManagementServerHostDao extends GenericDao<ManagementServerHost

List<String> 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
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;


Expand All @@ -35,19 +38,22 @@
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;
import com.cloud.utils.exception.CloudRuntimeException;

public class ManagementServerHostDaoImpl extends GenericDaoBase<ManagementServerHostVO, Long> 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<ManagementServerHostVO> MsIdSearch;
private final SearchBuilder<ManagementServerHostVO> ActiveSearch;
private final SearchBuilder<ManagementServerHostVO> InactiveSearch;
private final SearchBuilder<ManagementServerHostVO> StateSearch;
protected GenericSearchBuilder<ManagementServerHostVO, String> NonUpStateMsSearch;

@Override
public void invalidateRunSession(long id, long runid) {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -267,11 +268,43 @@ public List<ManagementServerHostVO> 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<String> listNonUpStateMsIPs() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MashrafeeAryan instead of skipping old down rows in the avoid list, can we just mark old rows with the same ip as removed when the ms registers? fixes the leftover rows too, like in #14448

SearchCriteria<String> sc = NonUpStateMsSearch.create();
sc.addAnd("state", SearchCriteria.Op.NLIKE, State.Up);
return customSearch(sc, null);
Set<String> upIPs = new HashSet<>();
Set<String> 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,148 @@

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<ManagementServerNode> node = Mockito.mockStatic(ManagementServerNode.class)) {
node.when(ManagementServerNode::getManagementServerId).thenReturn(123L);
return new ClusterManagerImpl();
}
}

@Test
public void testGetSelfNodeIP() {
String ip = "1.2.3.4";
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<Transaction> transactions = Mockito.mockStatic(Transaction.class);
MockedStatic<DateUtil> dates = Mockito.mockStatic(DateUtil.class);
MockedStatic<NetUtils> 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<ManagementServerHostVO>) 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));
}
}
}

}
Loading