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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions agent/conf/agent.properties
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Boolean> 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;
Expand Down Expand Up @@ -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;
Expand All @@ -143,4 +159,37 @@ enum ResourceType {
*/
Ternary<Boolean, String, Pair<List<HostUpdated>, List<HostSkipped>>> startRollingMaintenance(StartRollingMaintenanceCmd cmd);
Pair<ResourceType, List<Long>> 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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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
Expand Down
128 changes: 105 additions & 23 deletions server/src/main/java/com/cloud/resource/ResourceManagerImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,8 @@ public void setDiscoverers(final List<? extends Discoverer> discoverers) {
@Inject
private AlertManager alertManager;
@Inject
private RollingMaintenanceManager rollingMaintenanceManager;
@Inject
private AnnotationService annotationService;
@Inject
private VolumeDao volumeDao;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);

Expand All @@ -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);
Expand All @@ -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",
Expand All @@ -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() {
Expand Down Expand Up @@ -1874,7 +1948,13 @@ protected void configureVncAccessForKVMHostFailedMigrations(HostVO host, List<VM
*/
protected boolean setHostIntoMaintenance(HostVO host) throws NoTransitionException {
logger.debug("Host {} entering in Maintenance", host);
resourceStateTransitTo(host, ResourceState.Event.InternalEnterMaintenance, _nodeId);
if (resourceStateTransitTo(host, ResourceState.Event.InternalEnterMaintenance, _nodeId)) {
try {
rollingMaintenanceManager.runPostMigrateHook(host);
} catch (final RuntimeException e) {
logger.error("Could not start the PostMigrate maintenance hook on {}", host, e);
}
}
ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), CallContext.current().getCallingAccountId(),
EventVO.LEVEL_INFO, EventTypes.EVENT_MAINTENANCE_PREPARE,
String.format("completed maintenance for host %s", host), host.getId(), null, 0);
Expand Down Expand Up @@ -3927,16 +4007,7 @@ private boolean doCancelMaintenance(final long hostId) {
/* TODO: move to listener */
_haMgr.cancelScheduledMigrations(host);

boolean vms_migrating = false;
final List<VMInstanceVO> 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);
Expand All @@ -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.
Expand Down
Loading
Loading