Search in sources :

Example 21 with HypervisorType

use of com.cloud.model.enumeration.HypervisorType in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method createVirtualMachine.

@DB
private UserVm createVirtualMachine(final Zone zone, final ServiceOffering serviceOffering, final VirtualMachineTemplate tmplt, String hostName, final String displayName, final Account owner, final Long diskOfferingId, final Long diskSize, final List<NetworkVO> networkList, final String group, final HTTPMethod httpmethod, final String userData, final String sshKeyPair, final HypervisorType hypervisor, final Account caller, final Map<Long, IpAddresses> requestedIps, final IpAddresses defaultIps, final Boolean isDisplayVm, final String keyboard, final List<Long> affinityGroupIdList, final Map<String, String> customParameters, final String customId, final DiskControllerType diskControllerType, final Long bootMenuTimeout, MaintenancePolicy maintenancePolicy, OptimiseFor optimiseFor, String manufacturerString, String bootOrder) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException {
    _accountMgr.checkAccess(caller, null, true, owner);
    if (owner.getState() == Account.State.disabled) {
        throw new PermissionDeniedException("The owner of vm to deploy is disabled: " + owner);
    }
    final VMTemplateVO template = _templateDao.findById(tmplt.getId());
    if (template != null) {
        _templateDao.loadDetails(template);
    }
    if (optimiseFor == null) {
        if (template.getOptimiseFor() != null) {
            optimiseFor = template.getOptimiseFor();
        } else {
            optimiseFor = OptimiseFor.Generic;
        }
    }
    if (manufacturerString == null) {
        manufacturerString = template.getManufacturerString();
    }
    if (maintenancePolicy == null) {
        maintenancePolicy = template.getMaintenancePolicy();
    }
    Boolean macLarning = template.getMacLearning();
    String cpuFlags = template.getCpuFlags();
    final long accountId = owner.getId();
    assert !(requestedIps != null && (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null)) : "requestedIp list and defaultNetworkIp should never be " + "specified together";
    if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getId());
    }
    // check if zone is dedicated
    final DedicatedResourceVO dedicatedZone = _dedicatedDao.findByZoneId(zone.getId());
    if (dedicatedZone != null) {
        final DomainVO domain = _domainDao.findById(dedicatedZone.getDomainId());
        if (domain == null) {
            throw new CloudRuntimeException("Unable to find the domain " + zone.getDomainId() + " for the zone: " + zone);
        }
        // check that caller can operate with domain
        _configMgr.checkZoneAccess(caller, zone);
        // check that vm owner can create vm in the domain
        _configMgr.checkZoneAccess(owner, zone);
    }
    ServiceOfferingVO offering = _serviceOfferingDao.findById(serviceOffering.getId());
    // check if account/domain is with in resource limits to create a new vm
    final boolean isIso = ImageFormat.ISO == template.getFormat();
    long size = 0;
    // custom root disk size, resizes base template to larger size
    if (customParameters.containsKey("rootdisksize")) {
        final Long rootDiskSize = NumbersUtil.parseLong(customParameters.get("rootdisksize"), -1);
        if (rootDiskSize <= 0) {
            throw new InvalidParameterValueException("Root disk size should be a positive number.");
        }
        size = rootDiskSize * GB_TO_BYTES;
    }
    if (diskOfferingId != null) {
        final DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId);
        if (diskOffering != null && diskOffering.isCustomized()) {
            if (diskSize == null) {
                throw new InvalidParameterValueException("This disk offering requires a custom size specified");
            }
            final Long customDiskOfferingMaxSize = VolumeOrchestrationService.CustomDiskOfferingMaxSize.value();
            final Long customDiskOfferingMinSize = VolumeOrchestrationService.CustomDiskOfferingMinSize.value();
            if (diskSize < customDiskOfferingMinSize || diskSize > customDiskOfferingMaxSize) {
                throw new InvalidParameterValueException("VM Creation failed. Volume size: " + diskSize + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize + " Min:" + customDiskOfferingMinSize);
            }
            size += diskSize * GB_TO_BYTES;
        }
        size += _diskOfferingDao.findById(diskOfferingId).getDiskSize();
    }
    resourceLimitCheck(owner, isDisplayVm, new Long(offering.getCpu()), new Long(offering.getRamSize()));
    _resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, isIso || diskOfferingId == null ? 1 : 2);
    _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, size);
    // check that the affinity groups exist
    if (affinityGroupIdList != null) {
        for (final Long affinityGroupId : affinityGroupIdList) {
            final AffinityGroupVO ag = _affinityGroupDao.findById(affinityGroupId);
            if (ag == null) {
                throw new InvalidParameterValueException("Unable to find affinity group " + ag);
            } else if (!_affinityGroupService.isAffinityGroupProcessorAvailable(ag.getType())) {
                throw new InvalidParameterValueException("Affinity group type is not supported for group: " + ag + " ,type: " + ag.getType() + " , Please try again after removing the affinity group");
            } else {
                // verify permissions
                if (ag.getAclType() == ACLType.Domain) {
                    _accountMgr.checkAccess(caller, null, false, owner, ag);
                    // make sure the owner of these entities is same
                    if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
                        if (!_affinityGroupService.isAffinityGroupAvailableInDomain(ag.getId(), owner.getDomainId())) {
                            throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's domain");
                        }
                    }
                } else {
                    _accountMgr.checkAccess(caller, null, true, owner, ag);
                    // make sure the owner of these entities is same
                    if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
                        if (ag.getDomainId() != owner.getDomainId()) {
                            throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's domain");
                        }
                    }
                }
            }
        }
    }
    final HypervisorType hypervisorType;
    if (template.getHypervisorType() == null || template.getHypervisorType() == HypervisorType.None) {
        if (hypervisor == null || hypervisor == HypervisorType.None) {
            throw new InvalidParameterValueException("hypervisor parameter is needed to deploy VM or the hypervisor parameter value passed is invalid");
        }
        hypervisorType = hypervisor;
    } else {
        if (hypervisor != null && hypervisor != HypervisorType.None && hypervisor != template.getHypervisorType()) {
            throw new InvalidParameterValueException("Hypervisor passed to the deployVm call, is different from the hypervisor type of the template");
        }
        hypervisorType = template.getHypervisorType();
    }
    // check if we have available pools for vm deployment
    final long availablePools = _storagePoolDao.countPoolsByStatus(StoragePoolStatus.Up);
    if (availablePools < 1) {
        throw new StorageUnavailableException("There are no available pools in the UP state for vm deployment", -1);
    }
    if (template.getTemplateType().equals(TemplateType.SYSTEM)) {
        throw new InvalidParameterValueException("Unable to use system template " + template.getId() + " to deploy a user vm");
    }
    final List<VMTemplateZoneVO> listZoneTemplate = _templateZoneDao.listByZoneTemplate(zone.getId(), template.getId());
    if (listZoneTemplate == null || listZoneTemplate.isEmpty()) {
        throw new InvalidParameterValueException("The template " + template.getId() + " is not available for use");
    }
    if (isIso && !template.isBootable()) {
        throw new InvalidParameterValueException("Installing from ISO requires an ISO that is bootable: " + template.getId());
    }
    // Check templates permissions
    _accountMgr.checkAccess(owner, AccessType.UseEntry, false, template);
    // check if the user data is correct
    validateUserData(userData, httpmethod);
    // Find an SSH public key corresponding to the key pair name, if one is
    // given
    String sshPublicKey = null;
    if (sshKeyPair != null && !sshKeyPair.equals("")) {
        final SSHKeyPair pair = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), sshKeyPair);
        if (pair == null) {
            throw new InvalidParameterValueException("A key pair with name '" + sshKeyPair + "' was not found.");
        }
        sshPublicKey = pair.getPublicKey();
    }
    final List<Pair<NetworkVO, NicProfile>> networks = new ArrayList<>();
    final LinkedHashMap<String, NicProfile> networkNicMap = new LinkedHashMap<>();
    short defaultNetworkNumber = 0;
    boolean vpcNetwork = false;
    for (final NetworkVO network : networkList) {
        if (network.getDataCenterId() != zone.getId()) {
            if (!network.isStrechedL2Network()) {
                throw new InvalidParameterValueException("Network id=" + network.getId() + " doesn't belong to zone " + zone.getId());
            }
            final NetworkOffering ntwkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
            final Long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType());
            if (physicalNetworkId == null) {
                throw new InvalidParameterValueException("Network in which is VM getting deployed could not be" + " streched to the zone, as we could not find a valid physical network");
            }
            final String provider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Connectivity);
            if (!_networkModel.isProviderEnabledInPhysicalNetwork(physicalNetworkId, provider)) {
                throw new InvalidParameterValueException("Network in which is VM getting deployed could not be" + " streched to the zone, as we could not find a valid physical network");
            }
        }
        // relax the check if the caller is admin account
        if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
            if (!(network.getGuestType() == GuestType.Shared && network.getAclType() == ACLType.Domain) && !(network.getAclType() == ACLType.Account && network.getAccountId() == accountId)) {
                throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vm");
            }
        }
        IpAddresses requestedIpPair = null;
        if (requestedIps != null && !requestedIps.isEmpty()) {
            requestedIpPair = requestedIps.get(network.getId());
        }
        if (requestedIpPair == null) {
            requestedIpPair = new IpAddresses(null, null);
        } else {
            _networkModel.checkRequestedIpAddresses(network.getId(), requestedIpPair);
        }
        NicProfile profile = new NicProfile(requestedIpPair.getIp4Address(), requestedIpPair.getIp6Address(), requestedIpPair.getMacAddress());
        if (defaultNetworkNumber == 0) {
            defaultNetworkNumber++;
            // if user requested specific ip for default network, add it
            if (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null) {
                _networkModel.checkRequestedIpAddresses(network.getId(), defaultIps);
                profile = new NicProfile(defaultIps.getIp4Address(), defaultIps.getIp6Address());
            } else if (defaultIps.getMacAddress() != null) {
                profile = new NicProfile(null, null, defaultIps.getMacAddress());
            }
            profile.setDefaultNic(true);
            if (!_networkModel.areServicesSupportedInNetwork(network.getId(), new Service[] { Service.UserData })) {
                if (userData != null && !userData.isEmpty()) {
                    throw new InvalidParameterValueException("Unable to deploy VM as UserData is provided while deploying the VM, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
                }
                if (sshPublicKey != null && !sshPublicKey.isEmpty()) {
                    throw new InvalidParameterValueException("Unable to deploy VM as SSH keypair is provided while deploying the VM, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
                }
                if (template.getEnablePassword()) {
                    throw new InvalidParameterValueException("Unable to deploy VM as template " + template.getId() + " is password enabled, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
                }
            }
        }
        networks.add(new Pair<>(network, profile));
        networkNicMap.put(network.getUuid(), profile);
    }
    // gateway for the vm
    if (defaultNetworkNumber == 0) {
        throw new InvalidParameterValueException("At least 1 default network has to be specified for the vm");
    } else if (defaultNetworkNumber > 1) {
        throw new InvalidParameterValueException("Only 1 default network per vm is supported");
    }
    final long id = _vmDao.getNextInSequence(Long.class, "id");
    if (hostName != null) {
        // Check is hostName is RFC compliant
        checkNameForRFCCompliance(hostName);
    }
    final String instanceName;
    final String uuidName = _uuidMgr.generateUuid(UserVm.class, customId);
    if (hostName == null) {
        // Generate name using uuid and instance.name global config
        hostName = generateHostName(uuidName);
    }
    if (hostName != null) {
        // Check is hostName is RFC compliant
        checkNameForRFCCompliance(hostName);
    }
    instanceName = VirtualMachineName.getVmName(id, owner.getId(), _instance);
    // Check if VM with instanceName already exists.
    final VMInstanceVO vmObj = _vmInstanceDao.findVMByInstanceName(instanceName);
    if (vmObj != null && vmObj.getState() != VirtualMachine.State.Expunging) {
        throw new InvalidParameterValueException("There already exists a VM by the display name supplied");
    }
    checkIfHostNameUniqueInNtwkDomain(hostName, networkList);
    long userId = CallContext.current().getCallingUserId();
    if (CallContext.current().getCallingAccount().getId() != owner.getId()) {
        final List<UserVO> userVOs = _userDao.listByAccount(owner.getAccountId());
        if (!userVOs.isEmpty()) {
            userId = userVOs.get(0).getId();
        }
    }
    final UserVmVO vm = commitUserVm(zone, template, hostName, displayName, owner, diskOfferingId, diskSize, userData, caller, isDisplayVm, keyboard, accountId, userId, offering, isIso, sshPublicKey, networkNicMap, id, instanceName, uuidName, hypervisorType, customParameters, diskControllerType, manufacturerString, optimiseFor, macLarning, cpuFlags, maintenancePolicy, bootMenuTimeout, bootOrder);
    // Assign instance to the group
    try {
        if (group != null) {
            final boolean addToGroup = addInstanceToGroup(Long.valueOf(id), group);
            if (!addToGroup) {
                throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
            }
        }
    } catch (final Exception ex) {
        throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
    }
    if (affinityGroupIdList != null && !affinityGroupIdList.isEmpty()) {
        _affinityGroupVMMapDao.updateMap(vm.getId(), affinityGroupIdList);
    }
    CallContext.current().putContextParameter(VirtualMachine.class, vm.getUuid());
    return vm;
}
Also used : VMTemplateZoneVO(com.cloud.storage.VMTemplateZoneVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) ArrayList(java.util.ArrayList) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) LinkedHashMap(java.util.LinkedHashMap) StorageUnavailableException(com.cloud.legacymodel.exceptions.StorageUnavailableException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) SSHKeyPair(com.cloud.legacymodel.user.SSHKeyPair) Pair(com.cloud.legacymodel.utils.Pair) AffinityGroupVO(com.cloud.affinity.AffinityGroupVO) SSHKeyPair(com.cloud.legacymodel.user.SSHKeyPair) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkOffering(com.cloud.offering.NetworkOffering) AccountService(com.cloud.user.AccountService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Service(com.cloud.legacymodel.network.Network.Service) OrchestrationService(com.cloud.engine.service.api.OrchestrationService) ExecutorService(java.util.concurrent.ExecutorService) NetworkOrchestrationService(com.cloud.engine.orchestration.service.NetworkOrchestrationService) ManagementService(com.cloud.server.ManagementService) ResourceLimitService(com.cloud.user.ResourceLimitService) VolumeApiService(com.cloud.storage.VolumeApiService) AffinityGroupService(com.cloud.affinity.AffinityGroupService) VolumeOrchestrationService(com.cloud.engine.orchestration.service.VolumeOrchestrationService) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) VirtualMachineMigrationException(com.cloud.legacymodel.exceptions.VirtualMachineMigrationException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ExecutionException(com.cloud.legacymodel.exceptions.ExecutionException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) CloudException(com.cloud.legacymodel.exceptions.CloudException) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) ConfigurationException(javax.naming.ConfigurationException) StorageUnavailableException(com.cloud.legacymodel.exceptions.StorageUnavailableException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ManagementServerException(com.cloud.legacymodel.exceptions.ManagementServerException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) HypervisorType(com.cloud.model.enumeration.HypervisorType) IpAddresses(com.cloud.legacymodel.network.Network.IpAddresses) DomainVO(com.cloud.domain.DomainVO) UserVO(com.cloud.user.UserVO) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) DB(com.cloud.utils.db.DB)

Example 22 with HypervisorType

use of com.cloud.model.enumeration.HypervisorType in project cosmic by MissionCriticalCloud.

the class XenserverSnapshotStrategy method backupSnapshot.

@Override
public SnapshotInfo backupSnapshot(final SnapshotInfo snapshot) {
    final SnapshotInfo parentSnapshot = snapshot.getParent();
    if (parentSnapshot != null && snapshot.getPath().equalsIgnoreCase(parentSnapshot.getPath())) {
        s_logger.debug("backup an empty snapshot");
        // don't need to backup this snapshot
        final SnapshotDataStoreVO parentSnapshotOnBackupStore = snapshotStoreDao.findBySnapshot(parentSnapshot.getId(), DataStoreRole.Image);
        if (parentSnapshotOnBackupStore != null && parentSnapshotOnBackupStore.getState() == State.Ready) {
            final DataStore store = dataStoreMgr.getDataStore(parentSnapshotOnBackupStore.getDataStoreId(), parentSnapshotOnBackupStore.getRole());
            final SnapshotInfo snapshotOnImageStore = (SnapshotInfo) store.create(snapshot);
            snapshotOnImageStore.processEvent(Event.CreateOnlyRequested);
            final SnapshotObjectTO snapTO = new SnapshotObjectTO();
            snapTO.setPath(parentSnapshotOnBackupStore.getInstallPath());
            final CreateObjectAnswer createSnapshotAnswer = new CreateObjectAnswer(snapTO);
            snapshotOnImageStore.processEvent(Event.OperationSuccessed, createSnapshotAnswer);
            final SnapshotObject snapObj = (SnapshotObject) snapshot;
            try {
                snapObj.processEvent(Snapshot.Event.OperationNotPerformed);
            } catch (final NoTransitionException e) {
                s_logger.debug("Failed to change state: " + snapshot.getId() + ": " + e.toString());
                throw new CloudRuntimeException(e.toString());
            }
            return snapshotDataFactory.getSnapshot(snapObj.getId(), store);
        } else {
            s_logger.debug("parent snapshot hasn't been backed up yet");
        }
    }
    // determine full snapshot backup or not
    boolean fullBackup = true;
    SnapshotDataStoreVO parentSnapshotOnBackupStore = snapshotStoreDao.findLatestSnapshotForVolume(snapshot.getVolumeId(), DataStoreRole.Image);
    final SnapshotDataStoreVO parentSnapshotOnPrimaryStore = snapshotStoreDao.findLatestSnapshotForVolume(snapshot.getVolumeId(), DataStoreRole.Primary);
    final HypervisorType hypervisorType = snapshot.getBaseVolume().getHypervisorType();
    if (parentSnapshotOnPrimaryStore != null && parentSnapshotOnBackupStore != null && hypervisorType == HypervisorType.XenServer) {
        // CS does incremental backup
        // only for XenServer
        // In case of volume migration from one pool to other pool, CS should take full snapshot to avoid any issues with delta chain,
        // to check if this is a migrated volume, compare the current pool id of volume and store_id of oldest snapshot on primary for this volume.
        // Why oldest? Because at this point CS has two snapshot on primary entries for same volume, one with old pool_id and other one with
        // current pool id. So, verify and if volume found to be migrated, delete snapshot entry with previous pool store_id.
        final SnapshotDataStoreVO oldestSnapshotOnPrimary = snapshotStoreDao.findOldestSnapshotForVolume(snapshot.getVolumeId(), DataStoreRole.Primary);
        final VolumeVO volume = volumeDao.findById(snapshot.getVolumeId());
        if (oldestSnapshotOnPrimary != null) {
            if (oldestSnapshotOnPrimary.getDataStoreId() == volume.getPoolId()) {
                final int _deltaSnapshotMax = NumbersUtil.parseInt(configDao.getValue("snapshot.delta.max"), SnapshotManager.DELTAMAX);
                final int deltaSnap = _deltaSnapshotMax;
                int i;
                for (i = 1; i < deltaSnap; i++) {
                    final Long prevBackupId = parentSnapshotOnBackupStore.getParentSnapshotId();
                    if (prevBackupId == 0) {
                        break;
                    }
                    parentSnapshotOnBackupStore = snapshotStoreDao.findBySnapshot(prevBackupId, DataStoreRole.Image);
                    if (parentSnapshotOnBackupStore == null) {
                        break;
                    }
                }
                if (i >= deltaSnap) {
                    fullBackup = true;
                } else {
                    fullBackup = false;
                }
            } else {
                // if there is an snapshot entry for previousPool(primary storage) of migrated volume, delete it becasue CS created one more snapshot entry for current pool
                snapshotStoreDao.remove(oldestSnapshotOnPrimary.getId());
            }
        }
    }
    snapshot.addPayload(fullBackup);
    return snapshotSvr.backupSnapshot(snapshot);
}
Also used : SnapshotObjectTO(com.cloud.legacymodel.to.SnapshotObjectTO) SnapshotDataStoreVO(com.cloud.storage.datastore.db.SnapshotDataStoreVO) CreateObjectAnswer(com.cloud.legacymodel.communication.answer.CreateObjectAnswer) HypervisorType(com.cloud.model.enumeration.HypervisorType) SnapshotInfo(com.cloud.engine.subsystem.api.storage.SnapshotInfo) VolumeVO(com.cloud.storage.VolumeVO) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) DataStore(com.cloud.engine.subsystem.api.storage.DataStore) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException)

Example 23 with HypervisorType

use of com.cloud.model.enumeration.HypervisorType in project cosmic by MissionCriticalCloud.

the class VMSnapshotStrategyTest method testCreateVMSnapshot.

@Test
public void testCreateVMSnapshot() throws AgentUnavailableException, OperationTimedoutException {
    final Long hostId = 1L;
    final Long vmId = 1L;
    final Long guestOsId = 1L;
    final HypervisorType hypervisorType = HypervisorType.Any;
    final String hypervisorVersion = "default";
    final String guestOsName = "Other";
    final List<VolumeObjectTO> volumeObjectTOs = new ArrayList<>();
    final VMSnapshotVO vmSnapshot = Mockito.mock(VMSnapshotVO.class);
    final UserVmVO userVmVO = Mockito.mock(UserVmVO.class);
    Mockito.when(userVmVO.getGuestOSId()).thenReturn(guestOsId);
    Mockito.when(vmSnapshot.getVmId()).thenReturn(vmId);
    Mockito.when(vmSnapshotHelper.pickRunningHost(Matchers.anyLong())).thenReturn(hostId);
    Mockito.when(vmSnapshotHelper.getVolumeTOList(Matchers.anyLong())).thenReturn(volumeObjectTOs);
    Mockito.when(userVmDao.findById(Matchers.anyLong())).thenReturn(userVmVO);
    final GuestOSVO guestOSVO = Mockito.mock(GuestOSVO.class);
    Mockito.when(guestOSDao.findById(Matchers.anyLong())).thenReturn(guestOSVO);
    final GuestOSHypervisorVO guestOSHypervisorVO = Mockito.mock(GuestOSHypervisorVO.class);
    Mockito.when(guestOSHypervisorVO.getGuestOsName()).thenReturn(guestOsName);
    Mockito.when(guestOsHypervisorDao.findById(Matchers.anyLong())).thenReturn(guestOSHypervisorVO);
    Mockito.when(guestOsHypervisorDao.findByOsIdAndHypervisor(Matchers.anyLong(), Matchers.anyString(), Matchers.anyString())).thenReturn(guestOSHypervisorVO);
    Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(null);
    final HostVO hostVO = Mockito.mock(HostVO.class);
    Mockito.when(hostDao.findById(Matchers.anyLong())).thenReturn(hostVO);
    Mockito.when(hostVO.getHypervisorType()).thenReturn(hypervisorType);
    Mockito.when(hostVO.getHypervisorVersion()).thenReturn(hypervisorVersion);
    Exception e = null;
    try {
        vmSnapshotStrategy.takeVMSnapshot(vmSnapshot);
    } catch (final CloudRuntimeException e1) {
        e = e1;
    }
    assertNotNull(e);
    final CreateVMSnapshotAnswer answer = Mockito.mock(CreateVMSnapshotAnswer.class);
    Mockito.when(answer.getResult()).thenReturn(true);
    Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(answer);
    Mockito.when(vmSnapshotDao.findById(Matchers.anyLong())).thenReturn(vmSnapshot);
    VMSnapshot snapshot = null;
    snapshot = vmSnapshotStrategy.takeVMSnapshot(vmSnapshot);
    assertNotNull(snapshot);
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) ArrayList(java.util.ArrayList) GuestOSVO(com.cloud.storage.GuestOSVO) VMSnapshot(com.cloud.legacymodel.storage.VMSnapshot) HostVO(com.cloud.host.HostVO) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) IOException(java.io.IOException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) HypervisorType(com.cloud.model.enumeration.HypervisorType) GuestOSHypervisorVO(com.cloud.storage.GuestOSHypervisorVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) CreateVMSnapshotAnswer(com.cloud.legacymodel.communication.answer.CreateVMSnapshotAnswer) Command(com.cloud.legacymodel.communication.command.Command) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) VolumeObjectTO(com.cloud.legacymodel.to.VolumeObjectTO) Test(org.junit.Test)

Example 24 with HypervisorType

use of com.cloud.model.enumeration.HypervisorType in project cosmic by MissionCriticalCloud.

the class VMSnapshotStrategyTest method testRevertSnapshot.

@Test
public void testRevertSnapshot() throws AgentUnavailableException, OperationTimedoutException {
    final Long hostId = 1L;
    final Long vmId = 1L;
    final Long guestOsId = 1L;
    final HypervisorType hypervisorType = HypervisorType.Any;
    final String hypervisorVersion = "default";
    final String guestOsName = "Other";
    final List<VolumeObjectTO> volumeObjectTOs = new ArrayList<>();
    final VMSnapshotVO vmSnapshot = Mockito.mock(VMSnapshotVO.class);
    final UserVmVO userVmVO = Mockito.mock(UserVmVO.class);
    Mockito.when(userVmVO.getGuestOSId()).thenReturn(guestOsId);
    Mockito.when(vmSnapshot.getVmId()).thenReturn(vmId);
    Mockito.when(vmSnapshotHelper.pickRunningHost(Matchers.anyLong())).thenReturn(hostId);
    Mockito.when(vmSnapshotHelper.getVolumeTOList(Matchers.anyLong())).thenReturn(volumeObjectTOs);
    Mockito.when(userVmDao.findById(Matchers.anyLong())).thenReturn(userVmVO);
    final GuestOSVO guestOSVO = Mockito.mock(GuestOSVO.class);
    Mockito.when(guestOSDao.findById(Matchers.anyLong())).thenReturn(guestOSVO);
    final GuestOSHypervisorVO guestOSHypervisorVO = Mockito.mock(GuestOSHypervisorVO.class);
    Mockito.when(guestOSHypervisorVO.getGuestOsName()).thenReturn(guestOsName);
    Mockito.when(guestOsHypervisorDao.findById(Matchers.anyLong())).thenReturn(guestOSHypervisorVO);
    Mockito.when(guestOsHypervisorDao.findByOsIdAndHypervisor(Matchers.anyLong(), Matchers.anyString(), Matchers.anyString())).thenReturn(guestOSHypervisorVO);
    final VMSnapshotTO vmSnapshotTO = Mockito.mock(VMSnapshotTO.class);
    Mockito.when(vmSnapshotHelper.getSnapshotWithParents(Matchers.any(VMSnapshotVO.class))).thenReturn(vmSnapshotTO);
    Mockito.when(vmSnapshotDao.findById(Matchers.anyLong())).thenReturn(vmSnapshot);
    Mockito.when(vmSnapshot.getId()).thenReturn(1L);
    Mockito.when(vmSnapshot.getCreated()).thenReturn(new Date());
    Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(null);
    final HostVO hostVO = Mockito.mock(HostVO.class);
    Mockito.when(hostDao.findById(Matchers.anyLong())).thenReturn(hostVO);
    Mockito.when(hostVO.getHypervisorType()).thenReturn(hypervisorType);
    Mockito.when(hostVO.getHypervisorVersion()).thenReturn(hypervisorVersion);
    Exception e = null;
    try {
        vmSnapshotStrategy.revertVMSnapshot(vmSnapshot);
    } catch (final CloudRuntimeException e1) {
        e = e1;
    }
    assertNotNull(e);
    final RevertToVMSnapshotAnswer answer = Mockito.mock(RevertToVMSnapshotAnswer.class);
    Mockito.when(answer.getResult()).thenReturn(Boolean.TRUE);
    Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(answer);
    final boolean result = vmSnapshotStrategy.revertVMSnapshot(vmSnapshot);
    assertTrue(result);
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) RevertToVMSnapshotAnswer(com.cloud.legacymodel.communication.answer.RevertToVMSnapshotAnswer) ArrayList(java.util.ArrayList) GuestOSVO(com.cloud.storage.GuestOSVO) Date(java.util.Date) HostVO(com.cloud.host.HostVO) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) IOException(java.io.IOException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) HypervisorType(com.cloud.model.enumeration.HypervisorType) GuestOSHypervisorVO(com.cloud.storage.GuestOSHypervisorVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) VMSnapshotTO(com.cloud.legacymodel.to.VMSnapshotTO) Command(com.cloud.legacymodel.communication.command.Command) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) VolumeObjectTO(com.cloud.legacymodel.to.VolumeObjectTO) Test(org.junit.Test)

Example 25 with HypervisorType

use of com.cloud.model.enumeration.HypervisorType in project cosmic by MissionCriticalCloud.

the class QueryManagerImpl method searchForIsosInternal.

private Pair<List<TemplateJoinVO>, Integer> searchForIsosInternal(final ListIsosCmd cmd) {
    final TemplateFilter isoFilter = TemplateFilter.valueOf(cmd.getIsoFilter());
    final Long id = cmd.getId();
    final Map<String, String> tags = cmd.getTags();
    final boolean showRemovedISO = cmd.getShowRemoved();
    final Account caller = CallContext.current().getCallingAccount();
    boolean listAll = false;
    if (isoFilter != null && isoFilter == TemplateFilter.all) {
        if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
            throw new InvalidParameterValueException("Filter " + TemplateFilter.all + " can be specified by admin only");
        }
        listAll = true;
    }
    final List<Long> permittedAccountIds = new ArrayList<>();
    final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, listAll, false);
    final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    final List<Account> permittedAccounts = new ArrayList<>();
    for (final Long accountId : permittedAccountIds) {
        permittedAccounts.add(_accountMgr.getAccount(accountId));
    }
    final HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
    return searchForTemplatesInternal(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true, cmd.isBootable(), cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, true, cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags, showRemovedISO);
}
Also used : Account(com.cloud.legacymodel.user.Account) Ternary(com.cloud.legacymodel.utils.Ternary) ArrayList(java.util.ArrayList) TemplateFilter(com.cloud.legacymodel.storage.VirtualMachineTemplate.TemplateFilter) HypervisorType(com.cloud.model.enumeration.HypervisorType) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException)

Aggregations

HypervisorType (com.cloud.model.enumeration.HypervisorType)40 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)18 ArrayList (java.util.ArrayList)17 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)16 Account (com.cloud.legacymodel.user.Account)12 VMTemplateVO (com.cloud.storage.VMTemplateVO)8 AgentUnavailableException (com.cloud.legacymodel.exceptions.AgentUnavailableException)7 ClusterVO (com.cloud.dc.ClusterVO)6 DataStore (com.cloud.engine.subsystem.api.storage.DataStore)6 DB (com.cloud.utils.db.DB)6 UserVmVO (com.cloud.vm.UserVmVO)6 HostVO (com.cloud.host.HostVO)5 NoTransitionException (com.cloud.legacymodel.exceptions.NoTransitionException)5 OperationTimedoutException (com.cloud.legacymodel.exceptions.OperationTimedoutException)5 ResourceAllocationException (com.cloud.legacymodel.exceptions.ResourceAllocationException)5 NetworkVO (com.cloud.network.dao.NetworkVO)5 StoragePoolVO (com.cloud.storage.datastore.db.StoragePoolVO)5 VMSnapshotVO (com.cloud.vm.snapshot.VMSnapshotVO)5 EndPoint (com.cloud.engine.subsystem.api.storage.EndPoint)4 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)4