Search in sources :

Example 51 with UserVmVO

use of com.cloud.vm.UserVmVO in project cloudstack by apache.

the class VMSnapshotManagerImpl method syncVMSnapshot.

@Override
public boolean syncVMSnapshot(VMInstanceVO vm, Long hostId) {
    try {
        UserVmVO userVm = _userVMDao.findById(vm.getId());
        if (userVm == null)
            return false;
        List<VMSnapshotVO> vmSnapshotsInExpungingStates = _vmSnapshotDao.listByInstanceId(vm.getId(), VMSnapshot.State.Expunging, VMSnapshot.State.Reverting, VMSnapshot.State.Creating);
        for (VMSnapshotVO vmSnapshotVO : vmSnapshotsInExpungingStates) {
            VMSnapshotStrategy strategy = findVMSnapshotStrategy(vmSnapshotVO);
            if (vmSnapshotVO.getState() == VMSnapshot.State.Expunging) {
                return strategy.deleteVMSnapshot(vmSnapshotVO);
            } else if (vmSnapshotVO.getState() == VMSnapshot.State.Creating) {
                return strategy.takeVMSnapshot(vmSnapshotVO) != null;
            } else if (vmSnapshotVO.getState() == VMSnapshot.State.Reverting) {
                return strategy.revertVMSnapshot(vmSnapshotVO);
            }
        }
    } catch (Exception e) {
        s_logger.error(e.getMessage(), e);
        if (_vmSnapshotDao.listByInstanceId(vm.getId(), VMSnapshot.State.Expunging).size() == 0)
            return true;
        else
            return false;
    }
    return false;
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) VMSnapshotStrategy(org.apache.cloudstack.engine.subsystem.api.storage.VMSnapshotStrategy) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConfigurationException(javax.naming.ConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException)

Example 52 with UserVmVO

use of com.cloud.vm.UserVmVO in project cloudstack by apache.

the class AffinityGroupServiceImplTest method updateAffinityGroupVMRunning.

@Test(expected = InvalidParameterValueException.class)
public void updateAffinityGroupVMRunning() throws ResourceInUseException {
    when(_acctMgr.finalizeOwner((Account) anyObject(), anyString(), anyLong(), anyLong())).thenReturn(acct);
    UserVmVO vm = new UserVmVO(10L, "test", "test", 101L, HypervisorType.Any, 21L, false, false, DOMAIN_ID, 200L, 1, 5L, "", "test");
    vm.setState(VirtualMachine.State.Running);
    when(_vmDao.findById(10L)).thenReturn(vm);
    List<Long> affinityGroupIds = new ArrayList<Long>();
    affinityGroupIds.add(20L);
    _affinityService.updateVMAffinityGroups(10L, affinityGroupIds);
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) Matchers.anyLong(org.mockito.Matchers.anyLong) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 53 with UserVmVO

use of com.cloud.vm.UserVmVO in project cloudstack by apache.

the class UnmanagedVMsManagerImplTest method unmanageVMInstanceExistingISOAttachedTest.

@Test(expected = UnsupportedServiceException.class)
public void unmanageVMInstanceExistingISOAttachedTest() {
    UserVmVO userVmVO = mock(UserVmVO.class);
    when(userVmDao.findById(virtualMachineId)).thenReturn(userVmVO);
    when(userVmVO.getIsoId()).thenReturn(3L);
    unmanagedVMsManager.unmanageVMInstance(virtualMachineId);
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 54 with UserVmVO

use of com.cloud.vm.UserVmVO in project cloudstack by apache.

the class StoragePoolAutomationImpl method cancelMaintain.

@Override
public boolean cancelMaintain(DataStore store) {
    // Change the storage state back to up
    Long userId = CallContext.current().getCallingUserId();
    User user = _userDao.findById(userId);
    Account account = CallContext.current().getCallingAccount();
    StoragePoolVO poolVO = primaryDataStoreDao.findById(store.getId());
    StoragePool pool = (StoragePool) store;
    // Handeling the Zone wide and cluster wide primay storage
    List<HostVO> hosts = new ArrayList<HostVO>();
    // 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 (HostVO host : hosts) {
        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 succeeded");
            }
            if (pool.getPoolType() == Storage.StoragePoolType.DatastoreCluster) {
                s_logger.debug(String.format("Started synchronising datastore cluster storage pool %s with vCenter", pool.getUuid()));
                storageManager.syncDatastoreClusterStoragePool(pool.getId(), ((ModifyStoragePoolAnswer) answer).getDatastoreClusterChildren(), host.getId());
            }
        }
    }
    // 2. Get a list of pending work for this queue
    List<StoragePoolWorkVO> pendingWork = _storagePoolWorkDao.listPendingWorkForCancelMaintenanceByPoolId(poolVO.getId());
    // 3. work through the queue
    for (StoragePoolWorkVO work : pendingWork) {
        try {
            VMInstanceVO vmInstance = vmDao.findById(work.getVmId());
            if (vmInstance == null) {
                continue;
            }
            // proxy
            if (vmInstance.getType().equals(VirtualMachine.Type.ConsoleProxy)) {
                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)) {
                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)) {
                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 {
                    UserVmVO userVm = userVmDao.findById(vmInstance.getId());
                    vmMgr.advanceStart(userVm.getUuid(), null, null);
                    work.setStartedAfterMaintenance(true);
                    _storagePoolWorkDao.update(work.getId(), work);
                }
            }
        } catch (Exception e) {
            s_logger.debug("Failed start vm", e);
            throw new CloudRuntimeException(e.toString());
        }
    }
    return false;
}
Also used : Account(com.cloud.user.Account) SecondaryStorageVmVO(com.cloud.vm.SecondaryStorageVmVO) UserVmVO(com.cloud.vm.UserVmVO) User(com.cloud.user.User) ArrayList(java.util.ArrayList) VMInstanceVO(com.cloud.vm.VMInstanceVO) HostVO(com.cloud.host.HostVO) ModifyStoragePoolCommand(com.cloud.agent.api.ModifyStoragePoolCommand) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ModifyStoragePoolAnswer(com.cloud.agent.api.ModifyStoragePoolAnswer) Answer(com.cloud.agent.api.Answer) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) ConsoleProxyVO(com.cloud.vm.ConsoleProxyVO) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 55 with UserVmVO

use of com.cloud.vm.UserVmVO in project cloudstack by apache.

the class ProjectManagerImpl method deleteProject.

@Override
@ActionEvent(eventType = EventTypes.EVENT_PROJECT_DELETE, eventDescription = "deleting project", async = true)
public boolean deleteProject(long projectId, Boolean isCleanup) {
    CallContext ctx = CallContext.current();
    ProjectVO project = getProject(projectId);
    // verify input parameters
    if (project == null) {
        throw new InvalidParameterValueException("Unable to find project by id " + projectId);
    }
    CallContext.current().setProject(project);
    _accountMgr.checkAccess(ctx.getCallingAccount(), AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId()));
    if (isCleanup != null && isCleanup) {
        return deleteProject(ctx.getCallingAccount(), ctx.getCallingUserId(), project);
    } else {
        List<VMTemplateVO> userTemplates = _templateDao.listByAccountId(project.getProjectAccountId());
        List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.listByAccountId(project.getProjectAccountId());
        List<UserVmVO> vms = _userVmDao.listByAccountId(project.getProjectAccountId());
        List<VolumeVO> volumes = _volumeDao.findDetachedByAccount(project.getProjectAccountId());
        List<NetworkVO> networks = _networkDao.listByOwner(project.getProjectAccountId());
        List<? extends Vpc> vpcs = _vpcMgr.getVpcsForAccount(project.getProjectAccountId());
        Optional<String> message = Stream.of(userTemplates, vmSnapshots, vms, volumes, networks, vpcs).filter(entity -> !entity.isEmpty()).map(entity -> entity.size() + " " + entity.get(0).getEntityType().getSimpleName() + " to clean up").findFirst();
        if (message.isEmpty()) {
            return deleteProject(ctx.getCallingAccount(), ctx.getCallingUserId(), project);
        }
        CloudRuntimeException e = new CloudRuntimeException("Can't delete the project yet because it has " + message.get());
        e.addProxyObject(project.getUuid(), "projectId");
        throw e;
    }
}
Also used : Role(com.cloud.projects.ProjectAccount.Role) SMTPMailSender(org.apache.cloudstack.utils.mailing.SMTPMailSender) MessagingException(javax.mail.MessagingException) Transaction(com.cloud.utils.db.Transaction) DomainManager(com.cloud.user.DomainManager) TransactionCallbackWithExceptionNoReturn(com.cloud.utils.db.TransactionCallbackWithExceptionNoReturn) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) MailAddress(org.apache.cloudstack.utils.mailing.MailAddress) SecureRandom(java.security.SecureRandom) ResourceType(com.cloud.configuration.Resource.ResourceType) Logger(org.apache.log4j.Logger) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) Map(java.util.Map) ResourceLimitService(com.cloud.user.ResourceLimitService) DomainDao(com.cloud.domain.dao.DomainDao) Config(com.cloud.configuration.Config) CallContext(org.apache.cloudstack.context.CallContext) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ManagedContextRunnable(org.apache.cloudstack.managed.context.ManagedContextRunnable) TransactionCallback(com.cloud.utils.db.TransactionCallback) TimeZone(java.util.TimeZone) TransactionStatus(com.cloud.utils.db.TransactionStatus) ProjectRole(org.apache.cloudstack.acl.ProjectRole) ProjectJoinDao(com.cloud.api.query.dao.ProjectJoinDao) Set(java.util.Set) ApiDBUtils(com.cloud.api.ApiDBUtils) Account(com.cloud.user.Account) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) VpcManager(com.cloud.network.vpc.VpcManager) VMSnapshotDao(com.cloud.vm.snapshot.dao.VMSnapshotDao) List(java.util.List) Stream(java.util.stream.Stream) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) Optional(java.util.Optional) AccountDao(com.cloud.user.dao.AccountDao) ProjectRoleDao(org.apache.cloudstack.acl.dao.ProjectRoleDao) UnsupportedEncodingException(java.io.UnsupportedEncodingException) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) ManagerBase(com.cloud.utils.component.ManagerBase) ProjectAccountJoinDao(com.cloud.api.query.dao.ProjectAccountJoinDao) VMTemplateDao(com.cloud.storage.dao.VMTemplateDao) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) AccessType(org.apache.cloudstack.acl.SecurityChecker.AccessType) BooleanUtils(org.apache.commons.lang3.BooleanUtils) ConfigurationException(javax.naming.ConfigurationException) NetworkDao(com.cloud.network.dao.NetworkDao) EventTypes(com.cloud.event.EventTypes) ProjectInvitationDao(com.cloud.projects.dao.ProjectInvitationDao) Inject(javax.inject.Inject) HashSet(java.util.HashSet) ConfigKey(org.apache.cloudstack.framework.config.ConfigKey) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UserDao(com.cloud.user.dao.UserDao) State(com.cloud.projects.Project.State) User(com.cloud.user.User) NetworkVO(com.cloud.network.dao.NetworkVO) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) VolumeDao(com.cloud.storage.dao.VolumeDao) Configurable(org.apache.cloudstack.framework.config.Configurable) NamedThreadFactory(com.cloud.utils.concurrency.NamedThreadFactory) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ProjectDao(com.cloud.projects.dao.ProjectDao) VMTemplateVO(com.cloud.storage.VMTemplateVO) SMTPMailProperties(org.apache.cloudstack.utils.mailing.SMTPMailProperties) ConfigurationManager(com.cloud.configuration.ConfigurationManager) Vpc(com.cloud.network.vpc.Vpc) AccountVO(com.cloud.user.AccountVO) UserVmDao(com.cloud.vm.dao.UserVmDao) DB(com.cloud.utils.db.DB) ResourceTagDao(com.cloud.tags.dao.ResourceTagDao) TimeUnit(java.util.concurrent.TimeUnit) UserVmVO(com.cloud.vm.UserVmVO) Component(org.springframework.stereotype.Component) ProjectAccountDao(com.cloud.projects.dao.ProjectAccountDao) ProjectInvitationJoinDao(com.cloud.api.query.dao.ProjectInvitationJoinDao) ActionEvent(com.cloud.event.ActionEvent) AccountManager(com.cloud.user.AccountManager) DomainVO(com.cloud.domain.DomainVO) ConfigurationDao(org.apache.cloudstack.framework.config.dao.ConfigurationDao) VolumeVO(com.cloud.storage.VolumeVO) UserVmVO(com.cloud.vm.UserVmVO) NetworkVO(com.cloud.network.dao.NetworkVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) CallContext(org.apache.cloudstack.context.CallContext) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ActionEvent(com.cloud.event.ActionEvent)

Aggregations

UserVmVO (com.cloud.vm.UserVmVO)190 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)79 Account (com.cloud.user.Account)50 ArrayList (java.util.ArrayList)45 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)39 HostVO (com.cloud.host.HostVO)34 VMSnapshotVO (com.cloud.vm.snapshot.VMSnapshotVO)33 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)31 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)30 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)28 HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)25 VolumeVO (com.cloud.storage.VolumeVO)25 VMInstanceVO (com.cloud.vm.VMInstanceVO)24 ActionEvent (com.cloud.event.ActionEvent)23 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)22 GuestOSVO (com.cloud.storage.GuestOSVO)20 HashMap (java.util.HashMap)19 ConfigurationException (javax.naming.ConfigurationException)19 Test (org.junit.Test)19 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)18