@Override public void generateUsageEvent(VirtualMachine vm, boolean isDisplay, String eventType){ ServiceOfferingVO serviceOffering = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId()); if (!serviceOffering.isDynamic()) { UsageEventUtils.publishUsageEvent(eventType, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), serviceOffering.getId(), vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid(), isDisplay); } else { Map<String, String> customParameters = new HashMap<String, String>(); customParameters.put(UsageEventVO.DynamicParameters.cpuNumber.name(), serviceOffering.getCpu().toString()); customParameters.put(UsageEventVO.DynamicParameters.cpuSpeed.name(), serviceOffering.getSpeed().toString()); customParameters.put(UsageEventVO.DynamicParameters.memory.name(), serviceOffering.getRamSize().toString()); UsageEventUtils.publishUsageEvent(eventType, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), serviceOffering.getId(), vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid(), customParameters, isDisplay); } }
private boolean deleteConfigDriveIso(final VirtualMachine vm) throws ResourceUnavailableException { DataStore dataStore = _dataStoreMgr.getImageStore(vm.getDataCenterId()); Long agentId = findAgentIdForImageStore(dataStore); if (VirtualMachineManager.VmConfigDriveOnPrimaryPool.value()) { List<VolumeVO> volumes = _volumeDao.findByInstanceAndType(vm.getId(), Volume.Type.ROOT); if (volumes != null && volumes.size() > 0) { dataStore = _dataStoreMgr.getDataStore(volumes.get(0).getPoolId(), DataStoreRole.Primary); } agentId = (vm.getHostId() != null) ? vm.getHostId() : vm.getLastHostId(); } if (agentId == null || dataStore == null) { throw new ResourceUnavailableException("Config drive iso creation failed, agent or datastore not available", ConfigDriveNetworkElement.class, 0L); } LOG.debug("Deleting config drive ISO for vm: " + vm.getInstanceName()); final String isoPath = ConfigDrive.createConfigDrivePath(vm.getInstanceName()); final HandleConfigDriveIsoCommand configDriveIsoCommand = new HandleConfigDriveIsoCommand(isoPath, null, dataStore.getTO(), false); final Answer answer = agentManager.easySend(agentId, configDriveIsoCommand); if (!answer.getResult()) { LOG.error("Failed to remove config drive for instance: " + vm.getInstanceName()); return false; } return true; }
private VMSnapshot takeHypervisorSnapshot(VolumeInfo volumeInfo) { VirtualMachine virtualMachine = volumeInfo.getAttachedVM(); if (virtualMachine != null && VirtualMachine.State.Running.equals(virtualMachine.getState())) { String vmSnapshotName = UUID.randomUUID().toString().replace("-", ""); VMSnapshotVO vmSnapshotVO = new VMSnapshotVO(virtualMachine.getAccountId(), virtualMachine.getDomainId(), virtualMachine.getId(), vmSnapshotName, vmSnapshotName, vmSnapshotName, virtualMachine.getServiceOfferingId(), VMSnapshot.Type.Disk, null); VMSnapshot vmSnapshot = vmSnapshotDao.persist(vmSnapshotVO); if (vmSnapshot == null) { throw new CloudRuntimeException("Unable to allocate a VM snapshot object"); } vmSnapshot = vmSnapshotService.createVMSnapshot(virtualMachine.getId(), vmSnapshot.getId(), true); if (vmSnapshot == null) { throw new CloudRuntimeException("Unable to create a hypervisor-side snapshot"); } try { Thread.sleep(60000); } catch (Exception ex) { s_logger.warn(ex.getMessage(), ex); } return vmSnapshot; } // We didn't need to take a hypervisor-side snapshot. Return 'null' to indicate this. return null; }
private String getControlNicIpForVM(VirtualMachine vm) { if (vm.getType() == VirtualMachine.Type.ConsoleProxy || vm.getType() == VirtualMachine.Type.SecondaryStorageVm) { NicVO nic = _nicsDao.getControlNicForVM(vm.getId()); return nic.getIPv4Address(); } else if (vm.getType() == VirtualMachine.Type.DomainRouter) { return vm.getPrivateIpAddress(); } else { return null; } } public Command cleanup(final String vmName) {
private Long getHostId(VolumeInfo volumeInfo) { VirtualMachine virtualMachine = volumeInfo.getAttachedVM(); if (virtualMachine == null) { return null; } Long hostId = virtualMachine.getHostId(); if (hostId == null) { hostId = virtualMachine.getLastHostId(); } return hostId; }
private void setupAgentSecurity(final Host vmHost, final Map<String, String> sshAccessDetails, final VirtualMachine vm) throws AgentUnavailableException, OperationTimedoutException { final String csr = caManager.generateKeyStoreAndCsr(vmHost, sshAccessDetails); if (!Strings.isNullOrEmpty(csr)) { final Map<String, String> ipAddressDetails = new HashMap<>(sshAccessDetails); ipAddressDetails.remove(NetworkElementCommand.ROUTER_NAME); final Certificate certificate = caManager.issueCertificate(csr, Arrays.asList(vm.getHostName(), vm.getInstanceName()), new ArrayList<>(ipAddressDetails.values()), CAManager.CertValidityPeriod.value(), null); final boolean result = caManager.deployCertificate(vmHost, certificate, false, sshAccessDetails); if (!result) { s_logger.error("Failed to setup certificate for system vm: " + vm.getInstanceName()); } } else { s_logger.error("Failed to setup keystore and generate CSR for system vm: " + vm.getInstanceName()); } }
if (vm.getState() != work.getPreviousState() || vm.getUpdated() != work.getUpdateTime()) { s_logger.info("VM " + vm + " has been changed. Current State = " + vm.getState() + " Previous State = " + work.getPreviousState() + " last updated = " + vm.getUpdated() + " previous updated = " + work.getUpdateTime()); return null; if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) { alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER; } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) { alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY; } else if (VirtualMachine.Type.SecondaryStorageVm.equals(vm.getType())) { alertType = AlertManager.AlertType.ALERT_TYPE_SSVM; if (work.getStep() == Step.Investigating) { if (!isHostRemoved) { if (vm.getHostId() == null || vm.getHostId() != work.getHostId()) { s_logger.info("VM " + vm.toString() + " is now no longer on host " + work.getHostId()); return null; fenced = true; } else { s_logger.debug("VM " + vm.getInstanceName() + " is found to be alive by " + investigator.getName()); if (host.getStatus() == Status.Up) { s_logger.info(vm + " is alive and host is up. No need to restart it."); _alertMgr.sendAlert(alertType, vm.getDataCenterId(), vm.getPodIdToDeployIn(), "Unable to restart " + vm.getHostName() + " which was running on host " + hostDesc, "Insufficient capacity to restart VM, name: " + vm.getHostName() + ", id: " + vmId + " which was running on host " + hostDesc); return (System.currentTimeMillis() >> 10) + _restartRetryInterval;
@Override public SystemVmResponse createSystemVmResponse(VirtualMachine vm) { SystemVmResponse vmResponse = new SystemVmResponse(); if (vm.getType() == Type.SecondaryStorageVm || vm.getType() == Type.ConsoleProxy || vm.getType() == Type.DomainRouter || vm.getType() == Type.NetScalerVm) { vmResponse.setId(vm.getUuid()); vmResponse.setSystemVmType(vm.getType().toString().toLowerCase()); vmResponse.setName(vm.getHostName()); if (vm.getPodIdToDeployIn() != null) { HostPodVO pod = ApiDBUtils.findPodById(vm.getPodIdToDeployIn()); if (pod != null) { vmResponse.setPodId(pod.getUuid()); VMTemplateVO template = ApiDBUtils.findTemplateById(vm.getTemplateId()); if (template != null) { vmResponse.setTemplateId(template.getUuid()); vmResponse.setCreated(vm.getCreated()); if (vm.getHostId() != null) { Host host = ApiDBUtils.findHostById(vm.getHostId()); if (host != null) { vmResponse.setHostId(host.getUuid()); if (vm.getState() != null) { vmResponse.setState(vm.getState().toString()); if (vm.getType() == Type.ConsoleProxy) { ConsoleProxyVO proxy = ApiDBUtils.findConsoleProxy(vm.getId());
private boolean orchestrateRemoveNicFromVm(final VirtualMachine vm, final Nic nic) throws ConcurrentOperationException, ResourceUnavailableException { final CallContext cctx = CallContext.current(); final VMInstanceVO vmVO = _vmDao.findById(vm.getId()); final NetworkVO network = _networkDao.findById(nic.getNetworkId()); final ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount()); final Host host = _hostDao.findById(vm.getHostId()); final DeployDestination dest = new DeployDestination(dc, null, null, host); final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType()); final VirtualMachineTO vmTO = hvGuru.implement(vmProfile); new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(network.getId(), vm.getId()), _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network)); if (vm.getState() == State.Running) { final NicTO nicTO = toNicTO(nicProfile, vmProfile.getVirtualMachine().getHypervisorType()); s_logger.debug("Un-plugging nic " + nic + " for vm " + vm + " from network " + network); final boolean result = unplugNic(network, nicTO, vmTO, context, dest); s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network); final long isDefault = nic.isDefaultNic() ? 1 : 0; UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplay()); } else { s_logger.warn("Failed to unplug nic for the vm " + vm + " from network " + network); return false; } else if (vm.getState() != State.Stopped) { s_logger.warn("Unable to remove vm " + vm + " from network " + network); throw new ResourceUnavailableException("Unable to remove vm " + vm + " from network, is not in the right state", DataCenter.class, vm.getDataCenterId());
@Override public long getId() { return _vm.getId(); }
pubishOnEventBus(event.name(), "postStateTransitionEvent", vo, oldState, newState); if (vo.getType() != VirtualMachine.Type.User) { return true; generateUsageEvent(vo.getServiceOfferingId(), vo, EventTypes.EVENT_VM_CREATE); } else if (newState == State.Running) { generateUsageEvent(vo.getServiceOfferingId(), vo, EventTypes.EVENT_VM_START); } else if (newState == State.Stopped) { generateUsageEvent(vo.getServiceOfferingId(), vo, EventTypes.EVENT_VM_STOP); List<NicVO> nics = _nicDao.listByVmId(vo.getId()); for (NicVO nic : nics) { NetworkVO network = _networkDao.findById(nic.getNetworkId()); UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vo.getAccountId(), vo.getDataCenterId(), vo.getId(), Long.toString(nic.getId()), network.getNetworkOfferingId(), null, 0L, vo.getClass().getName(), vo.getUuid(), vo.isDisplay()); generateUsageEvent(vo.getServiceOfferingId(), vo, EventTypes.EVENT_VM_DESTROY);
assert (template.getFormat() != ImageFormat.ISO) : "ISO is not a template really...."; Long size = _tmpltMgr.getTemplateSize(template.getId(), vm.getDataCenterId()); if (rootDisksize != null) { rootDisksize = rootDisksize * 1024 * 1024 * 1024; maxIops = maxIops != null ? maxIops : offering.getMaxIops(); VolumeVO vol = new VolumeVO(type, name, vm.getDataCenterId(), owner.getDomainId(), owner.getId(), offering.getId(), offering.getProvisioningType(), size, minIops, maxIops, null); vol.setFormat(getSupportedImageFormatForCluster(template.getHypervisorType())); if (vm != null) { vol.setInstanceId(vm.getId()); if (!vm.getType().equals(VirtualMachine.Type.User)) { vol.setRecreatable(true); if (vm.getType() == VirtualMachine.Type.User) { UserVmVO userVm = _userVmDao.findById(vm.getId()); vol.setDisplayVolume(userVm.isDisplayVm()); if (vm.getType() == VirtualMachine.Type.User) { Volume.class.getName(), vol.getUuid(), vol.isDisplayVolume()); _resourceLimitMgr.incrementResourceCount(vm.getAccountId(), ResourceType.volume, vol.isDisplayVolume()); _resourceLimitMgr.incrementResourceCount(vm.getAccountId(), ResourceType.primary_storage, vol.isDisplayVolume(), new Long(vol.getSize()));
@Override public Pair<String, Integer> getVncPort(final VirtualMachine vm) { if (vm.getHostId() == null) { s_logger.warn("VM " + vm.getHostName() + " does not have host, return -1 for its VNC port"); return new Pair<String, Integer>(null, -1); } if (s_logger.isTraceEnabled()) { s_logger.trace("Trying to retrieve VNC port from agent about VM " + vm.getHostName()); } final GetVncPortAnswer answer = (GetVncPortAnswer)_agentMgr.easySend(vm.getHostId(), new GetVncPortCommand(vm.getId(), vm.getInstanceName())); if (answer != null && answer.getResult()) { return new Pair<String, Integer>(answer.getAddress(), answer.getPort()); } return new Pair<String, Integer>(null, -1); }
final VMInstanceVO vmVO = _vmDao.findById(vm.getId()); final ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount()); final Host host = _hostDao.findById(vm.getHostId()); final DeployDestination dest = new DeployDestination(dc, null, null, host); if (vm.getState() == State.Running) { final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType()); final VirtualMachineTO vmTO = hvGuru.implement(vmProfile); final NicTO nicTO = toNicTO(nic, vmProfile.getVirtualMachine().getHypervisorType()); Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vmVO.getUuid(), vm.isDisplay()); } else if (vm.getState() == State.Stopped) { throw new ResourceUnavailableException("Unable to add vm " + vm + " to network, is not in the right state", DataCenter.class, vm.getDataCenterId());
State newState = transition.getToState(); Event event = transition.getEvent(); s_logger.debug("VM state transitted from :" + oldState + " to " + newState + " with event: " + event + "vm's original host id: " + vm.getLastHostId() + " new host id: " + vm.getHostId() + " host id before state transition: " + oldHostId); if (event == Event.AgentReportStopped) { releaseVmCapacity(vm, false, false, vm.getLastHostId()); releaseVmCapacity(vm, false, false, oldHostId); } else if (event == Event.OperationFailed) { releaseVmCapacity(vm, false, false, vm.getLastHostId()); releaseVmCapacity(vm, true, false, vm.getLastHostId()); } else if (event == Event.AgentReportMigrated) { releaseVmCapacity(vm, false, false, oldHostId); if ((newState == State.Starting || newState == State.Migrating || event == Event.AgentReportMigrated) && vm.getHostId() != null) { boolean fromLastHost = false; if (vm.getHostId().equals(vm.getLastHostId())) { s_logger.debug("VM starting again on the last host it was stopped on"); fromLastHost = true; if (vm.getType() == VirtualMachine.Type.User) { UserVmVO userVM = _userVMDao.findById(vm.getId()); _userVMDao.loadDetails(userVM);
@Override public SystemVmInstanceResponse createSystemVmInstanceResponse(VirtualMachine vm) { SystemVmInstanceResponse vmResponse = new SystemVmInstanceResponse(); vmResponse.setId(vm.getUuid()); vmResponse.setSystemVmType(vm.getType().toString().toLowerCase()); vmResponse.setName(vm.getHostName()); if (vm.getHostId() != null) { Host host = ApiDBUtils.findHostById(vm.getHostId()); if (host != null) { vmResponse.setHostId(host.getUuid()); } } if (vm.getState() != null) { vmResponse.setState(vm.getState().toString()); } if (vm.getType() == Type.DomainRouter) { VirtualRouter router = (VirtualRouter)vm; if (router.getRole() != null) { vmResponse.setRole(router.getRole().toString()); } } vmResponse.setObjectName("systemvminstance"); return vmResponse; }
String value = configurationDao.getValue("vmsnapshot.create.wait"); int wait = NumbersUtil.parseInt(value, 1800); Long hostId = vmSnapshotHelper.pickRunningHost(virtualMachine.getId()); VMSnapshotTO vmSnapshotTO = new VMSnapshotTO(1L, UUID.randomUUID().toString(), VMSnapshot.Type.Disk, null, null, false, null, true); GuestOSVO guestOS = guestOSDao.findById(virtualMachine.getGuestOSId()); List<VolumeObjectTO> volumeTOs = vmSnapshotHelper.getVolumeTOList(virtualMachine.getId()); CreateVMSnapshotCommand ccmd = new CreateVMSnapshotCommand(virtualMachine.getInstanceName(), virtualMachine.getUuid(), vmSnapshotTO, volumeTOs, guestOS.getDisplayName()); HostVO host = hostDao.findById(hostId); GuestOSHypervisorVO guestOsMapping = guestOsHypervisorDao.findByOsIdAndHypervisor(guestOS.getId(), host.getHypervisorType().toString(), host.getHypervisorVersion());
@Override public EndPoint select(DataObject srcData, DataObject destData, StorageAction action) { s_logger.error("IR24 select BACKUPSNAPSHOT from primary to secondary " + srcData.getId() + " dest=" + destData.getId()); if (action == StorageAction.BACKUPSNAPSHOT && srcData.getDataStore().getRole() == DataStoreRole.Primary) { SnapshotInfo srcSnapshot = (SnapshotInfo)srcData; VolumeInfo volumeInfo = srcSnapshot.getBaseVolume(); VirtualMachine vm = volumeInfo.getAttachedVM(); if (srcSnapshot.getHypervisorType() == Hypervisor.HypervisorType.KVM) { if (vm != null && vm.getState() == VirtualMachine.State.Running) { return getEndPointFromHostId(vm.getHostId()); } } if (srcSnapshot.getHypervisorType() == Hypervisor.HypervisorType.VMware) { if (vm != null) { Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId(); if (hostId != null) { return getEndPointFromHostId(hostId); } } } } return select(srcData, destData); }
private void generateNetworkUsageForVm(VirtualMachine vm, boolean isDisplay, String eventType){ List<NicVO> nics = _nicDao.listByVmId(vm.getId()); for (NicVO nic : nics) { NetworkVO network = _networkDao.findById(nic.getNetworkId()); long isDefault = (nic.isDefaultNic()) ? 1 : 0; UsageEventUtils.publishUsageEvent(eventType, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, vm.getClass().getName(), vm.getUuid(), isDisplay); } }
long ram_requested = offering.getRamSize() * 1024L * 1024L; VirtualMachine vm = vmProfile.getVirtualMachine(); DataCenter dc = _dcDao.findById(vm.getDataCenterId()); if (vm.getType() == VirtualMachine.Type.User || vm.getType() == VirtualMachine.Type.DomainRouter) { checkForNonDedicatedResources(vmProfile, dc, avoids); if (vm.getHypervisorType() == HypervisorType.BareMetal) { DeployDestination dest = new DeployDestination(dc, pod, cluster, host, new HashMap<Volume, StoragePool>()); s_logger.debug("Returning Deployment Destination: " + dest); long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId()); if (vm.getType() == VirtualMachine.Type.User) { checkForNonDedicatedResources(vmProfile, dc, avoids); String plannerName = offering.getDeploymentPlanner(); if (plannerName == null) { if (vm.getHypervisorType() == HypervisorType.BareMetal) { plannerName = "BareMetalPlanner"; } else { if (vm.getLastHostId() != null && haVmTag == null) { s_logger.debug("This VM has last host_id specified, trying to choose the same host: " + vm.getLastHostId()); HostVO host = _hostDao.findById(vm.getLastHostId()); ServiceOfferingDetailsVO offeringDetails = null; if (host == null) {