Search in sources :

Example 51 with UserVm

use of com.cloud.uservm.UserVm in project cloudstack by apache.

the class UnmanagedVMsManagerImpl method migrateImportedVM.

private UserVm migrateImportedVM(HostVO sourceHost, VirtualMachineTemplate template, ServiceOfferingVO serviceOffering, UserVm userVm, final Account owner, List<Pair<DiskProfile, StoragePool>> diskProfileStoragePoolList) {
    UserVm vm = userVm;
    if (vm == null) {
        LOGGER.error(String.format("Failed to check migrations need during VM import"));
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to check migrations need during VM import"));
    }
    if (sourceHost == null || serviceOffering == null || diskProfileStoragePoolList == null) {
        LOGGER.error(String.format("Failed to check migrations need during import, VM: %s", userVm.getInstanceName()));
        cleanupFailedImportVM(vm);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to check migrations need during import, VM: %s", userVm.getInstanceName()));
    }
    if (!hostSupportsServiceOffering(sourceHost, serviceOffering)) {
        LOGGER.debug(String.format("VM %s needs to be migrated", vm.getUuid()));
        final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm, template, serviceOffering, owner, null);
        DeploymentPlanner.ExcludeList excludeList = new DeploymentPlanner.ExcludeList();
        excludeList.addHost(sourceHost.getId());
        final DataCenterDeployment plan = new DataCenterDeployment(sourceHost.getDataCenterId(), sourceHost.getPodId(), sourceHost.getClusterId(), null, null, null);
        DeployDestination dest = null;
        try {
            dest = deploymentPlanningManager.planDeployment(profile, plan, excludeList, null);
        } catch (Exception e) {
            LOGGER.warn(String.format("VM import failed for unmanaged vm: %s during vm migration, finding deployment destination", vm.getInstanceName()), e);
            cleanupFailedImportVM(vm);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm: %s during vm migration, finding deployment destination", vm.getInstanceName()));
        }
        if (dest != null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(" Found " + dest + " for migrating the vm to");
            }
        }
        if (dest == null) {
            cleanupFailedImportVM(vm);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm: %s during vm migration, no deployment destination found", vm.getInstanceName()));
        }
        try {
            if (vm.getState().equals(VirtualMachine.State.Stopped)) {
                VMInstanceVO vmInstanceVO = vmDao.findById(userVm.getId());
                vmInstanceVO.setHostId(dest.getHost().getId());
                vmInstanceVO.setLastHostId(dest.getHost().getId());
                vmDao.update(vmInstanceVO.getId(), vmInstanceVO);
            } else {
                virtualMachineManager.migrate(vm.getUuid(), sourceHost.getId(), dest);
            }
            vm = userVmManager.getUserVm(vm.getId());
        } catch (Exception e) {
            LOGGER.error(String.format("VM import failed for unmanaged vm: %s during vm migration", vm.getInstanceName()), e);
            cleanupFailedImportVM(vm);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm: %s during vm migration. %s", userVm.getInstanceName(), e.getMessage()));
        }
    }
    for (Pair<DiskProfile, StoragePool> diskProfileStoragePool : diskProfileStoragePoolList) {
        if (diskProfileStoragePool == null || diskProfileStoragePool.first() == null || diskProfileStoragePool.second() == null) {
            continue;
        }
        DiskProfile profile = diskProfileStoragePool.first();
        DiskOffering dOffering = diskOfferingDao.findById(profile.getDiskOfferingId());
        if (dOffering == null) {
            continue;
        }
        VolumeVO volumeVO = volumeDao.findById(profile.getVolumeId());
        if (volumeVO == null) {
            continue;
        }
        boolean poolSupportsOfferings = storagePoolSupportsDiskOffering(diskProfileStoragePool.second(), dOffering);
        if (poolSupportsOfferings) {
            continue;
        }
        LOGGER.debug(String.format("Volume %s needs to be migrated", volumeVO.getUuid()));
        Pair<List<? extends StoragePool>, List<? extends StoragePool>> poolsPair = managementService.listStoragePoolsForMigrationOfVolumeInternal(profile.getVolumeId(), null, null, null, null, false);
        if (CollectionUtils.isEmpty(poolsPair.first()) && CollectionUtils.isEmpty(poolsPair.second())) {
            cleanupFailedImportVM(vm);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm: %s during volume ID: %s migration as no suitable pool(s) found", userVm.getInstanceName(), volumeVO.getUuid()));
        }
        List<? extends StoragePool> storagePools = poolsPair.second();
        StoragePool storagePool = null;
        if (CollectionUtils.isNotEmpty(storagePools)) {
            for (StoragePool pool : storagePools) {
                if (diskProfileStoragePool.second().getId() != pool.getId() && storagePoolSupportsDiskOffering(pool, dOffering)) {
                    storagePool = pool;
                    break;
                }
            }
        }
        // For zone-wide pools, at times, suitable storage pools are not returned therefore consider all pools.
        if (storagePool == null && CollectionUtils.isNotEmpty(poolsPair.first())) {
            storagePools = poolsPair.first();
            for (StoragePool pool : storagePools) {
                if (diskProfileStoragePool.second().getId() != pool.getId() && storagePoolSupportsDiskOffering(pool, dOffering)) {
                    storagePool = pool;
                    break;
                }
            }
        }
        if (storagePool == null) {
            cleanupFailedImportVM(vm);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm: %s during volume ID: %s migration as no suitable pool found", userVm.getInstanceName(), volumeVO.getUuid()));
        } else {
            LOGGER.debug(String.format("Found storage pool %s(%s) for migrating the volume %s to", storagePool.getName(), storagePool.getUuid(), volumeVO.getUuid()));
        }
        try {
            Volume volume = null;
            if (vm.getState().equals(VirtualMachine.State.Running)) {
                volume = volumeManager.liveMigrateVolume(volumeVO, storagePool);
            } else {
                volume = volumeManager.migrateVolume(volumeVO, storagePool);
            }
            if (volume == null) {
                String msg = "";
                if (vm.getState().equals(VirtualMachine.State.Running)) {
                    msg = String.format("Live migration for volume ID: %s to destination pool ID: %s failed", volumeVO.getUuid(), storagePool.getUuid());
                } else {
                    msg = String.format("Migration for volume ID: %s to destination pool ID: %s failed", volumeVO.getUuid(), storagePool.getUuid());
                }
                LOGGER.error(msg);
                throw new CloudRuntimeException(msg);
            }
        } catch (Exception e) {
            LOGGER.error(String.format("VM import failed for unmanaged vm: %s during volume migration", vm.getInstanceName()), e);
            cleanupFailedImportVM(vm);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed for unmanaged vm: %s during volume migration. %s", userVm.getInstanceName(), StringUtils.defaultString(e.getMessage())));
        }
    }
    return userVm;
}
Also used : DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) StoragePool(com.cloud.storage.StoragePool) DiskOffering(com.cloud.offering.DiskOffering) VirtualMachineProfileImpl(com.cloud.vm.VirtualMachineProfileImpl) VMInstanceVO(com.cloud.vm.VMInstanceVO) DiskProfile(com.cloud.vm.DiskProfile) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ServerApiException(org.apache.cloudstack.api.ServerApiException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) InsufficientVirtualNetworkCapacityException(com.cloud.exception.InsufficientVirtualNetworkCapacityException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) UserVm(com.cloud.uservm.UserVm) ServerApiException(org.apache.cloudstack.api.ServerApiException) VolumeVO(com.cloud.storage.VolumeVO) Volume(com.cloud.storage.Volume) DeployDestination(com.cloud.deploy.DeployDestination) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DeploymentPlanner(com.cloud.deploy.DeploymentPlanner) ArrayList(java.util.ArrayList) List(java.util.List) VirtualMachineProfile(com.cloud.vm.VirtualMachineProfile)

Example 52 with UserVm

use of com.cloud.uservm.UserVm in project cloudstack by apache.

the class UserVmManagerImpl method addInstanceToGroup.

@Override
@DB
public boolean addInstanceToGroup(final long userVmId, String groupName) {
    UserVmVO vm = _vmDao.findById(userVmId);
    InstanceGroupVO group = _vmGroupDao.findByAccountAndName(vm.getAccountId(), groupName);
    // Create vm group if the group doesn't exist for this account
    if (group == null) {
        group = createVmGroup(groupName, vm.getAccountId());
    }
    if (group != null) {
        UserVm userVm = _vmDao.acquireInLockTable(userVmId);
        if (userVm == null) {
            s_logger.warn("Failed to acquire lock on user vm id=" + userVmId);
        }
        try {
            final InstanceGroupVO groupFinal = group;
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    // don't let the group be deleted when we are assigning vm to
                    // it.
                    InstanceGroupVO ngrpLock = _vmGroupDao.lockRow(groupFinal.getId(), false);
                    if (ngrpLock == null) {
                        s_logger.warn("Failed to acquire lock on vm group id=" + groupFinal.getId() + " name=" + groupFinal.getName());
                        throw new CloudRuntimeException("Failed to acquire lock on vm group id=" + groupFinal.getId() + " name=" + groupFinal.getName());
                    }
                    // Currently don't allow to assign a vm to more than one group
                    if (_groupVMMapDao.listByInstanceId(userVmId) != null) {
                        // Delete all mappings from group_vm_map table
                        List<InstanceGroupVMMapVO> groupVmMaps = _groupVMMapDao.listByInstanceId(userVmId);
                        for (InstanceGroupVMMapVO groupMap : groupVmMaps) {
                            SearchCriteria<InstanceGroupVMMapVO> sc = _groupVMMapDao.createSearchCriteria();
                            sc.addAnd("instanceId", SearchCriteria.Op.EQ, groupMap.getInstanceId());
                            _groupVMMapDao.expunge(sc);
                        }
                    }
                    InstanceGroupVMMapVO groupVmMapVO = new InstanceGroupVMMapVO(groupFinal.getId(), userVmId);
                    _groupVMMapDao.persist(groupVmMapVO);
                }
            });
            return true;
        } finally {
            if (userVm != null) {
                _vmDao.releaseFromLockTable(userVmId);
            }
        }
    }
    return false;
}
Also used : UserVm(com.cloud.uservm.UserVm) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) NodeList(org.w3c.dom.NodeList) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) SearchCriteria(com.cloud.utils.db.SearchCriteria) DB(com.cloud.utils.db.DB)

Example 53 with UserVm

use of com.cloud.uservm.UserVm in project cosmic by MissionCriticalCloud.

the class AttachIsoCmdByAdmin method execute.

@Override
public void execute() {
    CallContext.current().setEventDetails("Vm Id: " + getVirtualMachineId() + " ISO Id: " + getId());
    final boolean result = _templateService.attachIso(id, virtualMachineId);
    if (result) {
        final UserVm userVm = _responseGenerator.findUserVmById(virtualMachineId);
        if (userVm != null) {
            final UserVmResponse response = _responseGenerator.createUserVmResponse(ResponseView.Full, "virtualmachine", userVm).get(0);
            response.setResponseName(DeployVMCmd.getResultObjectName());
            setResponseObject(response);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to attach iso");
        }
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to attach iso");
    }
}
Also used : UserVm(com.cloud.uservm.UserVm) ServerApiException(com.cloud.api.ServerApiException) UserVmResponse(com.cloud.api.response.UserVmResponse)

Example 54 with UserVm

use of com.cloud.uservm.UserVm in project cosmic by MissionCriticalCloud.

the class DetachIsoCmdByAdmin method execute.

@Override
public void execute() {
    final boolean result = _templateService.detachIso(virtualMachineId);
    if (result) {
        final UserVm userVm = _entityMgr.findById(UserVm.class, virtualMachineId);
        final UserVmResponse response = _responseGenerator.createUserVmResponse(ResponseView.Full, "virtualmachine", userVm).get(0);
        response.setResponseName(DeployVMCmd.getResultObjectName());
        setResponseObject(response);
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to detach iso");
    }
}
Also used : UserVm(com.cloud.uservm.UserVm) ServerApiException(com.cloud.api.ServerApiException) UserVmResponse(com.cloud.api.response.UserVmResponse)

Example 55 with UserVm

use of com.cloud.uservm.UserVm in project cosmic by MissionCriticalCloud.

the class ListLoadBalancerRuleInstancesCmdByAdmin method execute.

@Override
public void execute() {
    final Pair<List<? extends UserVm>, List<String>> vmServiceMap = _lbService.listLoadBalancerInstances(this);
    final List<? extends UserVm> result = vmServiceMap.first();
    final List<String> serviceStates = vmServiceMap.second();
    if (!isListLbVmip()) {
        // list lb instances
        final ListResponse<UserVmResponse> response = new ListResponse<>();
        List<UserVmResponse> vmResponses = new ArrayList<>();
        if (result != null) {
            vmResponses = _responseGenerator.createUserVmResponse(ResponseView.Restricted, "loadbalancerruleinstance", result.toArray(new UserVm[result.size()]));
            for (int i = 0; i < result.size(); i++) {
                vmResponses.get(i).setServiceState(serviceStates.get(i));
            }
        }
        response.setResponses(vmResponses);
        response.setResponseName(getCommandName());
        setResponseObject(response);
    } else {
        final ListResponse<LoadBalancerRuleVmMapResponse> lbRes = new ListResponse<>();
        List<UserVmResponse> vmResponses = new ArrayList<>();
        final List<LoadBalancerRuleVmMapResponse> listlbVmRes = new ArrayList<>();
        if (result != null) {
            vmResponses = _responseGenerator.createUserVmResponse(ResponseView.Full, "loadbalancerruleinstance", result.toArray(new UserVm[result.size()]));
            final List<String> ipaddr = null;
            for (int i = 0; i < result.size(); i++) {
                final LoadBalancerRuleVmMapResponse lbRuleVmIpResponse = new LoadBalancerRuleVmMapResponse();
                vmResponses.get(i).setServiceState(serviceStates.get(i));
                lbRuleVmIpResponse.setUserVmResponse(vmResponses.get(i));
                // get vm id from the uuid
                final VirtualMachine lbvm = _entityMgr.findByUuid(VirtualMachine.class, vmResponses.get(i).getId());
                lbRuleVmIpResponse.setIpAddr(_lbService.listLbVmIpAddress(getId(), lbvm.getId()));
                lbRuleVmIpResponse.setObjectName("lbrulevmidip");
                listlbVmRes.add(lbRuleVmIpResponse);
            }
        }
        lbRes.setResponseName(getCommandName());
        lbRes.setResponses(listlbVmRes);
        setResponseObject(lbRes);
    }
}
Also used : ListResponse(com.cloud.api.response.ListResponse) ArrayList(java.util.ArrayList) LoadBalancerRuleVmMapResponse(com.cloud.api.response.LoadBalancerRuleVmMapResponse) UserVmResponse(com.cloud.api.response.UserVmResponse) UserVm(com.cloud.uservm.UserVm) ArrayList(java.util.ArrayList) List(java.util.List) VirtualMachine(com.cloud.vm.VirtualMachine)

Aggregations

UserVm (com.cloud.uservm.UserVm)196 ServerApiException (com.cloud.api.ServerApiException)59 UserVmResponse (com.cloud.api.response.UserVmResponse)59 ArrayList (java.util.ArrayList)54 ServerApiException (org.apache.cloudstack.api.ServerApiException)48 UserVmResponse (org.apache.cloudstack.api.response.UserVmResponse)47 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)32 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)30 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)28 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)28 Network (com.cloud.network.Network)26 Account (com.cloud.user.Account)22 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)21 ManagementServerException (com.cloud.exception.ManagementServerException)21 HashMap (java.util.HashMap)16 ServiceOffering (com.cloud.offering.ServiceOffering)15 DataCenter (com.cloud.dc.DataCenter)14 List (java.util.List)14 ActionEvent (com.cloud.event.ActionEvent)12 VirtualMachineMigrationException (com.cloud.exception.VirtualMachineMigrationException)12