use of com.cloud.legacymodel.user.Account in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method recoverVirtualMachine.
@Override
@DB
public UserVm recoverVirtualMachine(final RecoverVMCmd cmd) throws ResourceAllocationException, CloudRuntimeException {
final Long vmId = cmd.getId();
final Account caller = CallContext.current().getCallingAccount();
final Long userId = caller.getAccountId();
// Verify input parameters
final UserVmVO vm = _vmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
}
// When trying to expunge, permission is denied when the caller is not an admin and the AllowUserExpungeRecoverVm is false for the caller.
if (!_accountMgr.isAdmin(userId) && !AllowUserExpungeRecoverVm.valueIn(userId)) {
throw new PermissionDeniedException("Recovering a vm can only be done by an Admin. Or when the allow.user.expunge.recover.vm key is set.");
}
if (vm.getRemoved() != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find vm or vm is removed: " + vmId);
}
throw new InvalidParameterValueException("Unable to find vm by id " + vmId);
}
if (vm.getState() != State.Destroyed) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("vm is not in the right state: " + vmId);
}
throw new InvalidParameterValueException("Vm with id " + vmId + " is not in the right state");
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Recovering vm " + vmId);
}
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<ResourceAllocationException>() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) throws ResourceAllocationException {
final Account account = _accountDao.lockRow(vm.getAccountId(), true);
// if the account is deleted, throw error
if (account.getRemoved() != null) {
throw new CloudRuntimeException("Unable to recover VM as the account is deleted");
}
// Get serviceOffering for Virtual Machine
final ServiceOfferingVO serviceOffering = _serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
// First check that the maximum number of UserVMs, CPU and Memory limit for the given
// accountId will not be exceeded
resourceLimitCheck(account, vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
_haMgr.cancelDestroy(vm, vm.getHostId());
try {
if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.RecoveryRequested, null)) {
s_logger.debug("Unable to recover the vm because it is not in the correct state: " + vmId);
throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
}
} catch (final NoTransitionException e) {
throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
}
// Recover the VM's disks
final List<VolumeVO> volumes = _volsDao.findByInstance(vmId);
for (final VolumeVO volume : volumes) {
if (volume.getVolumeType().equals(VolumeType.ROOT)) {
// Create an event
final Long templateId = volume.getTemplateId();
final Long diskOfferingId = volume.getDiskOfferingId();
Long offeringId = null;
if (diskOfferingId != null) {
final DiskOfferingVO offering = _diskOfferingDao.findById(diskOfferingId);
if (offering != null && offering.getType() == DiskOfferingVO.Type.Disk) {
offeringId = offering.getId();
}
}
}
}
// Update Resource Count for the given account
resourceCountIncrement(account.getId(), vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
}
});
return _vmDao.findById(vmId);
}
use of com.cloud.legacymodel.user.Account in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method createVmGroup.
@DB
private InstanceGroupVO createVmGroup(final String groupName, final long accountId) {
Account account = null;
try {
// to ensure
account = _accountDao.acquireInLockTable(accountId);
// created.
if (account == null) {
s_logger.warn("Failed to acquire lock on account");
return null;
}
InstanceGroupVO group = _vmGroupDao.findByAccountAndName(accountId, groupName);
if (group == null) {
group = new InstanceGroupVO(groupName, accountId);
group = _vmGroupDao.persist(group);
}
return group;
} finally {
if (account != null) {
_accountDao.releaseFromLockTable(accountId);
}
}
}
use of com.cloud.legacymodel.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() != HostStatus.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.legacymodel.user.Account in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method upgradeVirtualMachine.
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_UPGRADE, eventDescription = "upgrading Vm")
public // This method will be deprecated as we use ScaleVMCmd for both stopped VMs and running VMs
UserVm upgradeVirtualMachine(final UpgradeVMCmd cmd) throws ResourceAllocationException {
final Long vmId = cmd.getId();
final Long svcOffId = cmd.getServiceOfferingId();
final Account caller = CallContext.current().getCallingAccount();
// Verify input parameters
// UserVmVO vmInstance = _vmDao.findById(vmId);
final VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
if (vmInstance == null) {
throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
} else if (!vmInstance.getState().equals(State.Stopped)) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + " " + " in state " + vmInstance.getState() + "; make sure the virtual machine is stopped");
}
// If target VM has associated VM snapshots then don't allow upgrading of VM
final List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(vmId);
if (vmSnapshots.size() > 0) {
throw new InvalidParameterValueException("Unable to change service offering for VM, please remove VM snapshots before changing service offering of VM");
}
_accountMgr.checkAccess(caller, null, true, vmInstance);
// Check resource limits for CPU and Memory.
final Map<String, String> customParameters = cmd.getDetails();
ServiceOfferingVO newServiceOffering = _offeringDao.findById(svcOffId);
final ServiceOfferingVO currentServiceOffering = _offeringDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId());
final int newCpu = newServiceOffering.getCpu();
final int newMemory = newServiceOffering.getRamSize();
final int currentCpu = currentServiceOffering.getCpu();
final int currentMemory = currentServiceOffering.getRamSize();
if (newCpu > currentCpu) {
_resourceLimitMgr.checkResourceLimit(caller, ResourceType.cpu, newCpu - currentCpu);
}
if (newMemory > currentMemory) {
_resourceLimitMgr.checkResourceLimit(caller, ResourceType.memory, newMemory - currentMemory);
}
// Check that the specified service offering ID is valid
_itMgr.checkIfCanUpgrade(vmInstance, newServiceOffering);
_itMgr.upgradeVmDb(vmId, svcOffId);
// Increment or decrement CPU and Memory count accordingly.
if (newCpu > currentCpu) {
_resourceLimitMgr.incrementResourceCount(caller.getAccountId(), ResourceType.cpu, new Long(newCpu - currentCpu));
} else if (currentCpu > newCpu) {
_resourceLimitMgr.decrementResourceCount(caller.getAccountId(), ResourceType.cpu, new Long(currentCpu - newCpu));
}
if (newMemory > currentMemory) {
_resourceLimitMgr.incrementResourceCount(caller.getAccountId(), ResourceType.memory, new Long(newMemory - currentMemory));
} else if (currentMemory > newMemory) {
_resourceLimitMgr.decrementResourceCount(caller.getAccountId(), ResourceType.memory, new Long(currentMemory - newMemory));
}
return _vmDao.findById(vmId);
}
use of com.cloud.legacymodel.user.Account in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method migrateVirtualMachine.
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true)
public VirtualMachine migrateVirtualMachine(final Long vmId, final Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
// access check - only root admin 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);
}
// business logic
if (vm.getState() != State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
}
final InvalidParameterValueException ex = new InvalidParameterValueException("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)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(vm + " is not XenServer/KVM, cannot migrate this VM.");
}
throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support XenServer/KVM only");
}
if (isVMUsingLocalStorage(vm)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(vm + " is using Local Storage, cannot migrate this VM.");
}
throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate");
}
// check if migrating to same host
final long srcHostId = vm.getHostId();
if (destinationHost.getId() == srcHostId) {
throw new InvalidParameterValueException("Cannot migrate VM, VM is already presnt on this host, please specify valid destination host to migrate the VM");
}
// check if host is UP
if (destinationHost.getState() != HostStatus.Up || destinationHost.getResourceState() != ResourceState.Enabled) {
throw new InvalidParameterValueException("Cannot migrate VM, destination host is not in correct state, has status: " + destinationHost.getState() + ", state: " + destinationHost.getResourceState());
}
if (vm.getType() != VirtualMachineType.User) {
// for System VMs check that the destination host is within the same
// cluster
final HostVO srcHost = _hostDao.findById(srcHostId);
if (srcHost != null && srcHost.getClusterId() != null && destinationHost.getClusterId() != null) {
if (srcHost.getClusterId().longValue() != destinationHost.getClusterId().longValue()) {
throw new InvalidParameterValueException("Cannot migrate the VM, destination host is not in the same cluster as current host of the VM");
}
}
}
checkHostsDedication(vm, srcHostId, destinationHost.getId());
// call to core process
final Zone zone = zoneRepository.findById(destinationHost.getDataCenterId()).orElse(null);
final HostPodVO pod = _podDao.findById(destinationHost.getPodId());
final Cluster cluster = _clusterDao.findById(destinationHost.getClusterId());
final DeployDestination dest = new DeployDestination(zone, pod, cluster, destinationHost);
// check max guest vm limit for the destinationHost
final HostVO destinationHostVO = _hostDao.findById(destinationHost.getId());
if (_capacityMgr.checkIfHostReachMaxGuestLimit(destinationHostVO)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Host name: " + destinationHost.getName() + ": " + destinationHost.getName() + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
}
throw new VirtualMachineMigrationException("Destination host: " + destinationHost.getName() + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
}
// Check host tags
final ServiceOffering serviceOffering = _serviceOfferingDao.findById(vm.getServiceOfferingId());
if (serviceOffering != null) {
final String requiredHostTag = serviceOffering.getHostTag();
final List<String> hostTags = _hostTagsDao.gethostTags(destinationHost.getId());
boolean foundRequiredHostTag = false;
for (final String hostTag : hostTags) {
if (hostTag.equals(requiredHostTag)) {
foundRequiredHostTag = true;
break;
}
}
if (!foundRequiredHostTag && requiredHostTag != null) {
throw new VirtualMachineMigrationException("Destination host: " + destinationHost.getName() + " does not have required host tag " + requiredHostTag);
}
}
final UserVmVO uservm = _vmDao.findById(vmId);
if (uservm != null) {
collectVmDiskStatistics(uservm);
}
_itMgr.migrate(vm.getUuid(), srcHostId, dest);
final VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
if (vmInstance.getType().equals(VirtualMachineType.User)) {
return _vmDao.findById(vmId);
} else {
return vmInstance;
}
}
Aggregations