Search in sources :

Example 46 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class UserVmManagerImpl method vmStorageMigration.

@Override
public VirtualMachine vmStorageMigration(Long vmId, StoragePool destPool) {
    // access check - only root admin can migrate VM
    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!");
    }
    VMInstanceVO vm = _vmInstanceDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("Unable to find the VM by id=" + vmId);
    }
    if (vm.getState() != State.Stopped) {
        InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Stopped, unable to migrate the vm having the specified id");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    if (vm.getType() != VirtualMachine.Type.User) {
        throw new InvalidParameterValueException("can only do storage migration on user vm");
    }
    List<VolumeVO> vols = _volsDao.findByInstance(vm.getId());
    if (vols.size() > 1) {
        throw new InvalidParameterValueException("Data disks attached to the vm, can not migrate. Need to dettach data disks at first");
    }
    // Check that Vm does not have VM Snapshots
    if (_vmSnapshotDao.findByVm(vmId).size() > 0) {
        throw new InvalidParameterValueException("VM's disk cannot be migrated, please remove all the VM Snapshots for this VM");
    }
    HypervisorType destHypervisorType = destPool.getHypervisor();
    if (destHypervisorType == null) {
        destHypervisorType = _clusterDao.findById(destPool.getClusterId()).getHypervisorType();
    }
    if (vm.getHypervisorType() != destHypervisorType) {
        throw new InvalidParameterValueException("hypervisor is not compatible: dest: " + destHypervisorType.toString() + ", vm: " + vm.getHypervisorType().toString());
    }
    _itMgr.storageMigration(vm.getUuid(), destPool);
    return _vmDao.findById(vm.getId());
}
Also used : HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) Account(com.cloud.user.Account) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Example 47 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class UserVmManagerImpl method destroyVm.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_DESTROY, eventDescription = "destroying Vm", async = true)
public UserVm destroyVm(DestroyVMCmd cmd) throws ResourceUnavailableException, ConcurrentOperationException {
    CallContext ctx = CallContext.current();
    long vmId = cmd.getId();
    boolean expunge = cmd.getExpunge();
    // When trying to expunge, permission is denied when the caller is not an admin and the AllowUserExpungeRecoverVm is false for the caller.
    if (expunge && !_accountMgr.isAdmin(ctx.getCallingAccount().getId()) && !AllowUserExpungeRecoverVm.valueIn(cmd.getEntityOwnerId())) {
        throw new PermissionDeniedException("Parameter " + ApiConstants.EXPUNGE + " can be passed by Admin only. Or when the allow.user.expunge.recover.vm key is set.");
    }
    UserVm destroyedVm = destroyVm(vmId, expunge);
    if (expunge) {
        UserVmVO vm = _vmDao.findById(vmId);
        if (!expunge(vm, ctx.getCallingUserId(), ctx.getCallingAccount())) {
            throw new CloudRuntimeException("Failed to expunge vm " + destroyedVm);
        }
    }
    return destroyedVm;
}
Also used : UserVm(com.cloud.uservm.UserVm) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) CallContext(org.apache.cloudstack.context.CallContext) ActionEvent(com.cloud.event.ActionEvent)

Example 48 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class UserVmManagerImpl method migrateVirtualMachineWithVolume.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true)
public VirtualMachine migrateVirtualMachineWithVolume(Long vmId, Host destinationHost, Map<String, String> volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
    // Access check - only root administrator can migrate VM.
    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!");
    }
    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);
        }
        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.VMware) && !vm.getHypervisorType().equals(HypervisorType.KVM) && !vm.getHypervisorType().equals(HypervisorType.Ovm) && !vm.getHypervisorType().equals(HypervisorType.Hyperv) && !vm.getHypervisorType().equals(HypervisorType.Simulator)) {
        throw new InvalidParameterValueException("Unsupported hypervisor type for vm migration, we support" + " XenServer/VMware/KVM only");
    }
    long srcHostId = vm.getHostId();
    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());
    }
    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");
    }
    List<VolumeVO> vmVolumes = _volsDao.findUsableVolumesForInstance(vm.getId());
    Map<Long, Long> volToPoolObjectMap = new HashMap<Long, Long>();
    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 (Map.Entry<String, String> entry : volumeToPool.entrySet()) {
            VolumeVO volume = _volsDao.findByUuid(entry.getKey());
            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(Long.valueOf(volume.getId()), Long.valueOf(pool.getId()));
            }
        }
    }
    // Check if all the volumes are in the correct state.
    for (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.
    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());
}
Also used : HypervisorCapabilitiesVO(com.cloud.hypervisor.HypervisorCapabilitiesVO) Account(com.cloud.user.Account) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Host(com.cloud.host.Host) HostVO(com.cloud.host.HostVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ActionEvent(com.cloud.event.ActionEvent)

Example 49 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class UserVmManagerImpl method stopVirtualMachine.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_STOP, eventDescription = "stopping Vm", async = true)
public UserVm stopVirtualMachine(long vmId, boolean forced) throws ConcurrentOperationException {
    // Input validation
    Account caller = CallContext.current().getCallingAccount();
    Long userId = CallContext.current().getCallingUserId();
    // if account is removed, return error
    if (caller != null && caller.getRemoved() != null) {
        throw new PermissionDeniedException("The account " + caller.getUuid() + " is removed");
    }
    UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
    }
    _userDao.findById(userId);
    boolean status = false;
    try {
        VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
        if (forced) {
            status = vmEntity.stopForced(Long.toString(userId));
        } else {
            status = vmEntity.stop(Long.toString(userId));
        }
        if (status) {
            return _vmDao.findById(vmId);
        } else {
            return null;
        }
    } catch (ResourceUnavailableException e) {
        throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e);
    } catch (CloudException e) {
        throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e);
    }
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualMachineEntity(org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) CloudException(com.cloud.exception.CloudException) ActionEvent(com.cloud.event.ActionEvent)

Example 50 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class AffinityGroupServiceImpl method updateVMAffinityGroups.

@Override
public UserVm updateVMAffinityGroups(Long vmId, List<Long> affinityGroupIds) {
    // Verify input parameters
    UserVmVO vmInstance = _userVmDao.findById(vmId);
    if (vmInstance == null) {
        throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
    }
    // Check that the VM is stopped
    if (!vmInstance.getState().equals(State.Stopped)) {
        s_logger.warn("Unable to update affinity groups of the virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState());
        throw new InvalidParameterValueException("Unable update affinity groups of the virtual machine " + vmInstance.toString() + " " + "in state " + vmInstance.getState() + "; make sure the virtual machine is stopped and not in an error state before updating.");
    }
    Account caller = CallContext.current().getCallingAccount();
    Account owner = _accountMgr.getAccount(vmInstance.getAccountId());
    // check that the affinity groups exist
    for (Long affinityGroupId : affinityGroupIds) {
        AffinityGroupVO ag = _affinityGroupDao.findById(affinityGroupId);
        if (ag == null) {
            throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupId);
        } else {
            // verify permissions
            _accountMgr.checkAccess(caller, null, true, owner, ag);
            // owner of these entities is same
            if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
                if (ag.getAccountId() != owner.getAccountId()) {
                    throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's account");
                }
            }
        }
    }
    _affinityGroupVMMapDao.updateMap(vmId, affinityGroupIds);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Updated VM :" + vmId + " affinity groups to =" + affinityGroupIds);
    }
    // APIResponseHelper will pull out the updated affinitygroups.
    return vmInstance;
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Aggregations

PermissionDeniedException (com.cloud.exception.PermissionDeniedException)82 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)70 Account (com.cloud.user.Account)69 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)26 ActionEvent (com.cloud.event.ActionEvent)23 ArrayList (java.util.ArrayList)22 Project (com.cloud.projects.Project)16 DB (com.cloud.utils.db.DB)15 HashMap (java.util.HashMap)15 DataCenterVO (com.cloud.dc.DataCenterVO)13 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)13 ConfigurationException (javax.naming.ConfigurationException)13 DomainVO (com.cloud.domain.DomainVO)11 Pair (com.cloud.utils.Pair)11 List (java.util.List)11 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)10 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)10 VolumeVO (com.cloud.storage.VolumeVO)10 TransactionStatus (com.cloud.utils.db.TransactionStatus)10 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)8