Copilot commented on code in PR #13345: URL: https://github.com/apache/cloudstack/pull/13345#discussion_r4144777505
########## agent/src/main/java/com/cloud/agent/HostConnectProcess.java: ########## @@ -0,0 +1,343 @@ +// 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.agent; + +import com.cloud.agent.api.AgentConnectStatusAnswer; +import com.cloud.agent.api.AgentConnectStatusCommand; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; +import com.cloud.agent.api.StartupAnswer; +import com.cloud.agent.api.StartupCommand; +import com.cloud.agent.properties.AgentProperties; +import com.cloud.agent.properties.AgentPropertiesFileHandler; +import com.cloud.agent.transport.Request; +import com.cloud.exception.CloudException; +import com.cloud.exception.OperationTimedoutException; +import com.cloud.host.Status; +import com.cloud.resource.ResourceStatusUpdater; +import com.cloud.resource.ServerResource; +import com.cloud.utils.concurrency.NamedThreadFactory; +import com.cloud.utils.nio.Link; +import org.apache.cloudstack.threadcontext.ThreadContextCommandUtil; +import org.apache.cloudstack.threadcontext.ThreadContextUtil; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; + +import java.io.IOException; +import java.nio.channels.ClosedChannelException; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Predicate; + +public class HostConnectProcess { + private static final Logger logger = LogManager.getLogger(HostConnectProcess.class); + + public static final int DEFAULT_ASYNC_COMMAND_TIMEOUT_SEC = + AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ASYNC_COMMAND_TIMEOUT_SEC); + + public static final int DEFAULT_ASYNC_STARTUP_COMMAND_TIMEOUT_SEC = + AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ASYNC_STARTUP_COMMAND_TIMEOUT_SEC); + + static final long HOST_STATUS_CHECK_INITIAL_DELAY_SEC = 10; + private long hostStatusCheckDelaySec = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.AGENT_HOST_STATUS_CHECK_DELAY_SEC); + private final AtomicReference<ScheduledFuture<?>> hostStatusFutureRef = new AtomicReference<>(); + private final Agent agent; + private ScheduledExecutorService hostStatusExecutor; + + public HostConnectProcess(Agent agent) { + this.agent = agent; + initExecutors(); + } + + private void initExecutors() { + stop(); + var threadFactory = new NamedThreadFactory("Agent-" + HostStatusTask.class.getSimpleName()); + hostStatusExecutor = Executors.newScheduledThreadPool(1, threadFactory); + } + + /** + * Stops the whole connect process and cancels all scheduled asynchronous tasks. + * Returns {@link Boolean#TRUE} if {@link HostConnectProcess} was waiting for {@link StartupAnswer}. + */ + public boolean stop() { + logger.debug("Stopping connect process. The process is active: {}", isInProgress()); + stopHostStatusExecutor(); + logger.debug("Stopped executor"); + Optional<? extends ScheduledFuture<?>> hostStatusOpt = Optional.ofNullable(hostStatusFutureRef.getAndSet(null)) + .filter(Predicate.not(ScheduledFuture::isCancelled)); + + hostStatusOpt.ifPresent(future -> future.cancel(true)); + logger.debug("Cancelled future"); + + return hostStatusOpt.isPresent(); + } + + private void stopHostStatusExecutor() { + if (hostStatusExecutor != null) { + hostStatusExecutor.shutdownNow(); + hostStatusExecutor = null; + } + } + + public void scheduleConnectProcess(Link link, boolean connectionTransfer) { + logger.debug("Scheduling connect process for {}", link); + initExecutors(); + + var task = new HostStatusTask(link, connectionTransfer, agent, hostStatusFutureRef); + var future = hostStatusExecutor.scheduleWithFixedDelay(ThreadContextUtil.wrapThreadContext(task), + HOST_STATUS_CHECK_INITIAL_DELAY_SEC, + hostStatusCheckDelaySec, TimeUnit.SECONDS); + hostStatusFutureRef.set(future); + } + + /** + * Returns {@link Boolean#TRUE} if {@link HostStatusTask} created and scheduled. + * That means there is already {@link Status#Connecting} process is running. + */ + public boolean isInProgress() { + return Optional.ofNullable(hostStatusFutureRef.get()) + .filter(Predicate.not(ScheduledFuture::isCancelled)).isPresent(); + } + + public void updateHostStatusCheckDelay(int newDelaySec) { + logger.info("Updating host status check delay from {} to {} seconds", hostStatusCheckDelaySec, newDelaySec); + this.hostStatusCheckDelaySec = newDelaySec; + } + + /** + * Task waits for the Host to be available to connect to submit {@link StartupCommand}. + * Checks Host status on Management Server cluster and submit {@link StartupCommand} only if there is no lock and + * Host is not {@link Status#Connecting}. + */ + public static class HostStatusTask implements Runnable, AsyncSend { + private final Set<Status> operationalStatuses = Set.of(Status.Connecting, Status.Up, Status.Rebalancing); + + private final Link link; + private final boolean forceConnect; + private final Agent agent; + private final AtomicReference<? extends ScheduledFuture<?>> futureRef; + + public HostStatusTask(Link link, boolean forceConnect, Agent agent, + AtomicReference<? extends ScheduledFuture<?>> futureRef) { + logger.debug("{} created", this.getClass().getSimpleName()); + this.link = link; + this.forceConnect = forceConnect; + this.agent = agent; + this.futureRef = futureRef; + } + + private void cancel() { + logger.debug("Cancelling future"); + Optional.ofNullable(futureRef.get()) + .filter(Predicate.not(ScheduledFuture::isCancelled)) + .ifPresent(future -> future.cancel(true)); Review Comment: `futureRef` is shared by all generations of `HostStatusTask`. If a new connection replaces an in-flight task, the cancelled old task can still return from its status request and call `cancel()`, which reads the newly installed future and cancels the replacement process. Keep the future associated with the task generation or cancel it only when the reference still points to that task. ########## framework/cluster/src/main/java/com/cloud/cluster/ClusterManagerImpl.java: ########## @@ -1250,7 +1253,18 @@ public ConfigKey<?>[] getConfigKeys() { private boolean pingManagementNode(final ManagementServerHostVO mshost) { final String targetIp = mshost.getServiceIP(); - if ("127.0.0.1".equals(targetIp) || "0.0.0.0".equals(targetIp)) { + final String targetHostName = mshost.getName(); + final String currentHostName = NetUtils.getCanonicalHostName(); + + // Prefer hostname (CNAME support) but fall back to the non-null service IP when name is unset. + final String connectTarget = StringUtils.isNotBlank(targetHostName) ? targetHostName : targetIp; + + // Check for self-detection using hostname comparison (for CNAME support) + if (currentHostName != null && currentHostName.equals(targetHostName)) { + logger.info("ping management node cluster service can not be performed on self (hostname match: {})", currentHostName); + return false; Review Comment: This hostname self-check runs while `checkNodeConflict` is validating a peer with the same hostname. For a live duplicate node that has the same hostname but a different service IP, `pingManagementNode` returns false here instead of probing the peer, so `handleConflict` treats the active conflict as stale and allows startup. Self-detection should use the local management-server record/id (or otherwise distinguish the peer IP), not hostname equality alone. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
