From ad77a3f2235f20cd5f1be8a45f2c892a547a2827 Mon Sep 17 00:00:00 2001 From: Brad House Date: Sun, 22 Nov 2026 20:28:16 +0000 Subject: [PATCH] Run rolling maintenance hooks on plain host maintenance Opt-in: kvm.host.maintenance.run.hooks (cluster, default false). Reuses the existing RollingMaintenanceCommand and rolling.maintenance.hooks.dir scripts on the KVM agent; no agent change. | Path | Stage | When | On failure | |---|---|---|---| | prepareHostForMaintenance | PreFlight, PreMaintenance | before VMs move | maintenance refused (also on exit 70 or host not Up) | | host reaches Maintenance | PostMigrate (new) | host is empty, runs in background | alert, state unchanged | | cancelHostMaintenance | PostMaintenance | before the host is enabled | alert, cancel goes on | - The Maintenance stage never runs on this path; the operator does the work. - Host detail `maintenance.hooks` holds an id of the maintenance whose PreMaintenance ran. PostMigrate and PostMaintenance only fire for that maintenance; PostMaintenance drops the marker. - A cluster-wide lock per host is held while any stage runs (rolling or not), so stages never overlap. - Prepare is refused before any hook when the host state can't enter maintenance (e.g. Disabled) or VMs are running with VM HA off. The usual prepare checks run again after the hooks, since they can take minutes; if prepare then fails, PostMaintenance undoes PreMaintenance. - Before PostMaintenance, cancel restarts a disconnected agent as it already does (kvm.ssh.to.agent) and waits for it; if it stays down the cancel is refused while the setting is on, and goes through without the hook once the setting is off. - A stale marker (host left maintenance some other way) is dropped when the next maintenance starts. - startRollingMaintenance gets the PostMigrate stage between entering maintenance and Maintenance, and calls maintain() without these hooks, so no stage runs twice. - Stage order documented in agent.properties. Signed-off-by: Brad House --- agent/conf/agent.properties | 4 + .../resource/RollingMaintenanceManager.java | 51 +++- .../com/cloud/resource/ResourceManager.java | 7 + .../cloud/resource/ResourceManagerImpl.java | 128 ++++++-- .../RollingMaintenanceManagerImpl.java | 285 +++++++++++++++++- .../resource/MockResourceManagerImpl.java | 5 + .../resource/ResourceManagerImplTest.java | 83 +++++ .../RollingMaintenanceManagerImplTest.java | 283 +++++++++++++++++ 8 files changed, 814 insertions(+), 32 deletions(-) diff --git a/agent/conf/agent.properties b/agent/conf/agent.properties index f91ef138dfc1..0c473a8de0e7 100644 --- a/agent/conf/agent.properties +++ b/agent/conf/agent.properties @@ -182,6 +182,10 @@ hypervisor.type=kvm # Sets the rolling maintenance hook scripts directory. # Default is null, however, can be used as /etc/cloudstack/agent/hooks.d +# One script per stage, named after it (optionally with .sh or .py): PreFlight, PreMaintenance, +# PostMigrate (host is empty), Maintenance, PostMaintenance. A missing script skips the stage. +# Exit 0 or 70 is success, anything else fails the stage; 70 from PreFlight or PreMaintenance also skips the host. +# The management server setting kvm.host.maintenance.run.hooks also runs them on plain host maintenance. #rolling.maintenance.hooks.dir= # Disables the rolling maintenance service execution. diff --git a/api/src/main/java/com/cloud/resource/RollingMaintenanceManager.java b/api/src/main/java/com/cloud/resource/RollingMaintenanceManager.java index d0c334feaa0a..fadea197d152 100644 --- a/api/src/main/java/com/cloud/resource/RollingMaintenanceManager.java +++ b/api/src/main/java/com/cloud/resource/RollingMaintenanceManager.java @@ -41,6 +41,20 @@ public interface RollingMaintenanceManager extends Configurable { "kvm.rolling.maintenance.wait.maintenance.timeout", "1800", "Timeout (in seconds) to wait for a host preparing to enter maintenance mode", true, ConfigKey.Scope.Global); + ConfigKey KvmHostMaintenanceRunHooks = new ConfigKey<>("Advanced", Boolean.class, + "kvm.host.maintenance.run.hooks", "false", + "Run the rolling maintenance hook scripts on KVM hosts (agent.properties: rolling.maintenance.hooks.dir) " + + "when a host is put into or taken out of maintenance with prepareHostForMaintenance and " + + "cancelHostMaintenance. Stages: PreFlight and PreMaintenance before VMs are moved off the host " + + "(a failure or exit code 70 refuses maintenance), PostMigrate once the host has reached " + + "Maintenance, PostMaintenance on cancel before the host is enabled again (failures of the last " + + "two raise an alert but do not change the host state; cancel needs the agent connected while " + + "this is enabled). Stages never overlap on a host. The Maintenance stage is not run and no " + + "payload argument is passed. A stage without a script is skipped. Each stage is limited by " + + "kvm.rolling.maintenance.stage.timeout.", + true, ConfigKey.Scope.Cluster); + + String HOST_MAINTENANCE_HOOKS_DETAIL = "maintenance.hooks"; class HostSkipped { private Host host; @@ -115,13 +129,15 @@ public void setOutputMsg(String outputMsg) { } enum Stage { - PreFlight, PreMaintenance, Maintenance, PostMaintenance; + PreFlight, PreMaintenance, PostMigrate, Maintenance, PostMaintenance; public Stage next() { switch (this) { case PreFlight: return PreMaintenance; case PreMaintenance: + return PostMigrate; + case PostMigrate: return Maintenance; case Maintenance: return PostMaintenance; @@ -143,4 +159,37 @@ enum ResourceType { */ Ternary, List>> startRollingMaintenance(StartRollingMaintenanceCmd cmd); Pair> getResourceTypeIdPair(StartRollingMaintenanceCmd cmd); + + /** + * Runs the PreFlight and PreMaintenance hooks on a host about to enter maintenance outside rolling maintenance, + * if {@link #KvmHostMaintenanceRunHooks} is enabled for its cluster. + * @return true if the hooks ran, false if they are disabled or already ran for this maintenance + * @throws CloudRuntimeException if the host is not Up, or a hook fails or asks to avoid maintenance + */ + boolean runPreMaintenanceHooks(Host host); + + /** + * Starts the PostMigrate hook in the background on a host that has just entered maintenance, + * if its maintenance was started with {@link #runPreMaintenanceHooks} and not cancelled since. + */ + void runPostMigrateHook(Host host); + + /** + * Runs the PostMaintenance hook on a host leaving maintenance, if its maintenance was started with + * {@link #runPreMaintenanceHooks}, and forgets that it was. A hook failure raises an alert and is not thrown. + * Waits up to the stage timeout for the agent to connect. + * @throws CloudRuntimeException if the host is not Up while the setting is still enabled, or another hook + * on the host does not finish in time + */ + void runPostMaintenanceHook(Host host); + + /** + * @return true if the host's current maintenance was started with {@link #runPreMaintenanceHooks} + */ + boolean isMaintenanceHooksActive(Host host); + + /** + * Forgets that the host's maintenance was started with {@link #runPreMaintenanceHooks}. + */ + void clearMaintenanceHooks(Host host); } diff --git a/engine/components-api/src/main/java/com/cloud/resource/ResourceManager.java b/engine/components-api/src/main/java/com/cloud/resource/ResourceManager.java index 4767e86e8ab8..3f11104928a5 100755 --- a/engine/components-api/src/main/java/com/cloud/resource/ResourceManager.java +++ b/engine/components-api/src/main/java/com/cloud/resource/ResourceManager.java @@ -27,6 +27,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; import com.cloud.gpu.VgpuProfileVO; import com.cloud.vm.VirtualMachine; +import org.apache.cloudstack.api.command.admin.host.PrepareForHostMaintenanceCmd; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.Configurable; @@ -132,6 +133,12 @@ public interface ResourceManager extends ResourceService, Configurable { public boolean maintain(final long hostId) throws AgentUnavailableException; + /** + * Prepares a host for maintenance; runMaintenanceHooks false skips the hooks of + * {@link RollingMaintenanceManager#KvmHostMaintenanceRunHooks}, for callers that run the stages themselves. + */ + Host maintain(PrepareForHostMaintenanceCmd cmd, boolean runMaintenanceHooks); + public boolean checkAndMaintain(final long hostId); @Override diff --git a/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java b/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java index e241339bfd6d..bcfcdfba7f6d 100755 --- a/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java +++ b/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java @@ -343,6 +343,8 @@ public void setDiscoverers(final List discoverers) { @Inject private AlertManager alertManager; @Inject + private RollingMaintenanceManager rollingMaintenanceManager; + @Inject private AnnotationService annotationService; @Inject private VolumeDao volumeDao; @@ -1440,6 +1442,10 @@ public Host cancelMaintenance(final CancelHostMaintenanceCmd cmd) { throw new CloudRuntimeException(String.format("Cannot perform cancelMaintenance when resource state is %s, host: %s", host.getResourceState(), host)); } + if (rollingMaintenanceManager.isMaintenanceHooksActive(host)) { + handleAgentIfNotConnected(host, hasTakenMigrationWork(host)); + rollingMaintenanceManager.runPostMaintenanceHook(host); + } processResourceEvent(ResourceListener.EVENT_CANCEL_MAINTENANCE_BEFORE, hostId); final boolean success = cancelMaintenance(hostId); processResourceEvent(ResourceListener.EVENT_CANCEL_MAINTENANCE_AFTER, hostId); @@ -1661,6 +1667,17 @@ public boolean maintain(final long hostId) throws AgentUnavailableException { @DB @ActionEvent(eventType = EventTypes.EVENT_MAINTENANCE_PREPARE, eventDescription = "prepare maintenance for host", async = true) public Host maintain(final PrepareForHostMaintenanceCmd cmd) { + return prepareForMaintenance(cmd, true); + } + + @Override + @DB + @ActionEvent(eventType = EventTypes.EVENT_MAINTENANCE_PREPARE, eventDescription = "prepare maintenance for host", async = true) + public Host maintain(final PrepareForHostMaintenanceCmd cmd, final boolean runMaintenanceHooks) { + return prepareForMaintenance(cmd, runMaintenanceHooks); + } + + private Host prepareForMaintenance(final PrepareForHostMaintenanceCmd cmd, final boolean runMaintenanceHooks) { final Long hostId = cmd.getId(); final HostVO host = _hostDao.findById(hostId); @@ -1674,6 +1691,7 @@ public Host maintain(final PrepareForHostMaintenanceCmd cmd) { if (SET_HOST_DOWN_TO_MAINTENANCE.valueIn(host.getDataCenterId()) && (host.getStatus() == Status.Down)) { if (host.getResourceState() == ResourceState.Enabled) { + rollingMaintenanceManager.clearMaintenanceHooks(host); _hostDao.updateResourceState(ResourceState.Enabled, ResourceState.Event.AdminAskMaintenance, ResourceState.PrepareForMaintenance, host); _hostDao.updateResourceState(ResourceState.PrepareForMaintenance, ResourceState.Event.InternalEnterMaintenance, ResourceState.Maintenance, host); return _hostDao.findById(hostId); @@ -1683,6 +1701,74 @@ public Host maintain(final PrepareForHostMaintenanceCmd cmd) { } } + checkHostCanEnterMaintenance(host); + final boolean hooksRan = runMaintenanceHooks && rollingMaintenanceManager.runPreMaintenanceHooks(host); + boolean prepared = false; + try { + if (hooksRan) { + final HostVO current = _hostDao.findById(hostId); + if (!ResourceState.canAttemptMaintenance(current.getResourceState())) { + throw new CloudRuntimeException("Host is already in state " + current.getResourceState() + ". Cannot recall for maintenance until resolved."); + } + checkHostCanEnterMaintenance(current); + } + processResourceEvent(ResourceListener.EVENT_PREPARE_MAINTENANCE_BEFORE, hostId); + if (maintain(hostId)) { + prepared = true; + processResourceEvent(ResourceListener.EVENT_PREPARE_MAINTENANCE_AFTER, hostId); + return _hostDao.findById(hostId); + } else { + throw new CloudRuntimeException(String.format("Unable to prepare for maintenance host %s", host)); + } + } catch (final AgentUnavailableException e) { + throw new CloudRuntimeException(String.format("Unable to prepare for maintenance host %s", host)); + } finally { + if (hooksRan && !prepared) { + undoPreMaintenanceHooks(hostId); + } + } + } + + /** + * The pre-maintenance hooks ran but the host did not enter maintenance; let the PostMaintenance hook undo them. + * If the host is in a maintenance state anyway (a concurrent request, or doMaintain moved it before failing), + * the hooks stay for that maintenance. + */ + private void undoPreMaintenanceHooks(final long hostId) { + try { + final HostVO current = _hostDao.findById(hostId); + if (current == null || ResourceState.isMaintenanceState(current.getResourceState())) { + return; + } + String error = null; + if (current.getStatus() != Status.Up) { + error = String.format("host is %s", current.getStatus()); + } else { + try { + rollingMaintenanceManager.runPostMaintenanceHook(current); + } catch (final CloudRuntimeException e) { + error = e.getMessage(); + } + } + if (error != null) { + final String subject = String.format("Could not undo the pre-maintenance hooks on host %s", current.getName()); + logger.error("{}: {}", subject, error); + alertManager.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, current.getDataCenterId(), current.getPodId(), subject, error); + rollingMaintenanceManager.clearMaintenanceHooks(current); + } + } catch (final RuntimeException e) { + logger.error("Could not undo the pre-maintenance hooks on host {}", hostId, e); + } + } + + private void checkHostCanEnterMaintenance(final HostVO host) { + final long hostId = host.getId(); + if (host.getResourceState().getNextState(ResourceState.Event.AdminAskMaintenance) == null) { + throw new CloudRuntimeException(String.format("Host %s in state %s cannot be put into maintenance", host, host.getResourceState())); + } + if (!_vmDao.listByHostId(hostId).isEmpty() && !HighAvailabilityManagerImpl.VmHaEnabled.valueIn(host.getDataCenterId())) { + throw new CloudRuntimeException(String.format("Cannot perform maintain for the host %s (%d) as there are running VMs on it and VM high availability manager is disabled", host.getName(), hostId)); + } if (_hostDao.countBy(host.getClusterId(), ResourceState.PrepareForMaintenance, ResourceState.ErrorInPrepareForMaintenance) > 0) { throw new CloudRuntimeException(String.format("There are other servers attempting migrations for maintenance. " + "Found hosts in PrepareForMaintenance OR ErrorInPrepareForMaintenance STATUS in cluster %s", @@ -1708,18 +1794,6 @@ public Host maintain(final PrepareForHostMaintenanceCmd cmd) { if (!_vmDao.findByHostInStates(hostId, State.Error, State.Unknown).isEmpty()) { throw new CloudRuntimeException("Host contains VMs in error/unknown/shutdown state. Please fix errors to proceed."); } - - try { - processResourceEvent(ResourceListener.EVENT_PREPARE_MAINTENANCE_BEFORE, hostId); - if (maintain(hostId)) { - processResourceEvent(ResourceListener.EVENT_PREPARE_MAINTENANCE_AFTER, hostId); - return _hostDao.findById(hostId); - } else { - throw new CloudRuntimeException(String.format("Unable to prepare for maintenance host %s", host)); - } - } catch (final AgentUnavailableException e) { - throw new CloudRuntimeException(String.format("Unable to prepare for maintenance host %s", host)); - } } protected boolean isMaintenanceLocalStrategyMigrate() { @@ -1874,7 +1948,13 @@ protected void configureVncAccessForKVMHostFailedMigrations(HostVO host, List vms = _haMgr.findTakenMigrationWork(); - for (final VMInstanceVO vm : vms) { - if (vm.getHostId() != null && vm.getHostId() == hostId) { - logger.warn("Unable to cancel migration because the vm is being migrated: {}, host {}", vm, host); - vms_migrating = true; - } - } - - handleAgentIfNotConnected(host, vms_migrating); + handleAgentIfNotConnected(host, hasTakenMigrationWork(host)); try { resourceStateTransitTo(host, ResourceState.Event.AdminCancelMaintenance, _nodeId); @@ -3950,6 +4021,17 @@ private boolean doCancelMaintenance(final long hostId) { } + private boolean hasTakenMigrationWork(final HostVO host) { + boolean vmsMigrating = false; + for (final VMInstanceVO vm : _haMgr.findTakenMigrationWork()) { + if (vm.getHostId() != null && vm.getHostId() == host.getId()) { + logger.warn("Unable to cancel migration because the vm is being migrated: {}, host {}", vm, host); + vmsMigrating = true; + } + } + return vmsMigrating; + } + /** * Handle agent (if available) if its not connected before cancelling maintenance. * Agent must be connected before cancelling maintenance. diff --git a/server/src/main/java/com/cloud/resource/RollingMaintenanceManagerImpl.java b/server/src/main/java/com/cloud/resource/RollingMaintenanceManagerImpl.java index 1e6ab9d0ffa2..0021add111ba 100644 --- a/server/src/main/java/com/cloud/resource/RollingMaintenanceManagerImpl.java +++ b/server/src/main/java/com/cloud/resource/RollingMaintenanceManagerImpl.java @@ -17,6 +17,7 @@ package com.cloud.resource; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; @@ -24,6 +25,9 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; import java.util.stream.Collectors; import javax.inject.Inject; @@ -36,6 +40,7 @@ import org.apache.cloudstack.api.command.admin.resource.StartRollingMaintenanceCmd; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.framework.config.ConfigKey; +import org.apache.cloudstack.managed.context.ManagedContextRunnable; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.ObjectUtils; @@ -53,11 +58,13 @@ import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.OperationTimedoutException; +import com.cloud.host.DetailVO; import com.cloud.host.Host; import com.cloud.host.HostTagVO; import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.HostDao; +import com.cloud.host.dao.HostDetailsDao; import com.cloud.host.dao.HostTagsDao; import com.cloud.hypervisor.Hypervisor; import com.cloud.org.Cluster; @@ -68,6 +75,8 @@ import com.cloud.utils.StringUtils; import com.cloud.utils.Ternary; import com.cloud.utils.component.ManagerBase; +import com.cloud.utils.concurrency.NamedThreadFactory; +import com.cloud.utils.db.GlobalLock; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.VMInstanceDetailVO; import com.cloud.vm.VMInstanceVO; @@ -99,6 +108,11 @@ public class RollingMaintenanceManagerImpl extends ManagerBase implements Rollin private HostTagsDao hostTagsDao; @Inject private AlertManager alertManager; + @Inject + private HostDetailsDao hostDetailsDao; + + private final ExecutorService hookExecutor = Executors.newCachedThreadPool(new NamedThreadFactory("HostMaintenanceHook")); + protected List _affinityProcessors; @@ -124,6 +138,12 @@ public boolean configure(String name, Map params) throws Configu return true; } + @Override + public boolean stop() { + hookExecutor.shutdown(); + return true; + } + private void updateCluster(long clusterId, String allocationState) { Cluster cluster = resourceManager.getCluster(clusterId); if (cluster == null) { @@ -324,8 +344,12 @@ private Ternary startRollingMaintenanceHostInCluster(C } Date startTime = new Date(); + clearMaintenanceHooks(host); putHostIntoMaintenance(host); - result = performMaintenanceStageOnHost(host, timeout, payload, forced, hostsToAvoidMaintenance, hostsSkipped); + result = performMaintenanceStageOnHost(host, Stage.PostMigrate, timeout, payload, forced, hostsSkipped); + if (!result.first() && !result.second()) { + result = performMaintenanceStageOnHost(host, Stage.Maintenance, timeout, payload, forced, hostsSkipped); + } if (result.first() || result.second()) { cancelHostMaintenance(host); return result; @@ -377,18 +401,18 @@ private void cancelHostMaintenance(Host host) { } /** - * Perform Maintenance stage on host + * Perform a stage on a host that is in maintenance (PostMigrate or Maintenance) * @return tuple: (FAIL, SKIP, DETAILS), where: * - FAIL: True if rolling maintenance must fail * - SKIP: True if host must be skipped * - DETAILS: Information retrieved by the host after executing the stage * @throws InterruptedException */ - private Ternary performMaintenanceStageOnHost(Host host, int timeout, String payload, Boolean forced, Map hostsToAvoidMaintenance, List hostsSkipped) throws InterruptedException { - Ternary result = performStageOnHost(host, Stage.Maintenance, timeout, payload, forced); + private Ternary performMaintenanceStageOnHost(Host host, Stage stage, int timeout, String payload, Boolean forced, List hostsSkipped) throws InterruptedException { + Ternary result = performStageOnHost(host, stage, timeout, payload, forced); if (!result.first()) { if (forced) { - String msg = "Maintenance script failed: " + result.second(); + String msg = stage + " script failed: " + result.second(); hostsSkipped.add(new HostSkipped(host, msg)); return new Ternary<>(true, true, msg); } @@ -407,7 +431,7 @@ private void putHostIntoMaintenance(Host host) throws InterruptedException, Agen logger.debug(String.format("Trying to set %s into maintenance", host)); PrepareForHostMaintenanceCmd cmd = new PrepareForHostMaintenanceCmd(); cmd.setId(host.getId()); - resourceManager.maintain(cmd); + resourceManager.maintain(cmd, false); waitForHostInMaintenance(host.getId()); } @@ -529,7 +553,24 @@ private Ternary performStageOnHost(Host host, Stage st * - DETAILS: Information retrieved by the host after executing the stage * - AVOID_MAINTENANCE: True if maintenance stage must be avoided */ - private Ternary sendRollingMaintenanceCommandToHost(Host host, Stage stage, + protected Ternary sendRollingMaintenanceCommandToHost(Host host, Stage stage, + int timeout, String payload) throws InterruptedException { + GlobalLock lock = getHooksLock(host); + try { + if (!lock.lock(getHooksLockTimeout())) { + return new Ternary<>(false, "Timed out waiting for another maintenance hook to finish on host " + host.getUuid(), false); + } + try { + return doSendRollingMaintenanceCommandToHost(host, stage, timeout, payload); + } finally { + lock.unlock(); + } + } finally { + lock.releaseRef(); + } + } + + protected Ternary doSendRollingMaintenanceCommandToHost(Host host, Stage stage, int timeout, String payload) throws InterruptedException { boolean completed = false; Answer answer = null; @@ -777,6 +818,233 @@ private void waitForHostInMaintenance(long hostId) throws CloudRuntimeException, logger.debug("Host " + host.getUuid() + "(" + host.getName() + ") is in maintenance"); } + protected boolean isHostMaintenanceHooksEnabled(Host host) { + return host.getHypervisorType() == Hypervisor.HypervisorType.KVM && host.getClusterId() != null && + Boolean.TRUE.equals(KvmHostMaintenanceRunHooks.valueIn(host.getClusterId())); + } + + /** + * Run a hook stage on a host outside rolling maintenance; the caller holds the hooks lock + * @return tuple: (SUCCESS, DETAILS, AVOID_MAINTENANCE), as {@link #sendRollingMaintenanceCommandToHost} + */ + protected Ternary runHookOnHost(Host host, Stage stage) { + logger.info("Running maintenance hook {} on {}", stage, host); + try { + return doSendRollingMaintenanceCommandToHost(host, stage, KvmRollingMaintenanceStageTimeout.value(), null); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return new Ternary<>(false, "Interrupted while running stage " + stage, false); + } catch (RuntimeException e) { + logger.error("Error running maintenance hook {} on {}", stage, host, e); + return new Ternary<>(false, e.getMessage(), false); + } + } + + private void alert(Host host, String subject, String body) { + logger.error("{}: {}", subject, body); + alertManager.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), subject, body); + } + + private void runHookOrAlert(Host host, Stage stage) { + Ternary result = runHookOnHost(host, stage); + if (result.first()) { + logger.info("Maintenance hook {} finished on {}: {}", stage, host, result.second()); + return; + } + alert(host, String.format("Maintenance hook %s failed on host %s", stage, host.getName()), + String.format("Stage %s failed on host %s: %s", stage, host.getUuid(), result.second())); + } + + private DetailVO findHooksDetail(Host host) { + return hostDetailsDao.findDetail(host.getId(), HOST_MAINTENANCE_HOOKS_DETAIL); + } + + /** + * Cluster-wide lock held while a hook runs, so that two stages never run on the host at the same time + */ + protected GlobalLock getHooksLock(Host host) { + return GlobalLock.getInternLock("host.maintenance.hooks." + host.getId()); + } + + private int getHooksLockTimeout() { + long seconds = 3L * KvmRollingMaintenanceStageTimeout.value() + KvmRollingMaintenancePingInterval.value(); + return (int) Math.min(seconds, Integer.MAX_VALUE / 1000); + } + + /** + * Run body holding the host's hooks lock + * @return false if the lock could not be taken within timeoutSeconds + */ + private boolean withHooksLock(Host host, int timeoutSeconds, Runnable body) { + GlobalLock lock = getHooksLock(host); + try { + if (!lock.lock(timeoutSeconds)) { + return false; + } + try { + body.run(); + } finally { + lock.unlock(); + } + return true; + } finally { + lock.releaseRef(); + } + } + + @Override + public boolean runPreMaintenanceHooks(Host host) { + DetailVO detail = findHooksDetail(host); + boolean inMaintenance = ResourceState.isMaintenanceState(host.getResourceState()); + if (!isHostMaintenanceHooksEnabled(host)) { + if (detail != null && !inMaintenance) { + clearMaintenanceHooks(host); + } + return false; + } + if (inMaintenance && detail != null) { + logger.debug("Pre-maintenance hooks already ran on {}", host); + return false; + } + if (host.getStatus() != Status.Up) { + throw new CloudRuntimeException(String.format("%s is %s, cannot run the maintenance hooks required by %s", + host, host.getStatus(), KvmHostMaintenanceRunHooks.key())); + } + boolean locked = withHooksLock(host, 1, () -> { + for (Stage stage : Arrays.asList(Stage.PreFlight, Stage.PreMaintenance)) { + Ternary result = runHookOnHost(host, stage); + if (!result.first()) { + throw new CloudRuntimeException(String.format("Maintenance hook %s failed on %s: %s", stage, host, result.second())); + } + if (result.third()) { + throw new CloudRuntimeException(String.format("Maintenance hook %s on %s refused maintenance: %s", stage, host, result.second())); + } + } + hostDetailsDao.persist(host.getId(), Map.of(HOST_MAINTENANCE_HOOKS_DETAIL, String.valueOf(System.currentTimeMillis()))); + }); + if (!locked) { + throw new CloudRuntimeException(String.format("Maintenance hooks are already running on %s", host)); + } + return true; + } + + @Override + public void runPostMigrateHook(Host host) { + DetailVO detail = findHooksDetail(host); + if (detail == null) { + return; + } + String maintenanceId = detail.getValue(); + try { + hookExecutor.submit(new ManagedContextRunnable() { + @Override + protected void runInContext() { + try { + runPostMigrateHookWithLock(host, maintenanceId); + } catch (RuntimeException e) { + logger.error("Error running maintenance hook {} on {}", Stage.PostMigrate, host, e); + alert(host, String.format("Maintenance hook %s failed on host %s", Stage.PostMigrate, host.getName()), e.getMessage()); + } + } + }); + } catch (RejectedExecutionException e) { + alert(host, String.format("Maintenance hook %s not run on host %s", Stage.PostMigrate, host.getName()), + "The management server is shutting down"); + } + } + + /** + * @param maintenanceId marker value of the maintenance that reached Maintenance, so that a task that waited out a + * cancel never runs for a later maintenance + */ + protected void runPostMigrateHookWithLock(Host host, String maintenanceId) { + boolean locked = withHooksLock(host, getHooksLockTimeout(), () -> { + DetailVO detail = findHooksDetail(host); + HostVO current = hostDao.findById(host.getId()); + if (detail == null || !detail.getValue().equals(maintenanceId) || current == null || + current.getResourceState() != ResourceState.Maintenance) { + logger.debug("{} is no longer in that maintenance, not running hook {}", host, Stage.PostMigrate); + return; + } + if (current.getStatus() != Status.Up) { + alert(host, String.format("Maintenance hook %s not run on host %s", Stage.PostMigrate, host.getName()), + String.format("Host %s is %s", host.getUuid(), current.getStatus())); + return; + } + runHookOrAlert(current, Stage.PostMigrate); + }); + if (!locked) { + alert(host, String.format("Maintenance hook %s not run on host %s", Stage.PostMigrate, host.getName()), + "Timed out waiting for another maintenance hook to finish"); + } + } + + @Override + public boolean isMaintenanceHooksActive(Host host) { + return findHooksDetail(host) != null; + } + + /** + * Wait for the agent to connect, e.g. after a reboot during maintenance or an agent restart + */ + protected HostVO waitForHostUp(Host host) { + long timeout = KvmRollingMaintenanceStageTimeout.value() * 1000L; + long step = Math.max(1, KvmRollingMaintenancePingInterval.value()) * 1000L; + HostVO current = hostDao.findById(host.getId()); + for (long waited = 0; current != null && current.getStatus() != Status.Up && waited < timeout; waited += step) { + try { + Thread.sleep(step); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new CloudRuntimeException("Interrupted while waiting for " + host + " to connect"); + } + current = hostDao.findById(host.getId()); + } + return current; + } + + @Override + public void runPostMaintenanceHook(Host host) { + if (findHooksDetail(host) == null) { + return; + } + waitForHostUp(host); + boolean locked = withHooksLock(host, getHooksLockTimeout(), () -> { + if (findHooksDetail(host) == null) { + return; + } + HostVO current = hostDao.findById(host.getId()); + if (current == null) { + return; + } + if (current.getStatus() == Status.Up) { + runHookOrAlert(current, Stage.PostMaintenance); + if (Thread.currentThread().isInterrupted()) { + throw new CloudRuntimeException(String.format("Interrupted while running the %s maintenance hook on %s", Stage.PostMaintenance, host)); + } + } else if (isHostMaintenanceHooksEnabled(current)) { + throw new CloudRuntimeException(String.format("%s is %s; the %s maintenance hook needs its agent. Connect the agent, " + + "or disable %s for the cluster to leave maintenance without the hook", current, current.getStatus(), + Stage.PostMaintenance, KvmHostMaintenanceRunHooks.key())); + } else { + alert(host, String.format("Maintenance hook %s not run on host %s", Stage.PostMaintenance, host.getName()), + String.format("Host %s is not Up, stage %s was skipped", host.getUuid(), Stage.PostMaintenance)); + } + clearMaintenanceHooks(host); + }); + if (!locked) { + throw new CloudRuntimeException(String.format("A maintenance hook is still running on %s, try again later", host)); + } + } + + @Override + public void clearMaintenanceHooks(Host host) { + DetailVO detail = findHooksDetail(host); + if (detail != null) { + hostDetailsDao.remove(detail.getId()); + } + } + @Override public String getConfigComponentName() { return RollingMaintenanceManagerImpl.class.getSimpleName(); @@ -784,6 +1052,7 @@ public String getConfigComponentName() { @Override public ConfigKey[] getConfigKeys() { - return new ConfigKey[] {KvmRollingMaintenanceStageTimeout, KvmRollingMaintenancePingInterval, KvmRollingMaintenanceWaitForMaintenanceTimeout}; + return new ConfigKey[] {KvmRollingMaintenanceStageTimeout, KvmRollingMaintenancePingInterval, KvmRollingMaintenanceWaitForMaintenanceTimeout, + KvmHostMaintenanceRunHooks}; } } diff --git a/server/src/test/java/com/cloud/resource/MockResourceManagerImpl.java b/server/src/test/java/com/cloud/resource/MockResourceManagerImpl.java index 01be6db73d88..8a1b5f378231 100755 --- a/server/src/test/java/com/cloud/resource/MockResourceManagerImpl.java +++ b/server/src/test/java/com/cloud/resource/MockResourceManagerImpl.java @@ -152,6 +152,11 @@ public Host maintain(final PrepareForHostMaintenanceCmd cmd) { return null; } + @Override + public Host maintain(final PrepareForHostMaintenanceCmd cmd, final boolean runMaintenanceHooks) { + return null; + } + @Override public Host declareHostAsDegraded(DeclareHostAsDegradedCmd cmd) { return null; diff --git a/server/src/test/java/com/cloud/resource/ResourceManagerImplTest.java b/server/src/test/java/com/cloud/resource/ResourceManagerImplTest.java index b9da7390566c..5a7c53f4394b 100644 --- a/server/src/test/java/com/cloud/resource/ResourceManagerImplTest.java +++ b/server/src/test/java/com/cloud/resource/ResourceManagerImplTest.java @@ -29,6 +29,7 @@ import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.HostPodDao; import com.cloud.event.ActionEventUtils; +import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.ha.HighAvailabilityManager; import com.cloud.host.Host; @@ -55,7 +56,9 @@ import com.cloud.vm.dao.VMInstanceDao; import com.trilead.ssh2.Connection; import org.apache.cloudstack.api.command.admin.host.CancelHostAsDegradedCmd; +import org.apache.cloudstack.api.command.admin.host.CancelHostMaintenanceCmd; import org.apache.cloudstack.api.command.admin.host.DeclareHostAsDegradedCmd; +import org.apache.cloudstack.api.command.admin.host.PrepareForHostMaintenanceCmd; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; import org.apache.cloudstack.framework.config.ConfigKey; @@ -68,6 +71,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.BDDMockito; +import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockedConstruction; @@ -129,6 +133,8 @@ public class ResourceManagerImplTest { private PrimaryDataStoreDao storagePoolDao; @Mock private StoragePoolHostDao storagePoolHostDao; + @Mock + private RollingMaintenanceManager rollingMaintenanceManager; @Spy @InjectMocks @@ -283,6 +289,83 @@ public void testCheckAndMaintainEnterMaintenanceModeNoVms() throws NoTransitionE Assert.assertTrue(enterMaintenanceMode); } + @Test + public void testSetHostIntoMaintenanceStartsPostMigrateHook() throws NoTransitionException { + Mockito.doReturn(true).when(resourceManager).resourceStateTransitTo(eq(host), eq(InternalEnterMaintenance), anyLong()); + Assert.assertTrue(resourceManager.setHostIntoMaintenance(host)); + verify(rollingMaintenanceManager).runPostMigrateHook(host); + } + + @Test + public void testCancelMaintenanceRunsPostMaintenanceHookFirst() { + when(host.getResourceState()).thenReturn(ResourceState.Maintenance); + Mockito.doReturn(true).when(resourceManager).cancelMaintenance(hostId); + when(rollingMaintenanceManager.isMaintenanceHooksActive(host)).thenReturn(true); + CancelHostMaintenanceCmd cmd = Mockito.mock(CancelHostMaintenanceCmd.class); + when(cmd.getId()).thenReturn(hostId); + + resourceManager.cancelMaintenance(cmd); + + InOrder inOrder = Mockito.inOrder(rollingMaintenanceManager, resourceManager); + inOrder.verify(rollingMaintenanceManager).runPostMaintenanceHook(host); + inOrder.verify(resourceManager).cancelMaintenance(hostId); + } + + @Test + public void testMaintainRefusedBeforeHooksWhenStateCannotEnterMaintenance() { + PrepareForHostMaintenanceCmd cmd = Mockito.mock(PrepareForHostMaintenanceCmd.class); + when(cmd.getId()).thenReturn(hostId); + when(host.getResourceState()).thenReturn(ResourceState.Disabled); + + Assert.assertThrows(CloudRuntimeException.class, () -> resourceManager.maintain(cmd, true)); + + verify(rollingMaintenanceManager, never()).runPreMaintenanceHooks(any()); + } + + @Test + public void testMaintainUndoesPreMaintenanceHooksWhenPrepareFails() throws AgentUnavailableException { + PrepareForHostMaintenanceCmd cmd = Mockito.mock(PrepareForHostMaintenanceCmd.class); + when(cmd.getId()).thenReturn(hostId); + when(rollingMaintenanceManager.runPreMaintenanceHooks(host)).thenReturn(true); + Mockito.doReturn(false).when(resourceManager).maintain(hostId); + + Assert.assertThrows(CloudRuntimeException.class, () -> resourceManager.maintain(cmd, true)); + + verify(rollingMaintenanceManager).runPostMaintenanceHook(host); + } + + @Test + public void testCancelMaintenanceStopsWhenPostMaintenanceHookThrows() { + when(host.getResourceState()).thenReturn(ResourceState.Maintenance); + when(rollingMaintenanceManager.isMaintenanceHooksActive(host)).thenReturn(true); + Mockito.doThrow(new CloudRuntimeException("agent not connected")).when(rollingMaintenanceManager).runPostMaintenanceHook(host); + CancelHostMaintenanceCmd cmd = Mockito.mock(CancelHostMaintenanceCmd.class); + when(cmd.getId()).thenReturn(hostId); + + Assert.assertThrows(CloudRuntimeException.class, () -> resourceManager.cancelMaintenance(cmd)); + + verify(resourceManager, never()).cancelMaintenance(hostId); + } + + @Test + public void testMaintainWithoutHooksSkipsThem() throws AgentUnavailableException { + PrepareForHostMaintenanceCmd cmd = Mockito.mock(PrepareForHostMaintenanceCmd.class); + when(cmd.getId()).thenReturn(hostId); + Mockito.doReturn(true).when(resourceManager).maintain(hostId); + + resourceManager.maintain(cmd, false); + + verify(rollingMaintenanceManager, never()).runPreMaintenanceHooks(any()); + verify(rollingMaintenanceManager, never()).runPostMaintenanceHook(any()); + } + + @Test + public void testSetHostIntoMaintenanceNoPostMigrateHookWhenTransitionLost() throws NoTransitionException { + Mockito.doReturn(false).when(resourceManager).resourceStateTransitTo(eq(host), eq(InternalEnterMaintenance), anyLong()); + resourceManager.setHostIntoMaintenance(host); + verify(rollingMaintenanceManager, never()).runPostMigrateHook(any()); + } + @Test public void testCheckAndMaintainProceedsWithPrepareForMaintenanceRunningVms() throws NoTransitionException { // Test proceeding through with no events if pending migrating works / retries left. diff --git a/server/src/test/java/com/cloud/resource/RollingMaintenanceManagerImplTest.java b/server/src/test/java/com/cloud/resource/RollingMaintenanceManagerImplTest.java index 586f2b58ecae..6d42dd6a2a8a 100644 --- a/server/src/test/java/com/cloud/resource/RollingMaintenanceManagerImplTest.java +++ b/server/src/test/java/com/cloud/resource/RollingMaintenanceManagerImplTest.java @@ -17,15 +17,19 @@ package com.cloud.resource; +import com.cloud.alert.AlertManager; +import com.cloud.host.DetailVO; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.HostDao; +import com.cloud.host.dao.HostDetailsDao; import com.cloud.hypervisor.Hypervisor; import com.cloud.org.Cluster; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.utils.Ternary; +import com.cloud.utils.db.GlobalLock; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.VMInstanceDetailVO; import com.cloud.vm.VMInstanceVO; @@ -68,6 +72,10 @@ public class RollingMaintenanceManagerImplTest { ServiceOfferingDao serviceOfferingDao; @Mock VMInstanceDetailsDao vmInstanceDetailsDao; + @Mock + HostDetailsDao hostDetailsDao; + @Mock + AlertManager alertManager; @Spy @InjectMocks @@ -232,4 +240,279 @@ public void testGetComputeResourcesCpuSpeedAndRamSize_ForCustomOffering() { Assert.assertEquals(1000, cpuSpeedAndRamSize.second().intValue()); Assert.assertEquals(1024, cpuSpeedAndRamSize.third().intValue()); } + + private void mockHook(RollingMaintenanceManager.Stage stage, boolean success, boolean avoidMaintenance) { + Mockito.doReturn(new Ternary<>(success, stage + " output", avoidMaintenance)).when(manager).runHookOnHost(host1, stage); + } + + private DetailVO mockHooksDetail(String value) { + DetailVO detail = new DetailVO(hostId1, RollingMaintenanceManager.HOST_MAINTENANCE_HOOKS_DETAIL, value); + Mockito.when(hostDetailsDao.findDetail(hostId1, RollingMaintenanceManager.HOST_MAINTENANCE_HOOKS_DETAIL)).thenReturn(detail); + return detail; + } + + private GlobalLock mockHooksLock(boolean acquired) { + GlobalLock lock = Mockito.mock(GlobalLock.class); + Mockito.when(lock.lock(Mockito.anyInt())).thenReturn(acquired); + Mockito.doReturn(lock).when(manager).getHooksLock(host1); + return lock; + } + + private void verifyAlert(int times) { + Mockito.verify(alertManager, Mockito.times(times)).sendAlert(Mockito.any(), Mockito.anyLong(), Mockito.any(), + Mockito.anyString(), Mockito.anyString()); + } + + @Test + public void testRunPreMaintenanceHooksDisabled() { + Mockito.doReturn(false).when(manager).isHostMaintenanceHooksEnabled(host1); + Assert.assertFalse(manager.runPreMaintenanceHooks(host1)); + Mockito.verify(manager, Mockito.never()).runHookOnHost(Mockito.any(), Mockito.any()); + Mockito.verify(hostDetailsDao, Mockito.never()).persist(Mockito.anyLong(), Mockito.anyMap()); + } + + @Test + public void testRunPreMaintenanceHooksDisabledDropsStaleDetail() { + Mockito.when(host1.getId()).thenReturn(hostId1); + Mockito.doReturn(false).when(manager).isHostMaintenanceHooksEnabled(host1); + mockHooksDetail("true"); + Assert.assertFalse(manager.runPreMaintenanceHooks(host1)); + Mockito.verify(hostDetailsDao).remove(Mockito.anyLong()); + } + + @Test + public void testRunPreMaintenanceHooksRunAgainWhenMaintenanceHasNoMarker() { + Mockito.when(host1.getId()).thenReturn(hostId1); + Mockito.when(host1.getResourceState()).thenReturn(ResourceState.ErrorInMaintenance); + Mockito.doReturn(true).when(manager).isHostMaintenanceHooksEnabled(host1); + mockHooksLock(true); + mockHook(RollingMaintenanceManager.Stage.PreFlight, true, false); + mockHook(RollingMaintenanceManager.Stage.PreMaintenance, true, false); + + Assert.assertTrue(manager.runPreMaintenanceHooks(host1)); + Mockito.verify(hostDetailsDao).persist(Mockito.eq(hostId1), Mockito.anyMap()); + } + + @Test + public void testRunPreMaintenanceHooksSuccess() { + Mockito.when(host1.getId()).thenReturn(hostId1); + Mockito.doReturn(true).when(manager).isHostMaintenanceHooksEnabled(host1); + GlobalLock lock = mockHooksLock(true); + mockHook(RollingMaintenanceManager.Stage.PreFlight, true, false); + mockHook(RollingMaintenanceManager.Stage.PreMaintenance, true, false); + + Assert.assertTrue(manager.runPreMaintenanceHooks(host1)); + + Mockito.verify(manager).runHookOnHost(host1, RollingMaintenanceManager.Stage.PreFlight); + Mockito.verify(manager).runHookOnHost(host1, RollingMaintenanceManager.Stage.PreMaintenance); + Mockito.verify(hostDetailsDao).persist(Mockito.eq(hostId1), Mockito.anyMap()); + Mockito.verify(lock).unlock(); + Mockito.verify(lock).releaseRef(); + } + + @Test + public void testRunPreMaintenanceHooksFailureRefusesMaintenance() { + Mockito.doReturn(true).when(manager).isHostMaintenanceHooksEnabled(host1); + GlobalLock lock = mockHooksLock(true); + mockHook(RollingMaintenanceManager.Stage.PreFlight, false, false); + + Assert.assertThrows(CloudRuntimeException.class, () -> manager.runPreMaintenanceHooks(host1)); + + Mockito.verify(manager, Mockito.never()).runHookOnHost(host1, RollingMaintenanceManager.Stage.PreMaintenance); + Mockito.verify(hostDetailsDao, Mockito.never()).persist(Mockito.anyLong(), Mockito.anyMap()); + Mockito.verify(lock).unlock(); + } + + @Test + public void testRunPreMaintenanceHooksAvoidMaintenanceRefusesMaintenance() { + Mockito.doReturn(true).when(manager).isHostMaintenanceHooksEnabled(host1); + mockHooksLock(true); + mockHook(RollingMaintenanceManager.Stage.PreFlight, true, false); + mockHook(RollingMaintenanceManager.Stage.PreMaintenance, true, true); + + Assert.assertThrows(CloudRuntimeException.class, () -> manager.runPreMaintenanceHooks(host1)); + + Mockito.verify(hostDetailsDao, Mockito.never()).persist(Mockito.anyLong(), Mockito.anyMap()); + } + + @Test + public void testRunPreMaintenanceHooksRefusedWhileOtherHookRuns() { + Mockito.doReturn(true).when(manager).isHostMaintenanceHooksEnabled(host1); + GlobalLock lock = mockHooksLock(false); + + Assert.assertThrows(CloudRuntimeException.class, () -> manager.runPreMaintenanceHooks(host1)); + + Mockito.verify(manager, Mockito.never()).runHookOnHost(Mockito.any(), Mockito.any()); + Mockito.verify(lock, Mockito.never()).unlock(); + Mockito.verify(lock).releaseRef(); + } + + @Test + public void testRunPreMaintenanceHooksNotRepeatedWhileInMaintenance() { + Mockito.when(host1.getId()).thenReturn(hostId1); + Mockito.when(host1.getResourceState()).thenReturn(ResourceState.ErrorInMaintenance); + Mockito.doReturn(true).when(manager).isHostMaintenanceHooksEnabled(host1); + mockHooksDetail("true"); + + Assert.assertFalse(manager.runPreMaintenanceHooks(host1)); + + Mockito.verify(manager, Mockito.never()).runHookOnHost(Mockito.any(), Mockito.any()); + } + + @Test + public void testRunPreMaintenanceHooksRefusedWhenHostNotUp() { + Mockito.when(host1.getStatus()).thenReturn(Status.Disconnected); + Mockito.doReturn(true).when(manager).isHostMaintenanceHooksEnabled(host1); + + Assert.assertThrows(CloudRuntimeException.class, () -> manager.runPreMaintenanceHooks(host1)); + + Mockito.verify(manager, Mockito.never()).runHookOnHost(Mockito.any(), Mockito.any()); + } + + @Test + public void testRunPostMigrateHookNotStartedWithoutPreMaintenance() { + Mockito.when(host1.getId()).thenReturn(hostId1); + manager.runPostMigrateHook(host1); + Mockito.verify(manager, Mockito.never()).runPostMigrateHookWithLock(Mockito.any(), Mockito.any()); + } + + @Test + public void testRunPostMigrateHookFailureRaisesAlert() throws Exception { + Mockito.when(host1.getId()).thenReturn(hostId1); + mockHooksDetail("1"); + GlobalLock lock = mockHooksLock(true); + mockHook(RollingMaintenanceManager.Stage.PostMigrate, false, false); + Mockito.when(host1.getResourceState()).thenReturn(ResourceState.Maintenance); + manager.configure("RollingMaintenanceManager", Collections.emptyMap()); + try { + manager.runPostMigrateHook(host1); + Mockito.verify(alertManager, Mockito.timeout(5000)).sendAlert(Mockito.any(), Mockito.anyLong(), Mockito.any(), + Mockito.anyString(), Mockito.anyString()); + Mockito.verify(lock, Mockito.timeout(5000)).releaseRef(); + } finally { + manager.stop(); + } + Mockito.verify(lock).unlock(); + } + + @Test + public void testRunPostMigrateHookSkippedForLaterMaintenance() { + Mockito.when(host1.getId()).thenReturn(hostId1); + Mockito.when(host1.getResourceState()).thenReturn(ResourceState.Maintenance); + mockHooksDetail("2"); + mockHooksLock(true); + + manager.runPostMigrateHookWithLock(host1, "1"); + + Mockito.verify(manager, Mockito.never()).runHookOnHost(Mockito.any(), Mockito.any()); + } + + @Test + public void testRunPostMigrateHookSkippedWhenHostLeftMaintenance() { + Mockito.when(host1.getId()).thenReturn(hostId1); + mockHooksDetail("1"); + mockHooksLock(true); + + manager.runPostMigrateHookWithLock(host1, "1"); + + Mockito.verify(manager, Mockito.never()).runHookOnHost(Mockito.any(), Mockito.any()); + } + + @Test + public void testRunPostMaintenanceHookNotRunWithoutPreMaintenance() { + Mockito.when(host1.getId()).thenReturn(hostId1); + manager.runPostMaintenanceHook(host1); + Mockito.verify(manager, Mockito.never()).runHookOnHost(Mockito.any(), Mockito.any()); + } + + @Test + public void testRunPostMaintenanceHookRunsAndClearsMarker() { + Mockito.when(host1.getId()).thenReturn(hostId1); + Mockito.doReturn(host1).when(manager).waitForHostUp(host1); + mockHooksDetail("1"); + GlobalLock lock = mockHooksLock(true); + mockHook(RollingMaintenanceManager.Stage.PostMaintenance, true, false); + + manager.runPostMaintenanceHook(host1); + + Mockito.verify(manager).runHookOnHost(host1, RollingMaintenanceManager.Stage.PostMaintenance); + Mockito.verify(hostDetailsDao).remove(Mockito.anyLong()); + Mockito.verify(lock).unlock(); + verifyAlert(0); + } + + @Test + public void testRunPostMaintenanceHookFailureRaisesAlert() { + Mockito.when(host1.getId()).thenReturn(hostId1); + Mockito.doReturn(host1).when(manager).waitForHostUp(host1); + mockHooksDetail("true"); + mockHooksLock(true); + mockHook(RollingMaintenanceManager.Stage.PostMaintenance, false, false); + + manager.runPostMaintenanceHook(host1); + + verifyAlert(1); + } + + @Test + public void testRunPostMaintenanceHookWaitTimeoutRefusesCancel() { + Mockito.when(host1.getId()).thenReturn(hostId1); + mockHooksDetail("true"); + mockHooksLock(false); + + Assert.assertThrows(CloudRuntimeException.class, () -> manager.runPostMaintenanceHook(host1)); + + Mockito.verify(manager, Mockito.never()).runHookOnHost(Mockito.any(), Mockito.any()); + } + + @Test + public void testRunPostMaintenanceHookHostNotUpRefusesCancelWhileEnabled() { + Mockito.when(host1.getId()).thenReturn(hostId1); + Mockito.doReturn(host1).when(manager).waitForHostUp(host1); + mockHooksLock(true); + Mockito.when(host1.getStatus()).thenReturn(Status.Down); + Mockito.doReturn(true).when(manager).isHostMaintenanceHooksEnabled(host1); + mockHooksDetail("true"); + + Assert.assertThrows(CloudRuntimeException.class, () -> manager.runPostMaintenanceHook(host1)); + + Mockito.verify(manager, Mockito.never()).runHookOnHost(Mockito.any(), Mockito.any()); + } + + @Test + public void testRunPostMaintenanceHookHostNotUpSkippedWhenDisabled() { + Mockito.when(host1.getId()).thenReturn(hostId1); + Mockito.doReturn(host1).when(manager).waitForHostUp(host1); + mockHooksLock(true); + Mockito.when(host1.getStatus()).thenReturn(Status.Down); + Mockito.doReturn(false).when(manager).isHostMaintenanceHooksEnabled(host1); + mockHooksDetail("true"); + + manager.runPostMaintenanceHook(host1); + + Mockito.verify(manager, Mockito.never()).runHookOnHost(Mockito.any(), Mockito.any()); + verifyAlert(1); + } + + @Test + public void testRunHookOnHostReportsUnexpectedErrorAsFailure() throws InterruptedException { + Mockito.doThrow(new ClassCastException("unexpected answer")).when(manager).doSendRollingMaintenanceCommandToHost( + Mockito.eq(host1), Mockito.any(), Mockito.anyInt(), Mockito.any()); + Ternary result = manager.runHookOnHost(host1, RollingMaintenanceManager.Stage.PostMigrate); + Assert.assertFalse(result.first()); + } + + @Test + public void testClearMaintenanceHooks() { + Mockito.when(host1.getId()).thenReturn(hostId1); + mockHooksDetail("true"); + manager.clearMaintenanceHooks(host1); + Mockito.verify(hostDetailsDao).remove(Mockito.anyLong()); + } + + @Test + public void testStageOrder() { + Assert.assertEquals(RollingMaintenanceManager.Stage.PostMigrate, RollingMaintenanceManager.Stage.PreMaintenance.next()); + Assert.assertEquals(RollingMaintenanceManager.Stage.Maintenance, RollingMaintenanceManager.Stage.PostMigrate.next()); + } }