Skip to content

Commit dd1abf8

Browse files
sureshanapartidhslove
authored andcommitted
Direct agents rebalance improvements with multiple management server nodes (apache#10674)
Sometimes hypervisor hosts (direct agents) stuck with Disconnect state during agent rebalancing activity across multiple management server nodes. This issue was noticed during frequent restart of the management server nodes in the cluster. When there are multiple management server nodes in a cluster, if one or more nodes are shutdown/start/restart, CloudStack will rebalance the hosts among the remaining nodes or move the nodes to the newly joined management server nodes. During the rebalancing period multiple operations could happen including: - DirectAgentScan at interval of configured direct.agent.scan.interval - AgentRebalanceScan to identify and schedule rebalance agents - TransferAgentScan to transfer the host from original owner to future owner **Current Rebalance behavior** 1. For hosts that have AgentAttache && not forForward but in Disconnect state, CloudStack simply ignore these hosts without trying to ping again or update the status of the host. 2. For hosts that have AgentAttache && forForward, CloudStack removes the agent but still try to loadDirectlyConnectedHost. **Improved Rebalance behavior** During DirectAgentScan: scanDirectAgentToLoad(), identify hosts that for self-managed hosts that are in Disconnect state (disconnected after pingtimeout). 1. For hosts that have AgentAttache and is forForward, CloudStack should remove the agent 2. For hosts that have AgentAttache and is not forForward but in Disconnect state, CloudStack should try to investigate and update the status to Up if host is pingable. 3. For hosts that don't have AgentAttache, CloudStack should try to loadDirectlyConnectedHost.
1 parent 4f21f81 commit dd1abf8

File tree

2 files changed

+182
-22
lines changed

2 files changed

+182
-22
lines changed

engine/orchestration/src/main/java/com/cloud/agent/manager/ClusteredAgentManagerImpl.java

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ private void runDirectAgentScanTimerTask() {
210210
scanDirectAgentToLoad();
211211
}
212212

213-
private void scanDirectAgentToLoad() {
213+
protected void scanDirectAgentToLoad() {
214214
logger.trace("Begin scanning directly connected hosts");
215215

216216
// for agents that are self-managed, threshold to be considered as disconnected after pingtimeout
@@ -231,11 +231,21 @@ private void scanDirectAgentToLoad() {
231231
logger.info("{} is detected down, but we have a forward attache running, disconnect this one before launching the host", host);
232232
removeAgent(agentattache, Status.Disconnected);
233233
} else {
234-
continue;
234+
logger.debug("Host {} status is {} but has an AgentAttache which is not forForward, try to load directly", host, host.getStatus());
235+
Status hostStatus = investigate(agentattache);
236+
if (Status.Up == hostStatus) {
237+
/* Got ping response from host, bring it back */
238+
logger.info("After investigation, Agent for host {} is determined to be up and running", host);
239+
agentStatusTransitTo(host, Event.Ping, _nodeId);
240+
} else {
241+
logger.debug("After investigation, AgentAttache is not null but host status is {}, try to load directly {}", hostStatus, host);
242+
loadDirectlyConnectedHost(host, false);
243+
}
235244
}
245+
} else {
246+
logger.debug("AgentAttache is null, loading directly connected {}", host);
247+
loadDirectlyConnectedHost(host, false);
236248
}
237-
logger.debug("Loading directly connected {}", host);
238-
loadDirectlyConnectedHost(host, false);
239249
} catch (final Throwable e) {
240250
logger.warn(" can not load directly connected {} due to ", host, e);
241251
}
@@ -381,20 +391,20 @@ public void reconnect(final long hostId) throws CloudRuntimeException, AgentUnav
381391
return;
382392
}
383393
if (!result) {
384-
throw new CloudRuntimeException("Failed to propagate agent change request event:" + Event.ShutdownRequested + " to host:" + hostId);
394+
throw new CloudRuntimeException(String.format("Failed to propagate agent change request event: %s to host: %s", Event.ShutdownRequested, hostId));
385395
}
386396
}
387397

388398
public void notifyNodesInCluster(final AgentAttache attache) {
389399
logger.debug("Notifying other nodes of to disconnect");
390-
final Command[] cmds = new Command[] {new ChangeAgentCommand(attache.getId(), Event.AgentDisconnected)};
400+
final Command[] cmds = new Command[]{new ChangeAgentCommand(attache.getId(), Event.AgentDisconnected)};
391401
_clusterMgr.broadcast(attache.getId(), _gson.toJson(cmds));
392402
}
393403

394404
// notifies MS peers to schedule a host scan task immediately, triggered during addHost operation
395405
public void notifyNodesInClusterToScheduleHostScanTask() {
396406
logger.debug("Notifying other MS nodes to run host scan task");
397-
final Command[] cmds = new Command[] {new ScheduleHostScanTaskCommand()};
407+
final Command[] cmds = new Command[]{new ScheduleHostScanTaskCommand()};
398408
_clusterMgr.broadcast(0, _gson.toJson(cmds));
399409
}
400410

@@ -435,7 +445,7 @@ public boolean routeToPeer(final String peer, final byte[] bytes) {
435445
}
436446
try {
437447
logD(bytes, "Routing to peer");
438-
Link.write(ch, new ByteBuffer[] {ByteBuffer.wrap(bytes)}, sslEngine);
448+
Link.write(ch, new ByteBuffer[]{ByteBuffer.wrap(bytes)}, sslEngine);
439449
return true;
440450
} catch (final IOException e) {
441451
try {
@@ -644,7 +654,7 @@ protected void doTask(final Task task) throws TaskExecutionException {
644654
}
645655
final Request req = Request.parse(data);
646656
final Command[] cmds = req.getCommands();
647-
final CancelCommand cancel = (CancelCommand)cmds[0];
657+
final CancelCommand cancel = (CancelCommand) cmds[0];
648658
logD(data, "Cancel request received");
649659
agent.cancel(cancel.getSequence());
650660
final Long current = agent._currentSequence;
@@ -671,7 +681,7 @@ protected void doTask(final Task task) throws TaskExecutionException {
671681
return;
672682
} else {
673683
if (agent instanceof Routable) {
674-
final Routable cluster = (Routable)agent;
684+
final Routable cluster = (Routable) agent;
675685
cluster.routeToAgent(data);
676686
} else {
677687
agent.send(Request.parse(data));
@@ -688,7 +698,7 @@ protected void doTask(final Task task) throws TaskExecutionException {
688698
if (mgmtId != -1 && mgmtId != _nodeId) {
689699
routeToPeer(Long.toString(mgmtId), data);
690700
if (Request.requiresSequentialExecution(data)) {
691-
final AgentAttache attache = (AgentAttache)link.attachment();
701+
final AgentAttache attache = (AgentAttache) link.attachment();
692702
if (attache != null) {
693703
attache.sendNext(Request.getSequence(data));
694704
}
@@ -961,7 +971,7 @@ protected void runInContext() {
961971
if (_agentToTransferIds.size() > 0) {
962972
logger.debug("Found {} agents to transfer", _agentToTransferIds.size());
963973
// for (Long hostId : _agentToTransferIds) {
964-
for (final Iterator<Long> iterator = _agentToTransferIds.iterator(); iterator.hasNext();) {
974+
for (final Iterator<Long> iterator = _agentToTransferIds.iterator(); iterator.hasNext(); ) {
965975
final Long hostId = iterator.next();
966976
final AgentAttache attache = findAttache(hostId);
967977

@@ -1105,7 +1115,7 @@ protected void finishRebalance(final long hostId, final long futureOwnerId, fina
11051115
return;
11061116
}
11071117

1108-
final ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)attache;
1118+
final ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache) attache;
11091119

11101120
if (success) {
11111121

@@ -1156,10 +1166,10 @@ protected boolean startRebalance(final long hostId) {
11561166
}
11571167

11581168
synchronized (_agents) {
1159-
final ClusteredDirectAgentAttache attache = (ClusteredDirectAgentAttache)_agents.get(hostId);
1169+
final ClusteredDirectAgentAttache attache = (ClusteredDirectAgentAttache) _agents.get(hostId);
11601170
if (attache != null && attache.getQueueSize() == 0 && attache.getNonRecurringListenersSize() == 0) {
11611171
handleDisconnectWithoutInvestigation(attache, Event.StartAgentRebalance, true, true);
1162-
final ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)createAttache(host);
1172+
final ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache) createAttache(host);
11631173
if (forwardAttache == null) {
11641174
logger.warn("Unable to create a forward attache for the host {} as a part of rebalance process", host);
11651175
return false;
@@ -1263,7 +1273,7 @@ public String dispatch(final ClusterServicePdu pdu) {
12631273
}
12641274

12651275
if (cmds.length == 1 && cmds[0] instanceof ChangeAgentCommand) { // intercepted
1266-
final ChangeAgentCommand cmd = (ChangeAgentCommand)cmds[0];
1276+
final ChangeAgentCommand cmd = (ChangeAgentCommand) cmds[0];
12671277

12681278
logger.debug("Intercepting command for agent change: agent {} event: {}", cmd.getAgentId(), cmd.getEvent());
12691279
boolean result = false;
@@ -1280,7 +1290,7 @@ public String dispatch(final ClusterServicePdu pdu) {
12801290
answers[0] = new ChangeAgentAnswer(cmd, result);
12811291
return _gson.toJson(answers);
12821292
} else if (cmds.length == 1 && cmds[0] instanceof TransferAgentCommand) {
1283-
final TransferAgentCommand cmd = (TransferAgentCommand)cmds[0];
1293+
final TransferAgentCommand cmd = (TransferAgentCommand) cmds[0];
12841294

12851295
logger.debug("Intercepting command for agent rebalancing: agent: {}, event: {}, connection transfer: {}", cmd.getAgentId(), cmd.getEvent(), cmd.isConnectionTransfer());
12861296
boolean result = false;
@@ -1299,7 +1309,7 @@ public String dispatch(final ClusterServicePdu pdu) {
12991309
answers[0] = new Answer(cmd, result, null);
13001310
return _gson.toJson(answers);
13011311
} else if (cmds.length == 1 && cmds[0] instanceof PropagateResourceEventCommand) {
1302-
final PropagateResourceEventCommand cmd = (PropagateResourceEventCommand)cmds[0];
1312+
final PropagateResourceEventCommand cmd = (PropagateResourceEventCommand) cmds[0];
13031313

13041314
logger.debug("Intercepting command to propagate event {} for host {} ({})", () -> cmd.getEvent().name(), cmd::getHostId, () -> _hostDao.findById(cmd.getHostId()));
13051315

@@ -1316,10 +1326,10 @@ public String dispatch(final ClusterServicePdu pdu) {
13161326
answers[0] = new Answer(cmd, result, null);
13171327
return _gson.toJson(answers);
13181328
} else if (cmds.length == 1 && cmds[0] instanceof ScheduleHostScanTaskCommand) {
1319-
final ScheduleHostScanTaskCommand cmd = (ScheduleHostScanTaskCommand)cmds[0];
1329+
final ScheduleHostScanTaskCommand cmd = (ScheduleHostScanTaskCommand) cmds[0];
13201330
return handleScheduleHostScanTaskCommand(cmd);
13211331
} else if (cmds.length == 1 && cmds[0] instanceof BaseShutdownManagementServerHostCommand) {
1322-
final BaseShutdownManagementServerHostCommand cmd = (BaseShutdownManagementServerHostCommand)cmds[0];
1332+
final BaseShutdownManagementServerHostCommand cmd = (BaseShutdownManagementServerHostCommand) cmds[0];
13231333
return handleShutdownManagementServerHostCommand(cmd);
13241334
}
13251335

@@ -1372,7 +1382,7 @@ private String handleShutdownManagementServerHostCommand(BaseShutdownManagementS
13721382
try {
13731383
managementServerMaintenanceManager.prepareForShutdown();
13741384
return "Successfully prepared for shutdown";
1375-
} catch(CloudRuntimeException e) {
1385+
} catch (CloudRuntimeException e) {
13761386
return e.getMessage();
13771387
}
13781388
}
@@ -1381,7 +1391,7 @@ private String handleShutdownManagementServerHostCommand(BaseShutdownManagementS
13811391
try {
13821392
managementServerMaintenanceManager.triggerShutdown();
13831393
return "Successfully triggered shutdown";
1384-
} catch(CloudRuntimeException e) {
1394+
} catch (CloudRuntimeException e) {
13851395
return e.getMessage();
13861396
}
13871397
}
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
package com.cloud.agent.manager;
19+
20+
import com.cloud.configuration.ManagementServiceConfiguration;
21+
import com.cloud.ha.HighAvailabilityManagerImpl;
22+
import com.cloud.host.HostVO;
23+
import com.cloud.host.Status;
24+
import com.cloud.host.dao.HostDao;
25+
import com.cloud.resource.ResourceManagerImpl;
26+
import org.junit.Before;
27+
import org.junit.Test;
28+
import org.junit.runner.RunWith;
29+
import org.mockito.Mock;
30+
import org.mockito.Mockito;
31+
import org.mockito.junit.MockitoJUnitRunner;
32+
33+
import java.util.ArrayList;
34+
import java.util.List;
35+
36+
import static org.mockito.ArgumentMatchers.any;
37+
import static org.mockito.ArgumentMatchers.anyBoolean;
38+
import static org.mockito.ArgumentMatchers.anyLong;
39+
import static org.mockito.Mockito.doReturn;
40+
import static org.mockito.Mockito.mock;
41+
import static org.mockito.Mockito.never;
42+
import static org.mockito.Mockito.verify;
43+
import static org.mockito.Mockito.when;
44+
45+
@RunWith(MockitoJUnitRunner.class)
46+
public class ClusteredAgentManagerImplTest {
47+
48+
private HostDao _hostDao;
49+
@Mock
50+
ManagementServiceConfiguration _mgmtServiceConf;
51+
52+
@Before
53+
public void setUp() throws Exception {
54+
_hostDao = mock(HostDao.class);
55+
}
56+
57+
@Test
58+
public void scanDirectAgentToLoadNoHostsTest() {
59+
ClusteredAgentManagerImpl clusteredAgentManagerImpl = mock(ClusteredAgentManagerImpl.class);
60+
clusteredAgentManagerImpl._hostDao = _hostDao;
61+
clusteredAgentManagerImpl.scanDirectAgentToLoad();
62+
verify(clusteredAgentManagerImpl, never()).findAttache(anyLong());
63+
verify(clusteredAgentManagerImpl, never()).loadDirectlyConnectedHost(any(), anyBoolean());
64+
}
65+
66+
@Test
67+
public void scanDirectAgentToLoadHostWithoutAttacheTest() {
68+
// Arrange
69+
ClusteredAgentManagerImpl clusteredAgentManagerImpl = Mockito.spy(ClusteredAgentManagerImpl.class);
70+
HostVO hostVO = mock(HostVO.class);
71+
clusteredAgentManagerImpl._hostDao = _hostDao;
72+
clusteredAgentManagerImpl.mgmtServiceConf = _mgmtServiceConf;
73+
clusteredAgentManagerImpl._resourceMgr = mock(ResourceManagerImpl.class);
74+
when(_mgmtServiceConf.getTimeout()).thenReturn(16000L);
75+
when(hostVO.getId()).thenReturn(1L);
76+
List hosts = new ArrayList<>();
77+
hosts.add(hostVO);
78+
when(_hostDao.findAndUpdateDirectAgentToLoad(anyLong(), anyLong(), anyLong())).thenReturn(hosts);
79+
AgentAttache agentAttache = mock(AgentAttache.class);
80+
doReturn(Boolean.TRUE).when(clusteredAgentManagerImpl).loadDirectlyConnectedHost(hostVO, false);
81+
clusteredAgentManagerImpl.scanDirectAgentToLoad();
82+
verify(clusteredAgentManagerImpl).loadDirectlyConnectedHost(hostVO, false);
83+
}
84+
85+
@Test
86+
public void scanDirectAgentToLoadHostWithForwardAttacheTest() {
87+
ClusteredAgentManagerImpl clusteredAgentManagerImpl = Mockito.spy(ClusteredAgentManagerImpl.class);
88+
HostVO hostVO = mock(HostVO.class);
89+
clusteredAgentManagerImpl._hostDao = _hostDao;
90+
clusteredAgentManagerImpl.mgmtServiceConf = _mgmtServiceConf;
91+
when(_mgmtServiceConf.getTimeout()).thenReturn(16000L);
92+
when(hostVO.getId()).thenReturn(1L);
93+
List hosts = new ArrayList<>();
94+
hosts.add(hostVO);
95+
when(_hostDao.findAndUpdateDirectAgentToLoad(anyLong(), anyLong(), anyLong())).thenReturn(hosts);
96+
AgentAttache agentAttache = mock(AgentAttache.class);
97+
when(agentAttache.forForward()).thenReturn(Boolean.TRUE);
98+
when(clusteredAgentManagerImpl.findAttache(1L)).thenReturn(agentAttache);
99+
100+
clusteredAgentManagerImpl.scanDirectAgentToLoad();
101+
verify(clusteredAgentManagerImpl).removeAgent(agentAttache, Status.Disconnected);
102+
}
103+
104+
@Test
105+
public void scanDirectAgentToLoadHostWithNonForwardAttacheTest() {
106+
// Arrange
107+
ClusteredAgentManagerImpl clusteredAgentManagerImpl = Mockito.spy(new ClusteredAgentManagerImpl());
108+
HostVO hostVO = mock(HostVO.class);
109+
clusteredAgentManagerImpl._hostDao = _hostDao;
110+
clusteredAgentManagerImpl.mgmtServiceConf = _mgmtServiceConf;
111+
clusteredAgentManagerImpl._haMgr = mock(HighAvailabilityManagerImpl.class);
112+
when(_mgmtServiceConf.getTimeout()).thenReturn(16000L);
113+
when(hostVO.getId()).thenReturn(0L);
114+
List hosts = new ArrayList<>();
115+
hosts.add(hostVO);
116+
when(_hostDao.findAndUpdateDirectAgentToLoad(anyLong(), anyLong(), anyLong())).thenReturn(hosts);
117+
118+
AgentAttache agentAttache = mock(AgentAttache.class);
119+
when(agentAttache.forForward()).thenReturn(Boolean.FALSE);
120+
when(clusteredAgentManagerImpl.findAttache(0L)).thenReturn(agentAttache);
121+
doReturn(Boolean.TRUE).when(clusteredAgentManagerImpl).agentStatusTransitTo(hostVO, Status.Event.Ping, clusteredAgentManagerImpl._nodeId);
122+
doReturn(Status.Up).when(clusteredAgentManagerImpl).investigate(agentAttache);
123+
124+
clusteredAgentManagerImpl.scanDirectAgentToLoad();
125+
verify(clusteredAgentManagerImpl).investigate(agentAttache);
126+
verify(clusteredAgentManagerImpl).agentStatusTransitTo(hostVO, Status.Event.Ping, clusteredAgentManagerImpl._nodeId);
127+
}
128+
129+
@Test
130+
public void scanDirectAgentToLoadHostWithNonForwardAttacheAndDisconnectedTest() {
131+
ClusteredAgentManagerImpl clusteredAgentManagerImpl = Mockito.spy(ClusteredAgentManagerImpl.class);
132+
HostVO hostVO = mock(HostVO.class);
133+
clusteredAgentManagerImpl._hostDao = _hostDao;
134+
clusteredAgentManagerImpl.mgmtServiceConf = _mgmtServiceConf;
135+
clusteredAgentManagerImpl._haMgr = mock(HighAvailabilityManagerImpl.class);
136+
clusteredAgentManagerImpl._resourceMgr = mock(ResourceManagerImpl.class);
137+
when(_mgmtServiceConf.getTimeout()).thenReturn(16000L);
138+
when(hostVO.getId()).thenReturn(0L);
139+
List hosts = new ArrayList<>();
140+
hosts.add(hostVO);
141+
when(_hostDao.findAndUpdateDirectAgentToLoad(anyLong(), anyLong(), anyLong())).thenReturn(hosts);
142+
AgentAttache agentAttache = mock(AgentAttache.class);
143+
when(agentAttache.forForward()).thenReturn(Boolean.FALSE);
144+
when(clusteredAgentManagerImpl.findAttache(0L)).thenReturn(agentAttache);
145+
doReturn(Boolean.TRUE).when(clusteredAgentManagerImpl).loadDirectlyConnectedHost(hostVO, false);
146+
clusteredAgentManagerImpl.scanDirectAgentToLoad();
147+
verify(clusteredAgentManagerImpl).investigate(agentAttache);
148+
verify(clusteredAgentManagerImpl).loadDirectlyConnectedHost(hostVO, false);
149+
}
150+
}

0 commit comments

Comments
 (0)