Skip to content

Commit 691b7d4

Browse files
review comments
1 parent 935a0b2 commit 691b7d4

22 files changed

Lines changed: 303 additions & 137 deletions

File tree

‎agent/src/main/java/com/cloud/agent/Agent.java‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import java.net.ConnectException;
2424
import java.net.InetAddress;
2525
import java.net.InetSocketAddress;
26+
import java.net.SocketAddress;
2627
import java.net.Socket;
2728
import java.net.UnknownHostException;
2829
import java.nio.channels.ClosedChannelException;
@@ -680,7 +681,7 @@ protected void reconnect(Link link, String preferredHost, boolean forceReconnect
680681
try {
681682
stopAndCleanupConnection();
682683
} catch (Exception ex) {
683-
logger.warn("Got an exception during stop and cleanup connection", e);
684+
logger.warn("Got an exception during stop and cleanup connection", ex);
684685
}
685686

686687
updateRefuseLoopState(e, host, firstRefuseLoopHostRef, ignoreAvoidMsHostListRef, skipTimeoutRef);
@@ -734,13 +735,13 @@ private void updateRefuseLoopState(Exception e, String host, AtomicReference<Str
734735
if (skipTimeout && firstRefuseLoopHost == null) {
735736
firstRefuseLoopHostRef.set(host);
736737
ignoreAvoidMsHostListRef.set(false);
737-
logger.debug("Started refuse loop for host {}", firstRefuseLoopHost);
738+
logger.debug("Started refuse loop for host {}", host);
738739
// closed "refuse loop"
739740
} else if (skipTimeout && firstRefuseLoopHost.equalsIgnoreCase(host)) {
740741
ignoreAvoidMsHostListRef.set(true);
741742
logger.debug("Closed refuse loop for host {}", firstRefuseLoopHost);
742743
// got non "refuse" related issue, break "refuse loop"
743-
} else if (!skipTimeout && (firstRefuseLoopHostRef != null || ignoreAvoidMsHostListRef.get())) {
744+
} else if (!skipTimeout && (firstRefuseLoopHost != null || ignoreAvoidMsHostListRef.get())) {
744745
logger.debug("Broke refuse loop for host {} by {}", firstRefuseLoopHost, host);
745746
firstRefuseLoopHostRef.set(null);
746747
ignoreAvoidMsHostListRef.set(false);
@@ -839,7 +840,8 @@ private boolean isReconnectStormDetected(Link link, String preferredHost, String
839840
logger.debug("Calling storm guard");
840841
boolean reconnectForCurrentLink = link == this.link;
841842
boolean currentLinkTerminated = this.link != null && this.link.isTerminated();
842-
boolean reconnectForNewHost = this.hostname != null && this.hostname.equals(preferredHost);
843+
String connectedHost = connection != null ? connection.getHost() : null;
844+
boolean reconnectForNewHost = org.apache.commons.lang3.StringUtils.isNotBlank(preferredHost) && !preferredHost.equalsIgnoreCase(connectedHost);
843845
// if none of the above is true
844846
boolean stormDetected = !(reconnectForCurrentLink || currentLinkTerminated || reconnectForNewHost);
845847
// connection storm guard
@@ -1708,12 +1710,12 @@ public int getNewConnectionsCount() {
17081710
}
17091711

17101712
@Override
1711-
public void registerNewConnection(InetSocketAddress address) {
1713+
public void registerNewConnection(SocketAddress address) {
17121714
logger.trace("Register new connection to {}", address);
17131715
}
17141716

17151717
@Override
1716-
public void unregisterNewConnection(InetSocketAddress address) {
1718+
public void unregisterNewConnection(SocketAddress address) {
17171719
logger.trace("Unregister new connection to {}", address);
17181720
}
17191721

‎agent/src/main/java/com/cloud/agent/AgentShell.java‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ public void setBackoffAlgorithm(BackoffAlgorithm backoffAlgorithm) {
101101
try {
102102
backoffAlgorithm.getConfiguration().forEach((key, value) -> setPersistentProperty(null, key, value));
103103
} catch (RuntimeException e) {
104-
LOGGER.warn("Failed to persist backoff properties");
104+
LOGGER.warn("Failed to persist backoff properties", e);
105105
}
106106
}
107107

@@ -420,7 +420,7 @@ public void init(String[] args) throws ConfigurationException {
420420
if (LOGGER.isDebugEnabled()) {
421421
List<String> properties = Collections.list((Enumeration<String>)_properties.propertyNames());
422422
for (String property : properties) {
423-
LOGGER.debug("Found property: {}, value: {}", property, _properties.getProperty(property));
423+
LOGGER.debug("Found property: {}", property);
424424
}
425425
}
426426

@@ -439,8 +439,7 @@ public void init(String[] args) throws ConfigurationException {
439439
setBackoffAlgorithm(BackoffFactory.create(_properties));
440440
LOGGER.info("Created {} delay algorithm implementation", getBackoffAlgorithm().getClass().getName());
441441
} catch (RuntimeException e) {
442-
String msg = String.format("Failed to create backoff with provided properties %s, failing back to default", _properties);
443-
LOGGER.warn(msg, e);
442+
LOGGER.warn("Failed to create backoff algorithm from the provided properties, falling back to default", e);
444443
setBackoffAlgorithm(BackoffFactory.createDefault(_properties));
445444
}
446445
}
@@ -583,7 +582,6 @@ public static void main(String[] args) {
583582
shell.start();
584583
} catch (ConfigurationException e) {
585584
LOGGER.fatal(e.getMessage(), e);
586-
System.out.println(e.getMessage());
587585
}
588586
}
589587

‎agent/src/main/java/com/cloud/agent/HostConnectProcess.java‎

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -125,30 +125,30 @@ public void updateHostStatusCheckDelay(int newDelaySec) {
125125
}
126126

127127
/**
128-
* Task wait for the Host to be available to connect to submit {@link StartupCommand}.
128+
* Task waits for the Host to be available to connect to submit {@link StartupCommand}.
129129
* Checks Host status on Management Server cluster and submit {@link StartupCommand} only if there is no lock and
130130
* Host is not {@link Status#Connecting}.
131131
*/
132132
public static class HostStatusTask implements Runnable, AsyncSend {
133133
private final Set<Status> operationalStatuses = Set.of(Status.Connecting, Status.Up, Status.Rebalancing);
134134

135-
private final Link _link;
136-
private final boolean _forceConnect;
137-
private final Agent _agent;
138-
private final AtomicReference<? extends ScheduledFuture<?>> _futureRef;
135+
private final Link link;
136+
private final boolean forceConnect;
137+
private final Agent agent;
138+
private final AtomicReference<? extends ScheduledFuture<?>> futureRef;
139139

140140
public HostStatusTask(Link link, boolean forceConnect, Agent agent,
141141
AtomicReference<? extends ScheduledFuture<?>> futureRef) {
142142
logger.debug("{} created", this.getClass().getSimpleName());
143-
_link = link;
144-
_forceConnect = forceConnect;
145-
_agent = agent;
146-
_futureRef = futureRef;
143+
this.link = link;
144+
this.forceConnect = forceConnect;
145+
this.agent = agent;
146+
this.futureRef = futureRef;
147147
}
148148

149149
private void cancel() {
150150
logger.debug("Cancelling future");
151-
Optional.ofNullable(_futureRef.get())
151+
Optional.ofNullable(futureRef.get())
152152
.filter(Predicate.not(ScheduledFuture::isCancelled))
153153
.ifPresent(future -> future.cancel(true));
154154
logger.debug("Cancelled future");
@@ -165,7 +165,7 @@ public void run() {
165165
}
166166

167167
private void runInternal() {
168-
ServerAttache attache = (ServerAttache) _link.attachment();
168+
ServerAttache attache = (ServerAttache) link.attachment();
169169
if (attache == null || attache.getLink() == null) {
170170
cancel();
171171
return;
@@ -176,8 +176,8 @@ private void runInternal() {
176176
answer = getAgentConnectStatusAnswer(attache);
177177
} catch (IOException e) {
178178
cancel();
179-
logger.error("The connection to {} interrupted, restarting the whole process", _link, e);
180-
_agent.getRequestHandler().submit(() -> _agent.reconnect(_link, null, _forceConnect));
179+
logger.error("The connection to {} interrupted, restarting the whole process", link, e);
180+
agent.getRequestHandler().submit(() -> agent.reconnect(link, null, forceConnect));
181181
return;
182182
}
183183
if (answer == null) {
@@ -190,24 +190,24 @@ private void runInternal() {
190190
// send startup command here
191191
logger.info("There is no lock and Host status is {}", status);
192192
try {
193-
sendStartupCommand(_link, _forceConnect);
194-
logger.debug("Sending startup command to {} finished", _link);
193+
sendStartupCommand();
194+
logger.debug("Sending startup command to {} finished", link);
195195
cancel();
196196
logger.debug("Unscheduled {}", getClass().getSimpleName());
197197
} catch (RuntimeException e) {
198-
logger.error("Failed to send startup command to {}", _link, e);
198+
logger.error("Failed to send startup command to {}", link, e);
199199
} catch (IOException e) {
200200
cancel();
201-
logger.error("The connection to {} interrupted, restarting the whole process", _link, e);
202-
_agent.getRequestHandler().submit(() -> _agent.reconnect(_link, null, _forceConnect));
201+
logger.error("The connection to {} interrupted, restarting the whole process", link, e);
202+
agent.getRequestHandler().submit(() -> agent.reconnect(link, null, forceConnect));
203203
}
204204
} else {
205205
logger.info("There is lock and Host status is {}, will retry later", status);
206206
}
207207
}
208208

209209
private AgentConnectStatusAnswer getAgentConnectStatusAnswer(ServerAttache attache) throws IOException {
210-
AgentConnectStatusCommand command = _agent.setupAgentConnectStatusCommand(new AgentConnectStatusCommand());
210+
AgentConnectStatusCommand command = agent.setupAgentConnectStatusCommand(new AgentConnectStatusCommand());
211211
var commands = new Command[]{command};
212212
try {
213213
return send(attache, commands, AgentConnectStatusAnswer.class, DEFAULT_ASYNC_COMMAND_TIMEOUT_SEC);
@@ -218,26 +218,26 @@ private AgentConnectStatusAnswer getAgentConnectStatusAnswer(ServerAttache attac
218218
}
219219
}
220220

221-
public void sendStartupCommand(Link link, boolean connectionTransfer) throws IOException {
221+
public void sendStartupCommand() throws IOException {
222222
ServerAttache attache = (ServerAttache) link.attachment();
223223
if (attache == null || attache.getLink() == null) {
224224
return;
225225
}
226-
ServerResource serverResource = _agent.getResource();
226+
ServerResource serverResource = agent.getResource();
227227
StartupCommand[] startup = serverResource.initialize();
228228
if (ArrayUtils.isEmpty(startup)) {
229229
logger.warn("No startup commands returned from {}, Startup command sending skipped", serverResource.getName());
230230
return;
231231
}
232-
String msHostList = _agent.getPersistentProperty("host");
232+
String msHostList = agent.getPersistentProperty("host");
233233
// need to downcast StartupCommand[] to Command[], otherwise logger will fail to decode JSON on MS side
234234
Command[] commands = new Command[startup.length];
235235
for (int i = 0; i < startup.length; i++) {
236236
StartupCommand command = startup[i];
237237
commands[i] = command;
238-
_agent.setupStartupCommand(command);
238+
agent.setupStartupCommand(command);
239239
command.setMSHostList(msHostList);
240-
command.setConnectionTransferred(connectionTransfer);
240+
command.setConnectionTransferred(forceConnect);
241241
ThreadContextCommandUtil.setContextInCommand(command);
242242
}
243243
String commandName = commands[0].getClass().getSimpleName();
@@ -263,29 +263,29 @@ public void sendStartupCommand(Link link, boolean connectionTransfer) throws IOE
263263
AgentConnectStatusAnswer answer = getAgentConnectStatusAnswer(attache);
264264
if (answer == null) {
265265
logger.warn("Received empty agent connect status answer, reconnecting");
266-
_agent.getRequestHandler().submit(() -> _agent.reconnect(link, null, connectionTransfer));
266+
agent.getRequestHandler().submit(() -> agent.reconnect(link, null, forceConnect));
267267
return;
268268
}
269269
Boolean lockAvailable = answer.isLockAvailable();
270270
Status status = answer.getHostStatus();
271271
if (Boolean.TRUE.equals(lockAvailable) && status != null && operationalStatuses.contains(status)) {
272-
logger.info("Host is in operational state {} on {}", status, _link);
272+
logger.info("Host is in operational state {} on {}", status, link);
273273
} else if (Boolean.FALSE.equals(lockAvailable)) {
274-
logger.info("Host is locked and has state {} on {}", status, _link);
274+
logger.info("Host is locked and has state {} on {}", status, link);
275275
} else {
276-
logger.info("Host is locked and has state {} on {}, reconnecting", status, _link);
277-
_agent.getRequestHandler().submit(() -> _agent.reconnect(link, null, connectionTransfer));
276+
logger.info("Host is locked and has state {} on {}, reconnecting", status, link);
277+
agent.getRequestHandler().submit(() -> agent.reconnect(link, null, forceConnect));
278278
return;
279279
}
280280
}
281281
if (serverResource instanceof ResourceStatusUpdater) {
282-
((ResourceStatusUpdater) serverResource).registerStatusUpdater(_agent);
282+
((ResourceStatusUpdater) serverResource).registerStatusUpdater(agent);
283283
}
284284

285285
}
286286

287287
public Agent getAgent() {
288-
return _agent;
288+
return agent;
289289
}
290290
}
291291

‎agent/src/main/java/com/cloud/agent/ServerAttache.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ protected void cancel(Request req) {
124124
protected synchronized void cancel(long seq) {
125125
logger.debug(log(seq, "Cancelling."));
126126

127-
ServerListener listener = _waitForList.remove(seq);
127+
ServerListener listener = unregisterListener(seq);
128128
if (listener != null) {
129129
listener.processDisconnect();
130130
}
@@ -194,7 +194,7 @@ public boolean processAnswers(long seq, Response resp) {
194194
logger.debug(log(seq, "Unable to find listener."));
195195
} else {
196196
processed = monitor.processAnswers(seq, answers);
197-
logger.trace(log(seq, (processed ? "" : " did not ") + " processed "));
197+
logger.trace(log(seq, processed ? "Processed" : "Not processed"));
198198
if (!monitor.isRecurring()) {
199199
unregisterListener(seq);
200200
}
@@ -486,7 +486,7 @@ protected void runInContext() {
486486
listener.processTimeout(_seq);
487487
}
488488
} catch (Exception e) {
489-
ServerAttache.logger.warn("Exception ", e);
489+
ServerAttache.logger.warn(log(_seq, "Failed to process listener timeout"), e);
490490
}
491491
}
492492
}

‎core/src/main/java/com/cloud/agent/api/AgentConnectStatusAnswer.java‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,9 @@
3131
public class AgentConnectStatusAnswer extends Answer {
3232

3333
/**
34-
* {@link Boolean#TRUE} means host has {@link GlobalLock#lock(int)} acquired, otherwise {@link Boolean#FALSE},
35-
* and null if there is an error during executing {@link AgentConnectStatusCommand}.
34+
* {@link Boolean#TRUE} means the host connect {@link GlobalLock} is available (no management server holds it),
35+
* so the agent may send its {@link StartupCommand}; {@link Boolean#FALSE} means another connect process holds it;
36+
* null if there is an error during executing {@link AgentConnectStatusCommand}.
3637
*/
3738
private Boolean lockAvailable;
3839
/**

‎core/src/main/java/org/apache/cloudstack/threadcontext/ThreadContextCommandUtil.java‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,24 @@ public class ThreadContextCommandUtil {
3030

3131
/**
3232
* Propagate UUID and log context ID from Command trace context to MDC.
33+
* A key absent from the command is removed from MDC so that a worker thread does not
34+
* carry over the context of a previously processed command.
3335
*
3436
* @param cmd the command containing trace context parameters
3537
*/
3638
public static void propagateContextFromCommand(Command cmd) {
37-
if (cmd != null) {
38-
ThreadContextUtil.setLogContextId(cmd.getTraceContextParam(ThreadContextUtil.CONTEXT_LOG_ID_KEY));
39-
ThreadContextUtil.setUuid(cmd.getTraceContextParam(ThreadContextUtil.CONTEXT_UUID_KEY));
39+
if (cmd == null) {
40+
return;
41+
}
42+
putOrRemove(ThreadContextUtil.MDC_LOG_CONTEXT_ID_KEY, cmd.getTraceContextParam(ThreadContextUtil.CONTEXT_LOG_ID_KEY));
43+
putOrRemove(ThreadContextUtil.MDC_UUID_KEY, cmd.getTraceContextParam(ThreadContextUtil.CONTEXT_UUID_KEY));
44+
}
45+
46+
private static void putOrRemove(String mdcKey, String value) {
47+
if (StringUtils.isNotEmpty(value)) {
48+
ThreadContext.put(mdcKey, value);
49+
} else {
50+
ThreadContext.remove(mdcKey);
4051
}
4152
}
4253

0 commit comments

Comments
 (0)