use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method migrateVirtualMachineWithVolume.
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true)
public VirtualMachine migrateVirtualMachineWithVolume(final Long vmId, final Host destinationHost, final Map<String, String> volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
// Access check - only root administrator can migrate VM.
final Account caller = CallContext.current().getCallingAccount();
if (!_accountMgr.isRootAdmin(caller.getId())) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Caller is not a root admin, permission denied to migrate the VM");
}
throw new PermissionDeniedException("No permission to migrate VM, Only Root Admin can migrate a VM!");
}
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("Unable to find the vm by id " + vmId);
}
if (vm.getState() != State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
}
final CloudRuntimeException ex = new CloudRuntimeException("VM is not Running, unable to migrate the vm with" + " specified id");
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
if (serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()) != null) {
throw new InvalidParameterValueException("Live Migration of GPU enabled VM is not supported");
}
if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.KVM)) {
throw new InvalidParameterValueException("Unsupported hypervisor type for vm migration, we support" + " XenServer/KVM only");
}
final long srcHostId = vm.getHostId();
final Host srcHost = _resourceMgr.getHost(srcHostId);
if (srcHost == null) {
throw new InvalidParameterValueException("Cannot migrate VM, there is not Host with id: " + srcHostId);
}
// Check if src and destination hosts are valid and migrating to same host
if (destinationHost.getId() == srcHostId) {
throw new InvalidParameterValueException("Cannot migrate VM, VM is already present on this host, please" + " specify valid destination host to migrate the VM");
}
// Check if the source and destination hosts are of the same type and support storage motion.
if (!srcHost.getHypervisorType().equals(destinationHost.getHypervisorType())) {
throw new CloudRuntimeException("The source and destination hosts are not of the same type " + "Source hypervisor type and version: " + srcHost.getHypervisorType().toString() + " " + srcHost.getHypervisorVersion() + ", Destination hypervisor type and version: " + destinationHost.getHypervisorType().toString() + " " + destinationHost.getHypervisorVersion());
}
if (srcHost.getHypervisorVersion() != null && !srcHost.getHypervisorVersion().equals(destinationHost.getHypervisorVersion())) {
throw new CloudRuntimeException("The source and destination hosts are not of the same version. " + "Source hypervisor type and version: " + srcHost.getHypervisorType().toString() + " " + srcHost.getHypervisorVersion() + ", Destination hypervisor type and version: " + destinationHost.getHypervisorType().toString() + " " + destinationHost.getHypervisorVersion());
}
final HypervisorCapabilitiesVO capabilities = _hypervisorCapabilitiesDao.findByHypervisorTypeAndVersion(srcHost.getHypervisorType(), srcHost.getHypervisorVersion());
if (!capabilities.isStorageMotionSupported()) {
throw new CloudRuntimeException("Migration with storage isn't supported on hypervisor " + srcHost.getHypervisorType() + " of version " + srcHost.getHypervisorVersion());
}
// Check if destination host is up.
if (destinationHost.getState() != com.cloud.host.Status.Up || destinationHost.getResourceState() != ResourceState.Enabled) {
throw new CloudRuntimeException("Cannot migrate VM, destination host is not in correct state, has " + "status: " + destinationHost.getState() + ", state: " + destinationHost.getResourceState());
}
// Check that Vm does not have VM Snapshots
if (_vmSnapshotDao.findByVm(vmId).size() > 0) {
throw new InvalidParameterValueException("VM with VM Snapshots cannot be migrated with storage, please remove all VM snapshots");
}
final List<VolumeVO> vmVolumes = _volsDao.findUsableVolumesForInstance(vm.getId());
final Map<Long, Long> volToPoolObjectMap = new HashMap<>();
if (!isVMUsingLocalStorage(vm) && destinationHost.getClusterId().equals(srcHost.getClusterId())) {
if (volumeToPool.isEmpty()) {
// then fail the call. migrateVirtualMachine api should have been used.
throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost + " to destination host " + destinationHost + " doesn't involve migrating the volumes.");
}
}
if (!volumeToPool.isEmpty()) {
// Check if all the volumes and pools passed as parameters are valid.
for (final Map.Entry<String, String> entry : volumeToPool.entrySet()) {
final VolumeVO volume = _volsDao.findByUuid(entry.getKey());
final StoragePoolVO pool = _storagePoolDao.findByUuid(entry.getValue());
if (volume == null) {
throw new InvalidParameterValueException("There is no volume present with the given id " + entry.getKey());
} else if (pool == null) {
throw new InvalidParameterValueException("There is no storage pool present with the given id " + entry.getValue());
} else if (pool.isInMaintenance()) {
throw new InvalidParameterValueException("Cannot migrate volume " + volume + "to the destination storage pool " + pool.getName() + " as the storage pool is in maintenance mode.");
} else {
// Verify the volume given belongs to the vm.
if (!vmVolumes.contains(volume)) {
throw new InvalidParameterValueException("There volume " + volume + " doesn't belong to " + "the virtual machine " + vm + " that has to be migrated");
}
volToPoolObjectMap.put(volume.getId(), pool.getId());
}
}
}
// Check if all the volumes are in the correct state.
for (final VolumeVO volume : vmVolumes) {
if (volume.getState() != Volume.State.Ready) {
throw new CloudRuntimeException("Volume " + volume + " of the VM is not in Ready state. Cannot " + "migrate the vm with its volumes.");
}
}
// Check max guest vm limit for the destinationHost.
final HostVO destinationHostVO = _hostDao.findById(destinationHost.getId());
if (_capacityMgr.checkIfHostReachMaxGuestLimit(destinationHostVO)) {
throw new VirtualMachineMigrationException("Host name: " + destinationHost.getName() + ", hostId: " + destinationHost.getId() + " already has max running vms (count includes system VMs). Cannot" + " migrate to this host");
}
checkHostsDedication(vm, srcHostId, destinationHost.getId());
_itMgr.migrateWithStorage(vm.getUuid(), srcHostId, destinationHost.getId(), volToPoolObjectMap);
return _vmDao.findById(vm.getId());
}
use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method updateDefaultNicForVirtualMachine.
@Override
@ActionEvent(eventType = EventTypes.EVENT_NIC_UPDATE, eventDescription = "Creating Nic", async = true)
public UserVm updateDefaultNicForVirtualMachine(final UpdateDefaultNicForVMCmd cmd) throws InvalidParameterValueException, CloudRuntimeException {
final Long vmId = cmd.getVmId();
final Long nicId = cmd.getNicId();
final Account caller = CallContext.current().getCallingAccount();
final UserVmVO vmInstance = _vmDao.findById(vmId);
if (vmInstance == null) {
throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
}
// Check that Vm does not have VM Snapshots
if (_vmSnapshotDao.findByVm(vmId).size() > 0) {
throw new InvalidParameterValueException("NIC cannot be updated for VM with VM Snapshots");
}
NicVO nic = _nicDao.findById(nicId);
if (nic == null) {
throw new InvalidParameterValueException("unable to find a nic with id " + nicId);
}
final NetworkVO network = _networkDao.findById(nic.getNetworkId());
if (network == null) {
throw new InvalidParameterValueException("unable to find a network with id " + nic.getNetworkId());
}
// Perform permission check on VM
_accountMgr.checkAccess(caller, null, true, vmInstance);
// Verify that zone is not Basic
final Zone zone = zoneRepository.findOne(vmInstance.getDataCenterId());
if (zone.getNetworkType() == NetworkType.Basic) {
throw new CloudRuntimeException("Zone " + vmInstance.getDataCenterId() + ", has a NetworkType of Basic. Can't change default NIC on a Basic Network");
}
// no need to check permissions for network, we'll enumerate the ones they already have access to
final Network existingdefaultnet = _networkModel.getDefaultNetworkForVm(vmId);
// check to see if nic is attached to VM
if (nic.getInstanceId() != vmId) {
throw new InvalidParameterValueException(nic + " is not a nic on " + vmInstance);
}
// if current default equals chosen new default, Throw an exception
if (nic.isDefaultNic()) {
throw new CloudRuntimeException("refusing to set default nic because chosen nic is already the default");
}
// make sure the VM is Running or Stopped
if (vmInstance.getState() != State.Running && vmInstance.getState() != State.Stopped) {
throw new CloudRuntimeException("refusing to set default " + vmInstance + " is not Running or Stopped");
}
NicProfile existing = null;
final List<NicProfile> nicProfiles = _networkMgr.getNicProfiles(vmInstance);
for (final NicProfile nicProfile : nicProfiles) {
if (nicProfile.isDefaultNic() && existingdefaultnet != null && nicProfile.getNetworkId() == existingdefaultnet.getId()) {
existing = nicProfile;
}
}
if (existing == null) {
s_logger.warn("Failed to update default nic, no nic profile found for existing default network");
throw new CloudRuntimeException("Failed to find a nic profile for the existing default network. This is bad and probably means some sort of configuration corruption");
}
NicVO existingVO = _nicDao.findById(existing.id);
nic.setDefaultNic(true);
existingVO.setDefaultNic(false);
nic = _nicDao.persist(nic);
existingVO = _nicDao.persist(existingVO);
Network newdefault = _networkModel.getDefaultNetworkForVm(vmId);
if (newdefault == null) {
nic.setDefaultNic(false);
existingVO.setDefaultNic(true);
nic = _nicDao.persist(nic);
_nicDao.persist(existingVO);
newdefault = _networkModel.getDefaultNetworkForVm(vmId);
if (newdefault.getId() == existingdefaultnet.getId()) {
throw new CloudRuntimeException("Setting a default nic failed, and we had no default nic, but we were able to set it back to the original");
}
throw new CloudRuntimeException("Failed to change default nic to " + nic + " and now we have no default");
} else if (newdefault.getId() == nic.getNetworkId()) {
s_logger.debug("successfully set default network to " + network + " for " + vmInstance);
return _vmDao.findById(vmInstance.getId());
}
throw new CloudRuntimeException("something strange happened, new default network(" + newdefault.getId() + ") is not null, and is not equal to the network(" + nic.getNetworkId() + ") of the chosen nic");
}
use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.
the class VMSnapshotManagerImpl method allocVMSnapshot.
@Override
public VMSnapshot allocVMSnapshot(final Long vmId, String vsDisplayName, final String vsDescription) throws ResourceAllocationException {
final Account caller = getCaller();
// check if VM exists
final UserVmVO userVmVo = _userVMDao.findById(vmId);
if (userVmVo == null) {
throw new InvalidParameterValueException("Creating VM snapshot failed due to VM:" + vmId + " is a system VM or does not exist");
}
if (_snapshotDao.listByInstanceId(vmId, Snapshot.State.BackedUp).size() > 0 && !HypervisorType.KVM.equals(userVmVo.getHypervisorType())) {
throw new InvalidParameterValueException("VM snapshot for this VM is not allowed. This VM has volumes attached which has snapshots, please remove all snapshots " + "before taking VM snapshot");
}
// VM snapshot with memory is not supported for vGPU Vms
if (_serviceOfferingDetailsDao.findDetail(userVmVo.getServiceOfferingId(), GPU.Keys.vgpuType.toString()) != null) {
throw new InvalidParameterValueException("VM snapshot with MEMORY is not supported for vGPU enabled VMs.");
}
// check hypervisor capabilities
if (!_hypervisorCapabilitiesDao.isVmSnapshotEnabled(userVmVo.getHypervisorType(), "default")) {
throw new InvalidParameterValueException("VM snapshot is not enabled for hypervisor type: " + userVmVo.getHypervisorType());
}
// parameter length check
if (vsDisplayName != null && vsDisplayName.length() > 255) {
throw new InvalidParameterValueException("Creating VM snapshot failed due to length of VM snapshot vsDisplayName should not exceed 255");
}
if (vsDescription != null && vsDescription.length() > 255) {
throw new InvalidParameterValueException("Creating VM snapshot failed due to length of VM snapshot vsDescription should not exceed 255");
}
// VM snapshot display name must be unique for a VM
final String timeString = DateUtil.getDateDisplayString(DateUtil.GMT_TIMEZONE, new Date(), DateUtil.YYYYMMDD_FORMAT);
final String vmSnapshotName = userVmVo.getInstanceName() + "_VS_" + timeString;
if (vsDisplayName == null) {
vsDisplayName = vmSnapshotName;
}
if (_vmSnapshotDao.findByName(vmId, vsDisplayName) != null) {
throw new InvalidParameterValueException("Creating VM snapshot failed due to VM snapshot with name '" + vsDisplayName + "' already exists");
}
if (userVmVo.getState() != VirtualMachine.State.Running) {
throw new InvalidParameterValueException("You can only take VM snapshots when the VM is in 'Running' state. Try taking a volume snapshot instead.");
}
// check access
_accountMgr.checkAccess(caller, null, true, userVmVo);
// check max snapshot limit for per VM
if (_vmSnapshotDao.findByVm(vmId).size() >= _vmSnapshotMax) {
throw new CloudRuntimeException("Creating vm snapshot failed due to a VM can just have : " + _vmSnapshotMax + " VM snapshots. Please delete old ones");
}
// check if there are active volume snapshots tasks
final List<VolumeVO> listVolumes = _volumeDao.findByInstance(vmId);
for (final VolumeVO volume : listVolumes) {
final List<SnapshotVO> activeSnapshots = _snapshotDao.listByInstanceId(volume.getInstanceId(), Snapshot.State.Creating, Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp);
if (activeSnapshots.size() > 0) {
throw new CloudRuntimeException("There is other active volume snapshot tasks on the instance to which the volume is attached, please try again later.");
}
if (userVmVo.getHypervisorType() == HypervisorType.KVM && volume.getFormat() != ImageFormat.QCOW2) {
throw new CloudRuntimeException("We only support create vm snapshots from vm with QCOW2 image");
}
}
// check if there are other active VM snapshot tasks
if (hasActiveVMSnapshotTasks(vmId)) {
throw new CloudRuntimeException("There is other active vm snapshot tasks on the instance, please try again later");
}
try {
final VMSnapshotVO vmSnapshotVo = new VMSnapshotVO(userVmVo.getAccountId(), userVmVo.getDomainId(), vmId, vsDescription, vmSnapshotName, vsDisplayName, userVmVo.getServiceOfferingId(), VMSnapshot.Type.DiskAndMemory, null);
final VMSnapshot vmSnapshot = _vmSnapshotDao.persist(vmSnapshotVo);
if (vmSnapshot == null) {
throw new CloudRuntimeException("Failed to create snapshot for vm: " + vmId);
}
return vmSnapshot;
} catch (final Exception e) {
final String msg = e.getMessage();
s_logger.error("Create vm snapshot record failed for vm: " + vmId + " due to: " + msg);
}
return null;
}
use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.
the class VMSnapshotManagerImpl method revertToVMSnapshotThroughJobQueue.
public Outcome<VMSnapshot> revertToVMSnapshotThroughJobQueue(final Long vmId, final Long vmSnapshotId) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
final VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkRevertToVMSnapshot.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(VirtualMachine.Type.Instance);
workJob.setVmInstanceId(vm.getId());
workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
// save work context info (there are some duplications)
final VmWorkRevertToVMSnapshot workInfo = new VmWorkRevertToVMSnapshot(callingUser.getId(), callingAccount.getId(), vm.getId(), VMSnapshotManagerImpl.VM_WORK_JOB_HANDLER, vmSnapshotId);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
return new VmJobVMSnapshotOutcome(workJob, vmSnapshotId);
}
use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.
the class StoragePoolAutomationImpl method cancelMaintain.
@Override
public boolean cancelMaintain(final DataStore store) {
// Change the storage state back to up
final Long userId = CallContext.current().getCallingUserId();
final User user = _userDao.findById(userId);
final Account account = CallContext.current().getCallingAccount();
final StoragePoolVO poolVO = primaryDataStoreDao.findById(store.getId());
final StoragePool pool = (StoragePool) store;
// Handeling the Zone wide and cluster wide primay storage
List<HostVO> hosts = new ArrayList<>();
// if the storage scope is ZONE wide, then get all the hosts for which hypervisor ZWSP created to send Modifystoragepoolcommand
if (poolVO.getScope().equals(ScopeType.ZONE)) {
if (HypervisorType.Any.equals(pool.getHypervisor())) {
hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZone(pool.getDataCenterId());
} else {
hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(poolVO.getHypervisor(), pool.getDataCenterId());
}
} else {
hosts = _resourceMgr.listHostsInClusterByStatus(pool.getClusterId(), Status.Up);
}
if (hosts == null || hosts.size() == 0) {
return true;
}
// add heartbeat
for (final HostVO host : hosts) {
final ModifyStoragePoolCommand msPoolCmd = new ModifyStoragePoolCommand(true, pool);
final Answer answer = agentMgr.easySend(host.getId(), msPoolCmd);
if (answer == null || !answer.getResult()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("ModifyStoragePool add failed due to " + ((answer == null) ? "answer null" : answer.getDetails()));
}
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("ModifyStoragePool add secceeded");
}
}
}
// 2. Get a list of pending work for this queue
final List<StoragePoolWorkVO> pendingWork = _storagePoolWorkDao.listPendingWorkForCancelMaintenanceByPoolId(poolVO.getId());
// 3. work through the queue
for (final StoragePoolWorkVO work : pendingWork) {
try {
final VMInstanceVO vmInstance = vmDao.findById(work.getVmId());
if (vmInstance == null) {
continue;
}
// proxy
if (vmInstance.getType().equals(VirtualMachine.Type.ConsoleProxy)) {
final ConsoleProxyVO consoleProxy = _consoleProxyDao.findById(vmInstance.getId());
vmMgr.advanceStart(consoleProxy.getUuid(), null, null);
// update work queue
work.setStartedAfterMaintenance(true);
_storagePoolWorkDao.update(work.getId(), work);
}
// if the instance is of type ssvm, call the ssvm manager
if (vmInstance.getType().equals(VirtualMachine.Type.SecondaryStorageVm)) {
final SecondaryStorageVmVO ssVm = _secStrgDao.findById(vmInstance.getId());
vmMgr.advanceStart(ssVm.getUuid(), null, null);
// update work queue
work.setStartedAfterMaintenance(true);
_storagePoolWorkDao.update(work.getId(), work);
}
// manager
if (vmInstance.getType().equals(VirtualMachine.Type.DomainRouter)) {
final DomainRouterVO domR = _domrDao.findById(vmInstance.getId());
vmMgr.advanceStart(domR.getUuid(), null, null);
// update work queue
work.setStartedAfterMaintenance(true);
_storagePoolWorkDao.update(work.getId(), work);
}
// if the instance is of type user vm, call the user vm manager
if (vmInstance.getType().equals(VirtualMachine.Type.User)) {
// don't allow to start vm that doesn't have a root volume
if (volumeDao.findByInstanceAndType(vmInstance.getId(), Volume.Type.ROOT).isEmpty()) {
_storagePoolWorkDao.remove(work.getId());
} else {
final UserVmVO userVm = userVmDao.findById(vmInstance.getId());
vmMgr.advanceStart(userVm.getUuid(), null, null);
work.setStartedAfterMaintenance(true);
_storagePoolWorkDao.update(work.getId(), work);
}
}
} catch (final Exception e) {
s_logger.debug("Failed start vm", e);
throw new CloudRuntimeException(e.toString());
}
}
return false;
}
Aggregations