Search in sources :

Example 81 with ServiceOffering

use of com.cloud.offering.ServiceOffering in project cloudstack by apache.

the class HypervisorGuruBase method toVirtualMachineTO.

protected VirtualMachineTO toVirtualMachineTO(VirtualMachineProfile vmProfile) {
    ServiceOffering offering = _serviceOfferingDao.findById(vmProfile.getId(), vmProfile.getServiceOfferingId());
    VirtualMachine vm = vmProfile.getVirtualMachine();
    Long clusterId = findClusterOfVm(vm);
    boolean divideMemoryByOverprovisioning = true;
    boolean divideCpuByOverprovisioning = true;
    if (clusterId != null) {
        divideMemoryByOverprovisioning = VmMinMemoryEqualsMemoryDividedByMemOverprovisioningFactor.valueIn(clusterId);
        divideCpuByOverprovisioning = VmMinCpuSpeedEqualsCpuSpeedDividedByCpuOverprovisioningFactor.valueIn(clusterId);
    }
    Long minMemory = (long) (offering.getRamSize() / (divideMemoryByOverprovisioning ? vmProfile.getMemoryOvercommitRatio() : 1));
    int minspeed = (int) (offering.getSpeed() / (divideCpuByOverprovisioning ? vmProfile.getCpuOvercommitRatio() : 1));
    int maxspeed = (offering.getSpeed());
    VirtualMachineTO to = new VirtualMachineTO(vm.getId(), vm.getInstanceName(), vm.getType(), offering.getCpu(), minspeed, maxspeed, minMemory * 1024l * 1024l, offering.getRamSize() * 1024l * 1024l, null, null, vm.isHaEnabled(), vm.limitCpuUse(), vm.getVncPassword());
    to.setBootArgs(vmProfile.getBootArgs());
    Map<VirtualMachineProfile.Param, Object> map = vmProfile.getParameters();
    if (MapUtils.isNotEmpty(map)) {
        if (map.containsKey(VirtualMachineProfile.Param.BootMode)) {
            if (StringUtils.isNotBlank((String) map.get(VirtualMachineProfile.Param.BootMode))) {
                to.setBootMode((String) map.get(VirtualMachineProfile.Param.BootMode));
            }
        }
        if (map.containsKey(VirtualMachineProfile.Param.BootType)) {
            if (StringUtils.isNotBlank((String) map.get(VirtualMachineProfile.Param.BootType))) {
                to.setBootType((String) map.get(VirtualMachineProfile.Param.BootType));
            }
        }
    }
    List<NicProfile> nicProfiles = vmProfile.getNics();
    NicTO[] nics = new NicTO[nicProfiles.size()];
    int i = 0;
    for (NicProfile nicProfile : nicProfiles) {
        if (vm.getType() == VirtualMachine.Type.NetScalerVm) {
            nicProfile.setBroadcastType(BroadcastDomainType.Native);
        }
        NicTO nicTo = toNicTO(nicProfile);
        nics[i++] = nicTo;
    }
    to.setNics(nics);
    to.setDisks(vmProfile.getDisks().toArray(new DiskTO[vmProfile.getDisks().size()]));
    if (vmProfile.getTemplate().getBits() == 32) {
        to.setArch("i686");
    } else {
        to.setArch("x86_64");
    }
    Map<String, String> detailsInVm = _userVmDetailsDao.listDetailsKeyPairs(vm.getId());
    if (detailsInVm != null) {
        to.setDetails(detailsInVm);
        addExtraConfig(detailsInVm, to);
    }
    addServiceOfferingExtraConfiguration(offering, to);
    // Set GPU details
    ServiceOfferingDetailsVO offeringDetail = _serviceOfferingDetailsDao.findDetail(offering.getId(), GPU.Keys.vgpuType.toString());
    if (offeringDetail != null) {
        ServiceOfferingDetailsVO groupName = _serviceOfferingDetailsDao.findDetail(offering.getId(), GPU.Keys.pciDevice.toString());
        to.setGpuDevice(_resourceMgr.getGPUDevice(vm.getHostId(), groupName.getValue(), offeringDetail.getValue()));
    }
    // Workaround to make sure the TO has the UUID we need for Niciri integration
    VMInstanceVO vmInstance = _virtualMachineDao.findById(to.getId());
    to.setEnableDynamicallyScaleVm(vmInstance.isDynamicallyScalable());
    to.setUuid(vmInstance.getUuid());
    to.setVmData(vmProfile.getVmData());
    to.setConfigDriveLabel(vmProfile.getConfigDriveLabel());
    to.setConfigDriveIsoRootFolder(vmProfile.getConfigDriveIsoRootFolder());
    to.setConfigDriveIsoFile(vmProfile.getConfigDriveIsoFile());
    to.setConfigDriveLocation(vmProfile.getConfigDriveLocation());
    to.setState(vm.getState());
    return to;
}
Also used : ServiceOffering(com.cloud.offering.ServiceOffering) ServiceOfferingDetailsVO(com.cloud.service.ServiceOfferingDetailsVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) NicProfile(com.cloud.vm.NicProfile) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) VirtualMachine(com.cloud.vm.VirtualMachine) NicTO(com.cloud.agent.api.to.NicTO) DiskTO(com.cloud.agent.api.to.DiskTO)

Example 82 with ServiceOffering

use of com.cloud.offering.ServiceOffering in project cloudstack by apache.

the class FirstFitPlanner method orderClusters.

@Override
public List<Long> orderClusters(VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid) throws InsufficientServerCapacityException {
    VirtualMachine vm = vmProfile.getVirtualMachine();
    DataCenter dc = dcDao.findById(vm.getDataCenterId());
    // check if datacenter is in avoid set
    if (avoid.shouldAvoid(dc)) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("DataCenter id = '" + dc.getId() + "' provided is in avoid set, DeploymentPlanner cannot allocate the VM, returning.");
        }
        return null;
    }
    List<Long> clusterList = new ArrayList<Long>();
    if (plan.getClusterId() != null) {
        Long clusterIdSpecified = plan.getClusterId();
        s_logger.debug("Searching resources only under specified Cluster: " + clusterIdSpecified);
        ClusterVO cluster = clusterDao.findById(plan.getClusterId());
        if (cluster != null) {
            if (avoid.shouldAvoid(cluster)) {
                s_logger.debug("The specified cluster is in avoid set, returning.");
            } else {
                clusterList.add(clusterIdSpecified);
                removeClustersCrossingThreshold(clusterList, avoid, vmProfile, plan);
            }
        } else {
            s_logger.debug("The specified cluster cannot be found, returning.");
            avoid.addCluster(plan.getClusterId());
            return null;
        }
    } else if (plan.getPodId() != null) {
        // consider clusters under this pod only
        Long podIdSpecified = plan.getPodId();
        s_logger.debug("Searching resources only under specified Pod: " + podIdSpecified);
        HostPodVO pod = podDao.findById(podIdSpecified);
        if (pod != null) {
            if (avoid.shouldAvoid(pod)) {
                s_logger.debug("The specified pod is in avoid set, returning.");
            } else {
                clusterList = scanClustersForDestinationInZoneOrPod(podIdSpecified, false, vmProfile, plan, avoid);
                if (clusterList == null) {
                    avoid.addPod(plan.getPodId());
                }
            }
        } else {
            s_logger.debug("The specified Pod cannot be found, returning.");
            avoid.addPod(plan.getPodId());
            return null;
        }
    } else {
        s_logger.debug("Searching all possible resources under this Zone: " + plan.getDataCenterId());
        boolean applyAllocationAtPods = Boolean.parseBoolean(configDao.getValue(Config.ApplyAllocationAlgorithmToPods.key()));
        if (applyAllocationAtPods) {
            // start scan at all pods under this zone.
            clusterList = scanPodsForDestination(vmProfile, plan, avoid);
        } else {
            // start scan at clusters under this zone.
            clusterList = scanClustersForDestinationInZoneOrPod(plan.getDataCenterId(), true, vmProfile, plan, avoid);
        }
    }
    if (clusterList != null && !clusterList.isEmpty()) {
        ServiceOffering offering = vmProfile.getServiceOffering();
        boolean nonUefiVMDeploy = false;
        if (vmProfile.getParameters().containsKey(VirtualMachineProfile.Param.BootType)) {
            if (vmProfile.getParameters().get(VirtualMachineProfile.Param.BootType).toString().equalsIgnoreCase("BIOS")) {
                nonUefiVMDeploy = true;
            }
        }
        // In case of non-GPU VMs, protect GPU enabled Hosts and prefer VM deployment on non-GPU Hosts.
        if (((serviceOfferingDetailsDao.findDetail(offering.getId(), GPU.Keys.vgpuType.toString()) == null) && !(hostGpuGroupsDao.listHostIds().isEmpty())) || nonUefiVMDeploy) {
            int requiredCpu = offering.getCpu() * offering.getSpeed();
            long requiredRam = offering.getRamSize() * 1024L * 1024L;
            reorderClustersBasedOnImplicitTags(clusterList, requiredCpu, requiredRam);
        }
    }
    return clusterList;
}
Also used : DataCenter(com.cloud.dc.DataCenter) ClusterVO(com.cloud.dc.ClusterVO) ServiceOffering(com.cloud.offering.ServiceOffering) ArrayList(java.util.ArrayList) HostPodVO(com.cloud.dc.HostPodVO) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 83 with ServiceOffering

use of com.cloud.offering.ServiceOffering in project cloudstack by apache.

the class UserVmManagerImpl method updateDisplayVmFlag.

protected void updateDisplayVmFlag(Boolean isDisplayVm, Long id, UserVmVO vmInstance) {
    vmInstance.setDisplayVm(isDisplayVm);
    // Resource limit changes
    ServiceOffering offering = _serviceOfferingDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId());
    if (isDisplayVm) {
        resourceCountIncrement(vmInstance.getAccountId(), true, Long.valueOf(offering.getCpu()), Long.valueOf(offering.getRamSize()));
    } else {
        resourceCountDecrement(vmInstance.getAccountId(), true, Long.valueOf(offering.getCpu()), Long.valueOf(offering.getRamSize()));
    }
    // Usage
    saveUsageEvent(vmInstance);
    // take care of the root volume as well.
    List<VolumeVO> rootVols = _volsDao.findByInstanceAndType(id, Volume.Type.ROOT);
    if (!rootVols.isEmpty()) {
        _volumeService.updateDisplay(rootVols.get(0), isDisplayVm);
    }
    // take care of the data volumes as well.
    List<VolumeVO> dataVols = _volsDao.findByInstanceAndType(id, Volume.Type.DATADISK);
    for (Volume dataVol : dataVols) {
        _volumeService.updateDisplay(dataVol, isDisplayVm);
    }
}
Also used : VolumeVO(com.cloud.storage.VolumeVO) ServiceOffering(com.cloud.offering.ServiceOffering) Volume(com.cloud.storage.Volume)

Example 84 with ServiceOffering

use of com.cloud.offering.ServiceOffering in project cloudstack by apache.

the class UserVmManagerImpl method createVirtualMachine.

@Override
public UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException {
    // Verify that all objects exist before passing them to the service
    Account owner = _accountService.getActiveAccountById(cmd.getEntityOwnerId());
    verifyDetails(cmd.getDetails());
    Long zoneId = cmd.getZoneId();
    DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
    if (zone == null) {
        throw new InvalidParameterValueException("Unable to find zone by id=" + zoneId);
    }
    Long serviceOfferingId = cmd.getServiceOfferingId();
    Long overrideDiskOfferingId = cmd.getOverrideDiskOfferingId();
    ServiceOffering serviceOffering = _entityMgr.findById(ServiceOffering.class, serviceOfferingId);
    if (serviceOffering == null) {
        throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId);
    }
    if (serviceOffering.getDiskOfferingStrictness() && overrideDiskOfferingId != null) {
        throw new InvalidParameterValueException(String.format("Cannot override disk offering id %d since provided service offering is strictly mapped to its disk offering", overrideDiskOfferingId));
    }
    if (!serviceOffering.isDynamic()) {
        for (String detail : cmd.getDetails().keySet()) {
            if (detail.equalsIgnoreCase(VmDetailConstants.CPU_NUMBER) || detail.equalsIgnoreCase(VmDetailConstants.CPU_SPEED) || detail.equalsIgnoreCase(VmDetailConstants.MEMORY)) {
                throw new InvalidParameterValueException("cpuNumber or cpuSpeed or memory should not be specified for static service offering");
            }
        }
    }
    Long templateId = cmd.getTemplateId();
    boolean dynamicScalingEnabled = cmd.isDynamicScalingEnabled();
    VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, templateId);
    // Make sure a valid template ID was specified
    if (template == null) {
        throw new InvalidParameterValueException("Unable to use template " + templateId);
    }
    ServiceOfferingJoinVO svcOffering = serviceOfferingJoinDao.findById(serviceOfferingId);
    if (template.isDeployAsIs()) {
        if (svcOffering != null && svcOffering.getRootDiskSize() != null && svcOffering.getRootDiskSize() > 0) {
            throw new InvalidParameterValueException("Failed to deploy Virtual Machine as a service offering with root disk size specified cannot be used with a deploy as-is template");
        }
        if (cmd.getDetails().get("rootdisksize") != null) {
            throw new InvalidParameterValueException("Overriding root disk size isn't supported for VMs deployed from deploy as-is templates");
        }
        // Bootmode and boottype are not supported on VMWare dpeloy-as-is templates (since 4.15)
        if ((cmd.getBootMode() != null || cmd.getBootType() != null)) {
            throw new InvalidParameterValueException("Boot type and boot mode are not supported on VMware, as we honour what is defined in the template.");
        }
    }
    Long diskOfferingId = cmd.getDiskOfferingId();
    DiskOffering diskOffering = null;
    if (diskOfferingId != null) {
        diskOffering = _entityMgr.findById(DiskOffering.class, diskOfferingId);
        if (diskOffering == null) {
            throw new InvalidParameterValueException("Unable to find disk offering " + diskOfferingId);
        }
        if (diskOffering.isComputeOnly()) {
            throw new InvalidParameterValueException(String.format("The disk offering id %d provided is directly mapped to a service offering, please provide an individual disk offering", diskOfferingId));
        }
    }
    if (!zone.isLocalStorageEnabled()) {
        DiskOffering diskOfferingMappedInServiceOffering = _entityMgr.findById(DiskOffering.class, serviceOffering.getDiskOfferingId());
        if (diskOfferingMappedInServiceOffering.isUseLocalStorage()) {
            throw new InvalidParameterValueException("Zone is not configured to use local storage but disk offering " + diskOfferingMappedInServiceOffering.getName() + " mapped in service offering uses it");
        }
        if (diskOffering != null && diskOffering.isUseLocalStorage()) {
            throw new InvalidParameterValueException("Zone is not configured to use local storage but disk offering " + diskOffering.getName() + " uses it");
        }
    }
    List<Long> networkIds = cmd.getNetworkIds();
    LinkedHashMap<Integer, Long> userVmNetworkMap = getVmOvfNetworkMapping(zone, owner, template, cmd.getVmNetworkMap());
    if (MapUtils.isNotEmpty(userVmNetworkMap)) {
        networkIds = new ArrayList<>(userVmNetworkMap.values());
    }
    Account caller = CallContext.current().getCallingAccount();
    Long callerId = caller.getId();
    boolean isRootAdmin = _accountService.isRootAdmin(callerId);
    Long hostId = cmd.getHostId();
    getDestinationHost(hostId, isRootAdmin, true);
    String ipAddress = cmd.getIpAddress();
    String ip6Address = cmd.getIp6Address();
    String macAddress = cmd.getMacAddress();
    String name = cmd.getName();
    String displayName = cmd.getDisplayName();
    UserVm vm = null;
    IpAddresses addrs = new IpAddresses(ipAddress, ip6Address, macAddress);
    Long size = cmd.getSize();
    String group = cmd.getGroup();
    String userData = cmd.getUserData();
    String sshKeyPairName = cmd.getSSHKeyPairName();
    Boolean displayVm = cmd.isDisplayVm();
    String keyboard = cmd.getKeyboard();
    Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap = cmd.getDataDiskTemplateToDiskOfferingMap();
    Map<String, String> userVmOVFProperties = cmd.getVmProperties();
    if (zone.getNetworkType() == NetworkType.Basic) {
        if (networkIds != null) {
            throw new InvalidParameterValueException("Can't specify network Ids in Basic zone");
        } else {
            vm = createBasicSecurityGroupVirtualMachine(zone, serviceOffering, template, getSecurityGroupIdList(cmd), owner, name, displayName, diskOfferingId, size, group, cmd.getHypervisor(), cmd.getHttpMethod(), userData, sshKeyPairName, cmd.getIpToNetworkMap(), addrs, displayVm, keyboard, cmd.getAffinityGroupIdList(), cmd.getDetails(), cmd.getCustomId(), cmd.getDhcpOptionsMap(), dataDiskTemplateToDiskOfferingMap, userVmOVFProperties, dynamicScalingEnabled, overrideDiskOfferingId);
        }
    } else {
        if (zone.isSecurityGroupEnabled()) {
            vm = createAdvancedSecurityGroupVirtualMachine(zone, serviceOffering, template, networkIds, getSecurityGroupIdList(cmd), owner, name, displayName, diskOfferingId, size, group, cmd.getHypervisor(), cmd.getHttpMethod(), userData, sshKeyPairName, cmd.getIpToNetworkMap(), addrs, displayVm, keyboard, cmd.getAffinityGroupIdList(), cmd.getDetails(), cmd.getCustomId(), cmd.getDhcpOptionsMap(), dataDiskTemplateToDiskOfferingMap, userVmOVFProperties, dynamicScalingEnabled, overrideDiskOfferingId);
        } else {
            if (cmd.getSecurityGroupIdList() != null && !cmd.getSecurityGroupIdList().isEmpty()) {
                throw new InvalidParameterValueException("Can't create vm with security groups; security group feature is not enabled per zone");
            }
            vm = createAdvancedVirtualMachine(zone, serviceOffering, template, networkIds, owner, name, displayName, diskOfferingId, size, group, cmd.getHypervisor(), cmd.getHttpMethod(), userData, sshKeyPairName, cmd.getIpToNetworkMap(), addrs, displayVm, keyboard, cmd.getAffinityGroupIdList(), cmd.getDetails(), cmd.getCustomId(), cmd.getDhcpOptionsMap(), dataDiskTemplateToDiskOfferingMap, userVmOVFProperties, dynamicScalingEnabled, null, overrideDiskOfferingId);
        }
    }
    // check if this templateId has a child ISO
    List<VMTemplateVO> child_templates = _templateDao.listByParentTemplatetId(templateId);
    for (VMTemplateVO tmpl : child_templates) {
        if (tmpl.getFormat() == Storage.ImageFormat.ISO) {
            s_logger.info("MDOV trying to attach disk to the VM " + tmpl.getId() + " vmid=" + vm.getId());
            _tmplService.attachIso(tmpl.getId(), vm.getId(), true);
        }
    }
    // Add extraConfig to user_vm_details table
    String extraConfig = cmd.getExtraConfig();
    if (StringUtils.isNotBlank(extraConfig)) {
        if (EnableAdditionalVmConfig.valueIn(callerId)) {
            s_logger.info("Adding extra configuration to user vm: " + vm.getUuid());
            addExtraConfig(vm, extraConfig);
        } else {
            throw new InvalidParameterValueException("attempted setting extraconfig but enable.additional.vm.configuration is disabled");
        }
    }
    if (cmd.getCopyImageTags()) {
        VMTemplateVO templateOrIso = _templateDao.findById(templateId);
        if (templateOrIso != null) {
            final ResourceTag.ResourceObjectType templateType = (templateOrIso.getFormat() == ImageFormat.ISO) ? ResourceTag.ResourceObjectType.ISO : ResourceTag.ResourceObjectType.Template;
            final List<? extends ResourceTag> resourceTags = resourceTagDao.listBy(templateId, templateType);
            for (ResourceTag resourceTag : resourceTags) {
                final ResourceTagVO copyTag = new ResourceTagVO(resourceTag.getKey(), resourceTag.getValue(), resourceTag.getAccountId(), resourceTag.getDomainId(), vm.getId(), ResourceTag.ResourceObjectType.UserVm, resourceTag.getCustomer(), vm.getUuid());
                resourceTagDao.persist(copyTag);
            }
        }
    }
    return vm;
}
Also used : Account(com.cloud.user.Account) DiskOffering(com.cloud.offering.DiskOffering) VMTemplateVO(com.cloud.storage.VMTemplateVO) UserVm(com.cloud.uservm.UserVm) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceTagVO(com.cloud.tags.ResourceTagVO) VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) ServiceOfferingJoinVO(com.cloud.api.query.vo.ServiceOfferingJoinVO) ServiceOffering(com.cloud.offering.ServiceOffering) IpAddresses(com.cloud.network.Network.IpAddresses) DataCenter(com.cloud.dc.DataCenter) ResourceTag(com.cloud.server.ResourceTag)

Example 85 with ServiceOffering

use of com.cloud.offering.ServiceOffering in project cloudstack by apache.

the class UserVmManagerImplTest method updateVirtualMachineTestCleanUpTrue.

@Test
public void updateVirtualMachineTestCleanUpTrue() throws ResourceUnavailableException, InsufficientCapacityException {
    configureDoNothingForMethodsThatWeDoNotWantToTest();
    ServiceOffering offering = getSvcoffering(512);
    Mockito.when(_serviceOfferingDao.findById(Mockito.anyLong(), Mockito.anyLong())).thenReturn((ServiceOfferingVO) offering);
    Mockito.when(updateVmCommand.isCleanupDetails()).thenReturn(true);
    Mockito.lenient().doNothing().when(userVmManagerImpl).updateDisplayVmFlag(false, vmId, userVmVoMock);
    Mockito.doNothing().when(userVmDetailVO).removeDetails(vmId);
    userVmManagerImpl.updateVirtualMachine(updateVmCommand);
    verifyMethodsThatAreAlwaysExecuted();
    Mockito.verify(userVmDetailVO).removeDetails(vmId);
    Mockito.verify(userVmManagerImpl, Mockito.times(0)).updateDisplayVmFlag(false, vmId, userVmVoMock);
}
Also used : ServiceOffering(com.cloud.offering.ServiceOffering) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

ServiceOffering (com.cloud.offering.ServiceOffering)103 ArrayList (java.util.ArrayList)34 Account (com.cloud.user.Account)30 DataCenter (com.cloud.dc.DataCenter)23 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)20 HashMap (java.util.HashMap)18 VirtualMachine (com.cloud.vm.VirtualMachine)17 VMTemplateVO (com.cloud.storage.VMTemplateVO)14 UserVm (com.cloud.uservm.UserVm)14 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)14 Map (java.util.Map)14 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)13 ServerApiException (com.cloud.api.ServerApiException)12 HostVO (com.cloud.host.HostVO)12 DiskOffering (com.cloud.offering.DiskOffering)11 ServiceOfferingVO (com.cloud.service.ServiceOfferingVO)11 Host (com.cloud.host.Host)10 Network (com.cloud.network.Network)10 List (java.util.List)10 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)9