boolean isActiveInstance(VMInstanceVO instance) { switch (instance.getState()) { case Migrating: case Starting: case Running: case Shutdowned: case Stopped: case Stopping: return true; case Destroyed: case Error: case Expunging: return false; default: s_logger.warn("Unknown VMInstance state " + instance.getState().getDescription()); } return true; }
private boolean skipCalculation(VMInstanceVO vm) { if (vm.getState() == State.Expunging) { if (s_logger.isDebugEnabled()) { s_logger.debug("Skip counting capacity for Expunging VM : " + vm.getInstanceName()); } return true; } if (vm.getState() == State.Destroyed && vm.getType() != VirtualMachine.Type.User) { return true; } if (vm.getState() == State.Stopped || vm.getState() == State.Destroyed) { // for Stopped/Destroyed VMs, we will skip counting it if it hasn't // been used for a while int secondsToSkipVMs = _secondsToSkipStoppedVMs; if (vm.getState() == State.Destroyed) { secondsToSkipVMs = _secondsToSkipDestroyedVMs; } long millisecondsSinceLastUpdate = DateUtil.currentGMTTime().getTime() - vm.getUpdateTime().getTime(); if (millisecondsSinceLastUpdate > secondsToSkipVMs * 1000L) { if (s_logger.isDebugEnabled()) { s_logger.debug("Skip counting " + vm.getState().toString() + " vm " + vm.getInstanceName() + " in capacity allocation as it has been " + vm.getState().toString().toLowerCase() + " for " + millisecondsSinceLastUpdate / 60000 + " minutes"); } return true; } } return false; }
private boolean hostSupportSnapsthotForVolume(HostVO host, VolumeInfo volume) { if (host.getHypervisorType() != HypervisorType.KVM) { return true; } //Turn off snapshot by default for KVM if the volume attached to vm that is not in the Stopped/Destroyed state, //unless it is set in the global flag Long vmId = volume.getInstanceId(); if (vmId != null) { VMInstanceVO vm = _vmDao.findById(vmId); if (vm.getState() != VirtualMachine.State.Stopped && vm.getState() != VirtualMachine.State.Destroyed) { boolean snapshotEnabled = Boolean.parseBoolean(_configDao.getValue("kvm.snapshot.enabled")); if (!snapshotEnabled) { s_logger.debug("Snapshot is not supported on host " + host + " for the volume " + volume + " attached to the vm " + vm); return false; } } } // Determine host capabilities String caps = host.getCapabilities(); if (caps != null) { String[] tokens = caps.split(","); for (String token : tokens) { if (token.contains("snapshot")) { return true; } } } return false; }
@Override public boolean upgradeVirtualMachine(Long vmId, Long newServiceOfferingId, Map<String, String> customParameters) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException { // Verify input parameters VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); if (vmInstance != null) { if (vmInstance.getState().equals(State.Stopped)) { upgradeStoppedVirtualMachine(vmId, newServiceOfferingId, customParameters); return true; } if (vmInstance.getState().equals(State.Running)) { return upgradeRunningVirtualMachine(vmId, newServiceOfferingId, customParameters); } } return false; }
@Override public void scheduleDestroy(VMInstanceVO vm, long hostId) { final HaWorkVO work = new HaWorkVO(vm.getId(), vm.getType(), WorkType.Destroy, Step.Scheduled, hostId, vm.getState(), 0, vm.getUpdated()); _haDao.persist(work); if (s_logger.isDebugEnabled()) { s_logger.debug("Scheduled " + work.toString()); } wakeupWorkers(); }
@Override public void scheduleStop(VMInstanceVO vm, long hostId, WorkType type) { assert (type == WorkType.CheckStop || type == WorkType.ForceStop || type == WorkType.Stop); if (_haDao.hasBeenScheduled(vm.getId(), type)) { s_logger.info("There's already a job scheduled to stop " + vm); return; } HaWorkVO work = new HaWorkVO(vm.getId(), vm.getType(), type, Step.Scheduled, hostId, vm.getState(), 0, vm.getUpdated()); _haDao.persist(work); if (s_logger.isDebugEnabled()) { s_logger.debug("Scheduled " + work); } wakeupWorkers(); }
@Override public void cleanupVMReservations() { List<VMReservationVO> reservations = _reservationDao.listAll(); for (VMReservationVO reserv : reservations) { VMInstanceVO vm = _vmInstanceDao.findById(reserv.getVmId()); if (vm != null) { if (vm.getState() == State.Starting || (vm.getState() == State.Stopped && vm.getLastHostId() == null)) { continue; } else { // delete reservation _reservationDao.remove(reserv.getId()); } } else { // delete reservation _reservationDao.remove(reserv.getId()); } } }
private void scanStalledVMInTransitionStateOnDisconnectedHosts() { final Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - VmOpWaitInterval.value() * 1000); final List<Long> stuckAndUncontrollableVMs = listStalledVMInTransitionStateOnDisconnectedHosts(cutTime); for (final Long vmId : stuckAndUncontrollableVMs) { final VMInstanceVO vm = _vmDao.findById(vmId); // We now only alert administrator about this situation _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(), VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") is stuck in " + vm.getState() + " state and its host is unreachable for too long"); } }
@Override protected void runInContext() { final GlobalLock lock = GlobalLock.getInternLock("TransitionChecking"); if (lock == null) { s_logger.debug("Couldn't get the global lock"); return; } if (!lock.lock(30)) { s_logger.debug("Couldn't lock the db"); return; } try { scanStalledVMInTransitionStateOnDisconnectedHosts(); final List<VMInstanceVO> instances = _vmDao.findVMInTransition(new Date(DateUtil.currentGMTTime().getTime() - AgentManager.Wait.value() * 1000), State.Starting, State.Stopping); for (final VMInstanceVO instance : instances) { final State state = instance.getState(); if (state == State.Stopping) { _haMgr.scheduleStop(instance, instance.getHostId(), WorkType.CheckStop); } else if (state == State.Starting) { _haMgr.scheduleRestart(instance, true); } } } catch (final Exception e) { s_logger.warn("Caught the following exception on transition checking", e); } finally { lock.unlock(); } } }
final VMInstanceVO router = _vmDao.findById(vm.getId()); if (router.getState() == State.Running) { throw new AgentUnavailableException("Unable to unplug nic from rotuer " + router + " from network " + network, dest.getHost().getId(), e); } else if (router.getState() == State.Stopped || router.getState() == State.Stopping) { s_logger.debug("Vm " + router.getInstanceName() + " is in " + router.getState() + ", so not sending unplug nic command to the backend"); } else { s_logger.warn("Unable to apply unplug nic, Vm " + router + " is not in the right state " + router.getState());
@Override public boolean stateTransitTo(final VirtualMachine vm1, final VirtualMachine.Event e, final Long hostId) throws NoTransitionException { final VMInstanceVO vm = (VMInstanceVO)vm1; final State oldState = vm.getState(); if (oldState == State.Starting) { if (e == Event.OperationSucceeded) { vm.setLastHostId(hostId); } } else if (oldState == State.Stopping) { if (e == Event.OperationSucceeded) { vm.setLastHostId(vm.getHostId()); } } return _stateMachine.transitTo(vm, e, new Pair<Long, Long>(vm.getHostId(), hostId), _vmDao); }
@Override public boolean scheduleMigration(final VMInstanceVO vm) { if (vm.getHostId() != null) { final HaWorkVO work = new HaWorkVO(vm.getId(), vm.getType(), WorkType.Migration, Step.Scheduled, vm.getHostId(), vm.getState(), 0, vm.getUpdated()); _haDao.persist(work); wakeupWorkers(); } return true; }
public boolean plugNic(final Network network, final NicTO nic, final VirtualMachineTO vm, final ReservationContext context, final DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { boolean result = true; final VMInstanceVO router = _vmDao.findById(vm.getId()); if (router.getState() == State.Running) { try { final PlugNicCommand plugNicCmd = new PlugNicCommand(nic, vm.getName(), vm.getType(), vm.getDetails()); final Commands cmds = new Commands(Command.OnError.Stop); cmds.addCommand("plugnic", plugNicCmd); _agentMgr.send(dest.getHost().getId(), cmds); final PlugNicAnswer plugNicAnswer = cmds.getAnswer(PlugNicAnswer.class); if (plugNicAnswer == null || !plugNicAnswer.getResult()) { s_logger.warn("Unable to plug nic for vm " + vm.getName()); result = false; } } catch (final OperationTimedoutException e) { throw new AgentUnavailableException("Unable to plug nic for router " + vm.getName() + " in network " + network, dest.getHost().getId(), e); } } else { s_logger.warn("Unable to apply PlugNic, vm " + router + " is not in the right state " + router.getState()); throw new ResourceUnavailableException("Unable to apply PlugNic on the backend," + " vm " + vm + " is not in the right state", DataCenter.class, router.getDataCenterId()); } return result; }
private void loadVmDetailsInMapForExternalDhcpIp() { List<NetworkVO> networks = _networkDao.listByGuestType(Network.GuestType.Shared); for (NetworkVO network: networks) { if(_networkModel.isSharedNetworkWithoutServices(network.getId())) { List<NicVO> nics = _nicDao.listByNetworkId(network.getId()); for (NicVO nic : nics) { if (nic.getIPv4Address() == null) { long nicId = nic.getId(); long vmId = nic.getInstanceId(); VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); // only load running vms. For stopped vms get loaded on starting if (vmInstance.getState() == State.Running) { VmAndCountDetails vmAndCount = new VmAndCountDetails(vmId, VmIpFetchTrialMax.value()); vmIdCountMap.put(nicId, vmAndCount); } } } } } }
@Override public boolean replugNic(final Network network, final NicTO nic, final VirtualMachineTO vm, final ReservationContext context, final DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { boolean result = true; final VMInstanceVO router = _vmDao.findById(vm.getId()); if (router.getState() == State.Running) { try { final ReplugNicCommand replugNicCmd = new ReplugNicCommand(nic, vm.getName(), vm.getType(), vm.getDetails()); final Commands cmds = new Commands(Command.OnError.Stop); cmds.addCommand("replugnic", replugNicCmd); _agentMgr.send(dest.getHost().getId(), cmds); final ReplugNicAnswer replugNicAnswer = cmds.getAnswer(ReplugNicAnswer.class); if (replugNicAnswer == null || !replugNicAnswer.getResult()) { s_logger.warn("Unable to replug nic for vm " + vm.getName()); result = false; } } catch (final OperationTimedoutException e) { throw new AgentUnavailableException("Unable to plug nic for router " + vm.getName() + " in network " + network, dest.getHost().getId(), e); } } else { s_logger.warn("Unable to apply ReplugNic, vm " + router + " is not in the right state " + router.getState()); throw new ResourceUnavailableException("Unable to apply ReplugNic on the backend," + " vm " + vm + " is not in the right state", DataCenter.class, router.getDataCenterId()); } return result; }
@Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { if (host.getType() != Host.Type.Routing || host.getHypervisorType() != HypervisorType.BareMetal) { return null; } List<VMInstanceVO> deadVms = _vmDao.listByLastHostId(host.getId()); for (VMInstanceVO vm : deadVms) { if (vm.getState() == State.Running || vm.getHostId() != null) { throw new CloudRuntimeException("VM " + vm.getId() + "is still running on host " + host.getId()); } _vmDao.remove(vm.getId()); } return new DeleteHostAnswer(true); }
@Override @ActionEvent(eventType = EventTypes.EVENT_VM_UPGRADE, eventDescription = "Upgrading system VM", async = true) public VirtualMachine upgradeSystemVM(final ScaleSystemVMCmd cmd) throws ResourceUnavailableException, ManagementServerException, VirtualMachineMigrationException, ConcurrentOperationException { final VMInstanceVO vmInstance = _vmInstanceDao.findById(cmd.getId()); if (vmInstance.getHypervisorType() == HypervisorType.XenServer && vmInstance.getState().equals(State.Running)) { throw new InvalidParameterValueException("Dynamic Scaling operation is not permitted for this hypervisor on system vm"); } final boolean result = _userVmMgr.upgradeVirtualMachine(cmd.getId(), cmd.getServiceOfferingId(), cmd.getDetails()); if (result) { final VirtualMachine vm = _vmInstanceDao.findById(cmd.getId()); return vm; } else { throw new CloudRuntimeException("Failed to upgrade System VM"); } }
@Override public boolean isLocalStorageActiveOnHost(Long hostId) { List<StoragePoolHostVO> storagePoolHostRefs = _storagePoolHostDao.listByHostId(hostId); for (StoragePoolHostVO storagePoolHostRef : storagePoolHostRefs) { StoragePoolVO PrimaryDataStoreVO = _storagePoolDao.findById(storagePoolHostRef.getPoolId()); if (PrimaryDataStoreVO.getPoolType() == StoragePoolType.LVM || PrimaryDataStoreVO.getPoolType() == StoragePoolType.EXT) { SearchBuilder<VolumeVO> volumeSB = _volsDao.createSearchBuilder(); volumeSB.and("poolId", volumeSB.entity().getPoolId(), SearchCriteria.Op.EQ); volumeSB.and("removed", volumeSB.entity().getRemoved(), SearchCriteria.Op.NULL); volumeSB.and("state", volumeSB.entity().getState(), SearchCriteria.Op.NIN); SearchBuilder<VMInstanceVO> activeVmSB = _vmInstanceDao.createSearchBuilder(); activeVmSB.and("state", activeVmSB.entity().getState(), SearchCriteria.Op.IN); volumeSB.join("activeVmSB", activeVmSB, volumeSB.entity().getInstanceId(), activeVmSB.entity().getId(), JoinBuilder.JoinType.INNER); SearchCriteria<VolumeVO> volumeSC = volumeSB.create(); volumeSC.setParameters("poolId", PrimaryDataStoreVO.getId()); volumeSC.setParameters("state", Volume.State.Expunging, Volume.State.Destroy); volumeSC.setJoinParameters("activeVmSB", "state", State.Starting, State.Running, State.Stopping, State.Migrating); List<VolumeVO> volumes = _volsDao.search(volumeSC, null); if (volumes.size() > 0) { return true; } } } return false; }
/** * Lists all pods given a Data Center Id, a {@link VirtualMachine.Type} and * a list of {@link VirtualMachine.State} * @param id * @param type * @param states * @return */ protected List<HostPodVO> listByDataCenterIdVMTypeAndStates(final long id, final VirtualMachine.Type type, final VirtualMachine.State... states) { final SearchBuilder<VMInstanceVO> vmInstanceSearch = vmDao.createSearchBuilder(); vmInstanceSearch.and("type", vmInstanceSearch.entity().getType(), SearchCriteria.Op.EQ); vmInstanceSearch.and("states", vmInstanceSearch.entity().getState(), SearchCriteria.Op.IN); final SearchBuilder<HostPodVO> podIdSearch = podDao.createSearchBuilder(); podIdSearch.and("dc", podIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); podIdSearch.select(null, SearchCriteria.Func.DISTINCT, podIdSearch.entity().getId()); podIdSearch.join("vmInstanceSearch", vmInstanceSearch, podIdSearch.entity().getId(), vmInstanceSearch.entity().getPodIdToDeployIn(), JoinBuilder.JoinType.INNER); podIdSearch.done(); final SearchCriteria<HostPodVO> sc = podIdSearch.create(); sc.setParameters("dc", id); sc.setJoinParameters("vmInstanceSearch", "type", type); sc.setJoinParameters("vmInstanceSearch", "states", (Object[]) states); return podDao.search(sc, null); }