Search in sources :

Example 1 with ServiceOfferingDetailsVO

use of com.cloud.service.ServiceOfferingDetailsVO in project cloudstack by apache.

the class ServiceOfferingDaoImpl method saveDetails.

@Override
public void saveDetails(ServiceOfferingVO serviceOffering) {
    Map<String, String> details = serviceOffering.getDetails();
    if (details == null) {
        return;
    }
    List<ServiceOfferingDetailsVO> resourceDetails = new ArrayList<ServiceOfferingDetailsVO>();
    for (String key : details.keySet()) {
        resourceDetails.add(new ServiceOfferingDetailsVO(serviceOffering.getId(), key, details.get(key), true));
    }
    detailsDao.saveDetails(resourceDetails);
}
Also used : ArrayList(java.util.ArrayList) ServiceOfferingDetailsVO(com.cloud.service.ServiceOfferingDetailsVO)

Example 2 with ServiceOfferingDetailsVO

use of com.cloud.service.ServiceOfferingDetailsVO in project cloudstack by apache.

the class FirstFitAllocator method allocateTo.

protected List<Host> allocateTo(DeploymentPlan plan, ServiceOffering offering, VMTemplateVO template, ExcludeList avoid, List<? extends Host> hosts, int returnUpTo, boolean considerReservedCapacity, Account account) {
    if (_allocationAlgorithm.equals("random") || _allocationAlgorithm.equals("userconcentratedpod_random")) {
        // Shuffle this so that we don't check the hosts in the same order.
        Collections.shuffle(hosts);
    } else if (_allocationAlgorithm.equals("userdispersing")) {
        hosts = reorderHostsByNumberOfVms(plan, hosts, account);
    } else if (_allocationAlgorithm.equals("firstfitleastconsumed")) {
        hosts = reorderHostsByCapacity(plan, hosts);
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("FirstFitAllocator has " + hosts.size() + " hosts to check for allocation: " + hosts);
    }
    // We will try to reorder the host lists such that we give priority to hosts that have
    // the minimums to support a VM's requirements
    hosts = prioritizeHosts(template, offering, hosts);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Found " + hosts.size() + " hosts for allocation after prioritization: " + hosts);
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Looking for speed=" + (offering.getCpu() * offering.getSpeed()) + "Mhz, Ram=" + offering.getRamSize());
    }
    long serviceOfferingId = offering.getId();
    List<Host> suitableHosts = new ArrayList<Host>();
    ServiceOfferingDetailsVO offeringDetails = null;
    for (Host host : hosts) {
        if (suitableHosts.size() == returnUpTo) {
            break;
        }
        if (avoid.shouldAvoid(host)) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Host name: " + host.getName() + ", hostId: " + host.getId() + " is in avoid set, skipping this and trying other available hosts");
            }
            continue;
        }
        //find number of guest VMs occupying capacity on this host.
        if (_capacityMgr.checkIfHostReachMaxGuestLimit(host)) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Host name: " + host.getName() + ", hostId: " + host.getId() + " already has max Running VMs(count includes system VMs), skipping this and trying other available hosts");
            }
            avoid.addHost(host.getId());
            continue;
        }
        // Check if GPU device is required by offering and host has the availability
        if ((offeringDetails = _serviceOfferingDetailsDao.findDetail(serviceOfferingId, GPU.Keys.vgpuType.toString())) != null) {
            ServiceOfferingDetailsVO groupName = _serviceOfferingDetailsDao.findDetail(serviceOfferingId, GPU.Keys.pciDevice.toString());
            if (!_resourceMgr.isGPUDeviceAvailable(host.getId(), groupName.getValue(), offeringDetails.getValue())) {
                s_logger.info("Host name: " + host.getName() + ", hostId: " + host.getId() + " does not have required GPU devices available");
                avoid.addHost(host.getId());
                continue;
            }
        }
        int cpu_requested = offering.getCpu() * offering.getSpeed();
        long ram_requested = offering.getRamSize() * 1024L * 1024L;
        Cluster cluster = _clusterDao.findById(host.getClusterId());
        ClusterDetailsVO clusterDetailsCpuOvercommit = _clusterDetailsDao.findDetail(cluster.getId(), "cpuOvercommitRatio");
        ClusterDetailsVO clusterDetailsRamOvercommmt = _clusterDetailsDao.findDetail(cluster.getId(), "memoryOvercommitRatio");
        Float cpuOvercommitRatio = Float.parseFloat(clusterDetailsCpuOvercommit.getValue());
        Float memoryOvercommitRatio = Float.parseFloat(clusterDetailsRamOvercommmt.getValue());
        boolean hostHasCpuCapability = _capacityMgr.checkIfHostHasCpuCapability(host.getId(), offering.getCpu(), offering.getSpeed());
        boolean hostHasCapacity = _capacityMgr.checkIfHostHasCapacity(host.getId(), cpu_requested, ram_requested, false, cpuOvercommitRatio, memoryOvercommitRatio, considerReservedCapacity);
        if (hostHasCpuCapability && hostHasCapacity) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Found a suitable host, adding to list: " + host.getId());
            }
            suitableHosts.add(host);
        } else {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Not using host " + host.getId() + "; host has cpu capability? " + hostHasCpuCapability + ", host has capacity?" + hostHasCapacity);
            }
            avoid.addHost(host.getId());
        }
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Host Allocator returning " + suitableHosts.size() + " suitable hosts");
    }
    return suitableHosts;
}
Also used : ArrayList(java.util.ArrayList) ServiceOfferingDetailsVO(com.cloud.service.ServiceOfferingDetailsVO) Cluster(com.cloud.org.Cluster) Host(com.cloud.host.Host) ClusterDetailsVO(com.cloud.dc.ClusterDetailsVO)

Example 3 with ServiceOfferingDetailsVO

use of com.cloud.service.ServiceOfferingDetailsVO in project cloudstack by apache.

the class ConfigurationManagerImpl method createServiceOffering.

protected ServiceOfferingVO createServiceOffering(final long userId, final boolean isSystem, final VirtualMachine.Type vmType, final String name, final Integer cpu, final Integer ramSize, final Integer speed, final String displayText, final String provisioningType, final boolean localStorageRequired, final boolean offerHA, final boolean limitResourceUse, final boolean volatileVm, String tags, final Long domainId, final String hostTag, final Integer networkRate, final String deploymentPlanner, final Map<String, String> details, final Boolean isCustomizedIops, Long minIops, Long maxIops, Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate, final Integer hypervisorSnapshotReserve) {
    // Check if user exists in the system
    final User user = _userDao.findById(userId);
    if (user == null || user.getRemoved() != null) {
        throw new InvalidParameterValueException("Unable to find active user by id " + userId);
    }
    final Account account = _accountDao.findById(user.getAccountId());
    if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
        if (domainId == null) {
            throw new InvalidParameterValueException("Unable to create public service offering by id " + userId + " because it is domain-admin");
        }
        if (tags != null || hostTag != null) {
            throw new InvalidParameterValueException("Unable to create service offering with storage tags or host tags by id " + userId + " because it is domain-admin");
        }
        if (!_domainDao.isChildDomain(account.getDomainId(), domainId)) {
            throw new InvalidParameterValueException("Unable to create service offering by another domain admin with id " + userId);
        }
    } else if (account.getType() != Account.ACCOUNT_TYPE_ADMIN) {
        throw new InvalidParameterValueException("Unable to create service offering by id " + userId + " because it is not root-admin or domain-admin");
    }
    final ProvisioningType typedProvisioningType = ProvisioningType.getProvisioningType(provisioningType);
    tags = StringUtils.cleanupTags(tags);
    ServiceOfferingVO offering = new ServiceOfferingVO(name, cpu, ramSize, speed, networkRate, null, offerHA, limitResourceUse, volatileVm, displayText, typedProvisioningType, localStorageRequired, false, tags, isSystem, vmType, domainId, hostTag, deploymentPlanner);
    if (isCustomizedIops != null) {
        bytesReadRate = null;
        bytesWriteRate = null;
        iopsReadRate = null;
        iopsWriteRate = null;
        if (isCustomizedIops) {
            minIops = null;
            maxIops = null;
        } else {
            if (minIops == null && maxIops == null) {
                minIops = 0L;
                maxIops = 0L;
            } else {
                if (minIops == null || minIops <= 0) {
                    throw new InvalidParameterValueException("The min IOPS must be greater than 0.");
                }
                if (maxIops == null) {
                    maxIops = 0L;
                }
                if (minIops > maxIops) {
                    throw new InvalidParameterValueException("The min IOPS must be less than or equal to the max IOPS.");
                }
            }
        }
    } else {
        minIops = null;
        maxIops = null;
    }
    offering.setCustomizedIops(isCustomizedIops);
    offering.setMinIops(minIops);
    offering.setMaxIops(maxIops);
    if (bytesReadRate != null && bytesReadRate > 0) {
        offering.setBytesReadRate(bytesReadRate);
    }
    if (bytesWriteRate != null && bytesWriteRate > 0) {
        offering.setBytesWriteRate(bytesWriteRate);
    }
    if (iopsReadRate != null && iopsReadRate > 0) {
        offering.setIopsReadRate(iopsReadRate);
    }
    if (iopsWriteRate != null && iopsWriteRate > 0) {
        offering.setIopsWriteRate(iopsWriteRate);
    }
    if (hypervisorSnapshotReserve != null && hypervisorSnapshotReserve < 0) {
        throw new InvalidParameterValueException("If provided, Hypervisor Snapshot Reserve must be greater than or equal to 0.");
    }
    offering.setHypervisorSnapshotReserve(hypervisorSnapshotReserve);
    List<ServiceOfferingDetailsVO> detailsVO = null;
    if (details != null) {
        // To have correct input, either both gpu card name and VGPU type should be passed or nothing should be passed.
        // Use XOR condition to verify that.
        final boolean entry1 = details.containsKey(GPU.Keys.pciDevice.toString());
        final boolean entry2 = details.containsKey(GPU.Keys.vgpuType.toString());
        if ((entry1 || entry2) && !(entry1 && entry2)) {
            throw new InvalidParameterValueException("Please specify the pciDevice and vgpuType correctly.");
        }
        detailsVO = new ArrayList<ServiceOfferingDetailsVO>();
        for (final Entry<String, String> detailEntry : details.entrySet()) {
            if (detailEntry.getKey().equals(GPU.Keys.pciDevice.toString())) {
                if (detailEntry.getValue() == null) {
                    throw new InvalidParameterValueException("Please specify a GPU Card.");
                }
            }
            if (detailEntry.getKey().equals(GPU.Keys.vgpuType.toString())) {
                if (detailEntry.getValue() == null) {
                    throw new InvalidParameterValueException("vGPUType value cannot be null");
                }
            }
            detailsVO.add(new ServiceOfferingDetailsVO(offering.getId(), detailEntry.getKey(), detailEntry.getValue(), true));
        }
    }
    if ((offering = _serviceOfferingDao.persist(offering)) != null) {
        if (detailsVO != null && !detailsVO.isEmpty()) {
            for (int index = 0; index < detailsVO.size(); index++) {
                detailsVO.get(index).setResourceId(offering.getId());
            }
            _serviceOfferingDetailsDao.saveDetails(detailsVO);
        }
        CallContext.current().setEventDetails("Service offering id=" + offering.getId());
        return offering;
    } else {
        return null;
    }
}
Also used : Account(com.cloud.user.Account) ProvisioningType(com.cloud.storage.Storage.ProvisioningType) User(com.cloud.user.User) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ServiceOfferingDetailsVO(com.cloud.service.ServiceOfferingDetailsVO) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO)

Example 4 with ServiceOfferingDetailsVO

use of com.cloud.service.ServiceOfferingDetailsVO in project cloudstack by apache.

the class UserVmJoinDaoImpl method newUserVmResponse.

@Override
public UserVmResponse newUserVmResponse(ResponseView view, String objectName, UserVmJoinVO userVm, EnumSet<VMDetails> details, Account caller) {
    UserVmResponse userVmResponse = new UserVmResponse();
    if (userVm.getHypervisorType() != null) {
        userVmResponse.setHypervisor(userVm.getHypervisorType().toString());
    }
    userVmResponse.setId(userVm.getUuid());
    userVmResponse.setName(userVm.getName());
    if (userVm.getDisplayName() != null) {
        userVmResponse.setDisplayName(userVm.getDisplayName());
    } else {
        userVmResponse.setDisplayName(userVm.getName());
    }
    if (userVm.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) {
        userVmResponse.setProjectId(userVm.getProjectUuid());
        userVmResponse.setProjectName(userVm.getProjectName());
    } else {
        userVmResponse.setAccountName(userVm.getAccountName());
    }
    User user = _userDao.getUser(userVm.getUserId());
    if (user != null) {
        userVmResponse.setUserId(user.getUuid());
        userVmResponse.setUserName(user.getUsername());
    }
    userVmResponse.setDomainId(userVm.getDomainUuid());
    userVmResponse.setDomainName(userVm.getDomainName());
    userVmResponse.setCreated(userVm.getCreated());
    userVmResponse.setDisplayVm(userVm.isDisplayVm());
    if (userVm.getState() != null) {
        userVmResponse.setState(userVm.getState().toString());
    }
    userVmResponse.setHaEnable(userVm.isHaEnabled());
    if (details.contains(VMDetails.all) || details.contains(VMDetails.group)) {
        userVmResponse.setGroupId(userVm.getInstanceGroupUuid());
        userVmResponse.setGroup(userVm.getInstanceGroupName());
    }
    userVmResponse.setZoneId(userVm.getDataCenterUuid());
    userVmResponse.setZoneName(userVm.getDataCenterName());
    if (view == ResponseView.Full) {
        userVmResponse.setInstanceName(userVm.getInstanceName());
        userVmResponse.setHostId(userVm.getHostUuid());
        userVmResponse.setHostName(userVm.getHostName());
    }
    if (details.contains(VMDetails.all) || details.contains(VMDetails.tmpl)) {
        userVmResponse.setTemplateId(userVm.getTemplateUuid());
        userVmResponse.setTemplateName(userVm.getTemplateName());
        userVmResponse.setTemplateDisplayText(userVm.getTemplateDisplayText());
        userVmResponse.setPasswordEnabled(userVm.isPasswordEnabled());
    }
    if (details.contains(VMDetails.all) || details.contains(VMDetails.iso)) {
        userVmResponse.setIsoId(userVm.getIsoUuid());
        userVmResponse.setIsoName(userVm.getIsoName());
        userVmResponse.setIsoDisplayText(userVm.getIsoDisplayText());
    }
    if (details.contains(VMDetails.all) || details.contains(VMDetails.servoff)) {
        userVmResponse.setServiceOfferingId(userVm.getServiceOfferingUuid());
        userVmResponse.setServiceOfferingName(userVm.getServiceOfferingName());
    }
    if (details.contains(VMDetails.all) || details.contains(VMDetails.diskoff)) {
        userVmResponse.setDiskOfferingId(userVm.getDiskOfferingUuid());
        userVmResponse.setDiskOfferingName(userVm.getDiskOfferingName());
    }
    if (details.contains(VMDetails.all) || details.contains(VMDetails.servoff) || details.contains(VMDetails.stats)) {
        userVmResponse.setCpuNumber(userVm.getCpu());
        userVmResponse.setCpuSpeed(userVm.getSpeed());
        userVmResponse.setMemory(userVm.getRamSize());
        ServiceOfferingDetailsVO serviceOfferingDetail = ApiDBUtils.findServiceOfferingDetail(userVm.getServiceOfferingId(), GPU.Keys.vgpuType.toString());
        if (serviceOfferingDetail != null) {
            userVmResponse.setVgpu(serviceOfferingDetail.getValue());
        }
    }
    userVmResponse.setGuestOsId(userVm.getGuestOsUuid());
    if (details.contains(VMDetails.all) || details.contains(VMDetails.volume)) {
        userVmResponse.setRootDeviceId(userVm.getVolumeDeviceId());
        if (userVm.getVolumeType() != null) {
            userVmResponse.setRootDeviceType(userVm.getVolumeType().toString());
        }
    }
    userVmResponse.setPassword(userVm.getPassword());
    if (userVm.getJobId() != null) {
        userVmResponse.setJobId(userVm.getJobUuid());
        userVmResponse.setJobStatus(userVm.getJobStatus());
    }
    //userVmResponse.setForVirtualNetwork(userVm.getForVirtualNetwork());
    userVmResponse.setPublicIpId(userVm.getPublicIpUuid());
    userVmResponse.setPublicIp(userVm.getPublicIpAddress());
    userVmResponse.setKeyPairName(userVm.getKeypairName());
    userVmResponse.setOsTypeId(userVm.getGuestOsId());
    if (details.contains(VMDetails.all) || details.contains(VMDetails.stats)) {
        // stats calculation
        VmStats vmStats = ApiDBUtils.getVmStatistics(userVm.getId());
        if (vmStats != null) {
            userVmResponse.setCpuUsed(new DecimalFormat("#.##").format(vmStats.getCPUUtilization()) + "%");
            userVmResponse.setNetworkKbsRead((long) vmStats.getNetworkReadKBs());
            userVmResponse.setNetworkKbsWrite((long) vmStats.getNetworkWriteKBs());
            userVmResponse.setDiskKbsRead((long) vmStats.getDiskReadKBs());
            userVmResponse.setDiskKbsWrite((long) vmStats.getDiskWriteKBs());
            userVmResponse.setDiskIORead((long) vmStats.getDiskReadIOs());
            userVmResponse.setDiskIOWrite((long) vmStats.getDiskWriteIOs());
            userVmResponse.setMemoryKBs((long) vmStats.getMemoryKBs());
            userVmResponse.setMemoryIntFreeKBs((long) vmStats.getIntFreeMemoryKBs());
            userVmResponse.setMemoryTargetKBs((long) vmStats.getTargetMemoryKBs());
        }
    }
    if (details.contains(VMDetails.all) || details.contains(VMDetails.secgrp)) {
        Long securityGroupId = userVm.getSecurityGroupId();
        if (securityGroupId != null && securityGroupId.longValue() != 0) {
            SecurityGroupResponse resp = new SecurityGroupResponse();
            resp.setId(userVm.getSecurityGroupUuid());
            resp.setName(userVm.getSecurityGroupName());
            resp.setDescription(userVm.getSecurityGroupDescription());
            resp.setObjectName("securitygroup");
            if (userVm.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) {
                resp.setProjectId(userVm.getProjectUuid());
                resp.setProjectName(userVm.getProjectName());
            } else {
                resp.setAccountName(userVm.getAccountName());
            }
            userVmResponse.addSecurityGroup(resp);
        }
    }
    if (details.contains(VMDetails.all) || details.contains(VMDetails.nics)) {
        long nic_id = userVm.getNicId();
        if (nic_id > 0) {
            NicResponse nicResponse = new NicResponse();
            nicResponse.setId(userVm.getNicUuid());
            nicResponse.setIpaddress(userVm.getIpAddress());
            nicResponse.setGateway(userVm.getGateway());
            nicResponse.setNetmask(userVm.getNetmask());
            nicResponse.setNetworkid(userVm.getNetworkUuid());
            nicResponse.setNetworkName(userVm.getNetworkName());
            nicResponse.setMacAddress(userVm.getMacAddress());
            nicResponse.setIp6Address(userVm.getIp6Address());
            nicResponse.setIp6Gateway(userVm.getIp6Gateway());
            nicResponse.setIp6Cidr(userVm.getIp6Cidr());
            if (userVm.getBroadcastUri() != null) {
                nicResponse.setBroadcastUri(userVm.getBroadcastUri().toString());
            }
            if (userVm.getIsolationUri() != null) {
                nicResponse.setIsolationUri(userVm.getIsolationUri().toString());
            }
            if (userVm.getTrafficType() != null) {
                nicResponse.setTrafficType(userVm.getTrafficType().toString());
            }
            if (userVm.getGuestType() != null) {
                nicResponse.setType(userVm.getGuestType().toString());
            }
            nicResponse.setIsDefault(userVm.isDefaultNic());
            List<NicSecondaryIpVO> secondaryIps = ApiDBUtils.findNicSecondaryIps(userVm.getNicId());
            if (secondaryIps != null) {
                List<NicSecondaryIpResponse> ipList = new ArrayList<NicSecondaryIpResponse>();
                for (NicSecondaryIpVO ip : secondaryIps) {
                    NicSecondaryIpResponse ipRes = new NicSecondaryIpResponse();
                    ipRes.setId(ip.getUuid());
                    ipRes.setIpAddr(ip.getIp4Address());
                    ipList.add(ipRes);
                }
                nicResponse.setSecondaryIps(ipList);
            }
            nicResponse.setObjectName("nic");
            userVmResponse.addNic(nicResponse);
        }
    }
    // update tag information
    long tag_id = userVm.getTagId();
    if (tag_id > 0 && !userVmResponse.containTag(tag_id)) {
        addTagInformation(userVm, userVmResponse);
    }
    if (details.contains(VMDetails.all) || details.contains(VMDetails.affgrp)) {
        Long affinityGroupId = userVm.getAffinityGroupId();
        if (affinityGroupId != null && affinityGroupId.longValue() != 0) {
            AffinityGroupResponse resp = new AffinityGroupResponse();
            resp.setId(userVm.getAffinityGroupUuid());
            resp.setName(userVm.getAffinityGroupName());
            resp.setDescription(userVm.getAffinityGroupDescription());
            resp.setObjectName("affinitygroup");
            resp.setAccountName(userVm.getAccountName());
            userVmResponse.addAffinityGroup(resp);
        }
    }
    // set resource details map
    // Allow passing details to end user
    List<UserVmDetailVO> vmDetails = _userVmDetailsDao.listDetails(userVm.getId());
    if (vmDetails != null) {
        Map<String, String> resourceDetails = new HashMap<String, String>();
        for (UserVmDetailVO userVmDetailVO : vmDetails) {
            resourceDetails.put(userVmDetailVO.getName(), userVmDetailVO.getValue());
        }
        userVmResponse.setDetails(resourceDetails);
    }
    userVmResponse.setObjectName(objectName);
    if (userVm.isDynamicallyScalable() == null) {
        userVmResponse.setDynamicallyScalable(false);
    } else {
        userVmResponse.setDynamicallyScalable(userVm.isDynamicallyScalable());
    }
    return userVmResponse;
}
Also used : User(com.cloud.user.User) HashMap(java.util.HashMap) DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList) ServiceOfferingDetailsVO(com.cloud.service.ServiceOfferingDetailsVO) SecurityGroupResponse(org.apache.cloudstack.api.response.SecurityGroupResponse) UserVmResponse(org.apache.cloudstack.api.response.UserVmResponse) NicSecondaryIpResponse(org.apache.cloudstack.api.response.NicSecondaryIpResponse) UserVmDetailVO(com.cloud.vm.UserVmDetailVO) NicSecondaryIpVO(com.cloud.vm.dao.NicSecondaryIpVO) AffinityGroupResponse(org.apache.cloudstack.affinity.AffinityGroupResponse) VmStats(com.cloud.vm.VmStats) NicResponse(org.apache.cloudstack.api.response.NicResponse)

Example 5 with ServiceOfferingDetailsVO

use of com.cloud.service.ServiceOfferingDetailsVO in project cloudstack by apache.

the class DeploymentPlanningManagerImpl method planDeployment.

@Override
public DeployDestination planDeployment(VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids, DeploymentPlanner planner) throws InsufficientServerCapacityException, AffinityConflictException {
    ServiceOffering offering = vmProfile.getServiceOffering();
    int cpu_requested = offering.getCpu() * offering.getSpeed();
    long ram_requested = offering.getRamSize() * 1024L * 1024L;
    VirtualMachine vm = vmProfile.getVirtualMachine();
    DataCenter dc = _dcDao.findById(vm.getDataCenterId());
    if (vm.getType() == VirtualMachine.Type.User || vm.getType() == VirtualMachine.Type.DomainRouter) {
        checkForNonDedicatedResources(vmProfile, dc, avoids);
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("DeploymentPlanner allocation algorithm: " + planner);
        s_logger.debug("Trying to allocate a host and storage pools from dc:" + plan.getDataCenterId() + ", pod:" + plan.getPodId() + ",cluster:" + plan.getClusterId() + ", requested cpu: " + cpu_requested + ", requested ram: " + ram_requested);
        s_logger.debug("Is ROOT volume READY (pool already allocated)?: " + (plan.getPoolId() != null ? "Yes" : "No"));
    }
    String haVmTag = (String) vmProfile.getParameter(VirtualMachineProfile.Param.HaTag);
    if (plan.getHostId() != null && haVmTag == null) {
        Long hostIdSpecified = plan.getHostId();
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("DeploymentPlan has host_id specified, choosing this host and making no checks on this host: " + hostIdSpecified);
        }
        HostVO host = _hostDao.findById(hostIdSpecified);
        if (host == null) {
            s_logger.debug("The specified host cannot be found");
        } else if (avoids.shouldAvoid(host)) {
            s_logger.debug("The specified host is in avoid set");
        } else {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Looking for suitable pools for this host under zone: " + host.getDataCenterId() + ", pod: " + host.getPodId() + ", cluster: " + host.getClusterId());
            }
            Pod pod = _podDao.findById(host.getPodId());
            Cluster cluster = _clusterDao.findById(host.getClusterId());
            if (vm.getHypervisorType() == HypervisorType.BareMetal) {
                DeployDestination dest = new DeployDestination(dc, pod, cluster, host, new HashMap<Volume, StoragePool>());
                s_logger.debug("Returning Deployment Destination: " + dest);
                return dest;
            }
            // search for storage under the zone, pod, cluster of the host.
            DataCenterDeployment lastPlan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), hostIdSpecified, plan.getPoolId(), null, plan.getReservationContext());
            Pair<Map<Volume, List<StoragePool>>, List<Volume>> result = findSuitablePoolsForVolumes(vmProfile, lastPlan, avoids, HostAllocator.RETURN_UPTO_ALL);
            Map<Volume, List<StoragePool>> suitableVolumeStoragePools = result.first();
            List<Volume> readyAndReusedVolumes = result.second();
            // choose the potential pool for this VM for this host
            if (!suitableVolumeStoragePools.isEmpty()) {
                List<Host> suitableHosts = new ArrayList<Host>();
                suitableHosts.add(host);
                Pair<Host, Map<Volume, StoragePool>> potentialResources = findPotentialDeploymentResources(suitableHosts, suitableVolumeStoragePools, avoids, getPlannerUsage(planner, vmProfile, plan, avoids), readyAndReusedVolumes);
                if (potentialResources != null) {
                    pod = _podDao.findById(host.getPodId());
                    cluster = _clusterDao.findById(host.getClusterId());
                    Map<Volume, StoragePool> storageVolMap = potentialResources.second();
                    // we don't have to prepare this volume.
                    for (Volume vol : readyAndReusedVolumes) {
                        storageVolMap.remove(vol);
                    }
                    DeployDestination dest = new DeployDestination(dc, pod, cluster, host, storageVolMap);
                    s_logger.debug("Returning Deployment Destination: " + dest);
                    return dest;
                }
            }
        }
        s_logger.debug("Cannot deploy to specified host, returning.");
        return null;
    }
    // call affinitygroup chain
    long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
    if (vmGroupCount > 0) {
        for (AffinityGroupProcessor processor : _affinityProcessors) {
            processor.process(vmProfile, plan, avoids);
        }
    }
    if (vm.getType() == VirtualMachine.Type.User) {
        checkForNonDedicatedResources(vmProfile, dc, avoids);
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Deploy avoids pods: " + avoids.getPodsToAvoid() + ", clusters: " + avoids.getClustersToAvoid() + ", hosts: " + avoids.getHostsToAvoid());
    }
    // check if datacenter is in avoid set
    if (avoids.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;
    }
    if (planner == null) {
        String plannerName = offering.getDeploymentPlanner();
        if (plannerName == null) {
            if (vm.getHypervisorType() == HypervisorType.BareMetal) {
                plannerName = "BareMetalPlanner";
            } else {
                plannerName = _configDao.getValue(Config.VmDeploymentPlanner.key());
            }
        }
        planner = getDeploymentPlannerByName(plannerName);
    }
    if (vm.getLastHostId() != null && haVmTag == null) {
        s_logger.debug("This VM has last host_id specified, trying to choose the same host: " + vm.getLastHostId());
        HostVO host = _hostDao.findById(vm.getLastHostId());
        ServiceOfferingDetailsVO offeringDetails = null;
        if (host == null) {
            s_logger.debug("The last host of this VM cannot be found");
        } else if (avoids.shouldAvoid(host)) {
            s_logger.debug("The last host of this VM is in avoid set");
        } else if (plan.getClusterId() != null && host.getClusterId() != null && !plan.getClusterId().equals(host.getClusterId())) {
            s_logger.debug("The last host of this VM cannot be picked as the plan specifies different clusterId: " + plan.getClusterId());
        } else if (_capacityMgr.checkIfHostReachMaxGuestLimit(host)) {
            s_logger.debug("The last Host, hostId: " + host.getId() + " already has max Running VMs(count includes system VMs), skipping this and trying other available hosts");
        } else if ((offeringDetails = _serviceOfferingDetailsDao.findDetail(offering.getId(), GPU.Keys.vgpuType.toString())) != null) {
            ServiceOfferingDetailsVO groupName = _serviceOfferingDetailsDao.findDetail(offering.getId(), GPU.Keys.pciDevice.toString());
            if (!_resourceMgr.isGPUDeviceAvailable(host.getId(), groupName.getValue(), offeringDetails.getValue())) {
                s_logger.debug("The last host of this VM does not have required GPU devices available");
            }
        } else {
            if (host.getStatus() == Status.Up && host.getResourceState() == ResourceState.Enabled) {
                boolean hostTagsMatch = true;
                if (offering.getHostTag() != null) {
                    _hostDao.loadHostTags(host);
                    if (!(host.getHostTags() != null && host.getHostTags().contains(offering.getHostTag()))) {
                        hostTagsMatch = false;
                    }
                }
                if (hostTagsMatch) {
                    long cluster_id = host.getClusterId();
                    ClusterDetailsVO cluster_detail_cpu = _clusterDetailsDao.findDetail(cluster_id, "cpuOvercommitRatio");
                    ClusterDetailsVO cluster_detail_ram = _clusterDetailsDao.findDetail(cluster_id, "memoryOvercommitRatio");
                    Float cpuOvercommitRatio = Float.parseFloat(cluster_detail_cpu.getValue());
                    Float memoryOvercommitRatio = Float.parseFloat(cluster_detail_ram.getValue());
                    boolean hostHasCpuCapability, hostHasCapacity = false;
                    hostHasCpuCapability = _capacityMgr.checkIfHostHasCpuCapability(host.getId(), offering.getCpu(), offering.getSpeed());
                    if (hostHasCpuCapability) {
                        // first check from reserved capacity
                        hostHasCapacity = _capacityMgr.checkIfHostHasCapacity(host.getId(), cpu_requested, ram_requested, true, cpuOvercommitRatio, memoryOvercommitRatio, true);
                        // if not reserved, check the free capacity
                        if (!hostHasCapacity)
                            hostHasCapacity = _capacityMgr.checkIfHostHasCapacity(host.getId(), cpu_requested, ram_requested, false, cpuOvercommitRatio, memoryOvercommitRatio, true);
                    }
                    if (hostHasCapacity && hostHasCpuCapability) {
                        s_logger.debug("The last host of this VM is UP and has enough capacity");
                        s_logger.debug("Now checking for suitable pools under zone: " + host.getDataCenterId() + ", pod: " + host.getPodId() + ", cluster: " + host.getClusterId());
                        Pod pod = _podDao.findById(host.getPodId());
                        Cluster cluster = _clusterDao.findById(host.getClusterId());
                        if (vm.getHypervisorType() == HypervisorType.BareMetal) {
                            DeployDestination dest = new DeployDestination(dc, pod, cluster, host, new HashMap<Volume, StoragePool>());
                            s_logger.debug("Returning Deployment Destination: " + dest);
                            return dest;
                        }
                        // search for storage under the zone, pod, cluster
                        // of
                        // the last host.
                        DataCenterDeployment lastPlan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), plan.getPoolId(), null);
                        Pair<Map<Volume, List<StoragePool>>, List<Volume>> result = findSuitablePoolsForVolumes(vmProfile, lastPlan, avoids, HostAllocator.RETURN_UPTO_ALL);
                        Map<Volume, List<StoragePool>> suitableVolumeStoragePools = result.first();
                        List<Volume> readyAndReusedVolumes = result.second();
                        // host
                        if (!suitableVolumeStoragePools.isEmpty()) {
                            List<Host> suitableHosts = new ArrayList<Host>();
                            suitableHosts.add(host);
                            Pair<Host, Map<Volume, StoragePool>> potentialResources = findPotentialDeploymentResources(suitableHosts, suitableVolumeStoragePools, avoids, getPlannerUsage(planner, vmProfile, plan, avoids), readyAndReusedVolumes);
                            if (potentialResources != null) {
                                Map<Volume, StoragePool> storageVolMap = potentialResources.second();
                                // this volume.
                                for (Volume vol : readyAndReusedVolumes) {
                                    storageVolMap.remove(vol);
                                }
                                DeployDestination dest = new DeployDestination(dc, pod, cluster, host, storageVolMap);
                                s_logger.debug("Returning Deployment Destination: " + dest);
                                return dest;
                            }
                        }
                    } else {
                        s_logger.debug("The last host of this VM does not have enough capacity");
                    }
                } else {
                    s_logger.debug("Service Offering host tag does not match the last host of this VM");
                }
            } else {
                s_logger.debug("The last host of this VM is not UP or is not enabled, host status is: " + host.getStatus().name() + ", host resource state is: " + host.getResourceState());
            }
        }
        s_logger.debug("Cannot choose the last host to deploy this VM ");
    }
    DeployDestination dest = null;
    List<Long> clusterList = null;
    if (planner != null && planner.canHandle(vmProfile, plan, avoids)) {
        while (true) {
            if (planner instanceof DeploymentClusterPlanner) {
                ExcludeList plannerAvoidInput = new ExcludeList(avoids.getDataCentersToAvoid(), avoids.getPodsToAvoid(), avoids.getClustersToAvoid(), avoids.getHostsToAvoid(), avoids.getPoolsToAvoid());
                clusterList = ((DeploymentClusterPlanner) planner).orderClusters(vmProfile, plan, avoids);
                if (clusterList != null && !clusterList.isEmpty()) {
                    // planner refactoring. call allocators to list hosts
                    ExcludeList plannerAvoidOutput = new ExcludeList(avoids.getDataCentersToAvoid(), avoids.getPodsToAvoid(), avoids.getClustersToAvoid(), avoids.getHostsToAvoid(), avoids.getPoolsToAvoid());
                    resetAvoidSet(plannerAvoidOutput, plannerAvoidInput);
                    dest = checkClustersforDestination(clusterList, vmProfile, plan, avoids, dc, getPlannerUsage(planner, vmProfile, plan, avoids), plannerAvoidOutput);
                    if (dest != null) {
                        return dest;
                    }
                    // reset the avoid input to the planners
                    resetAvoidSet(avoids, plannerAvoidOutput);
                } else {
                    return null;
                }
            } else {
                dest = planner.plan(vmProfile, plan, avoids);
                if (dest != null) {
                    long hostId = dest.getHost().getId();
                    avoids.addHost(dest.getHost().getId());
                    if (checkIfHostFitsPlannerUsage(hostId, DeploymentPlanner.PlannerResourceUsage.Shared)) {
                        // found destination
                        return dest;
                    } else {
                        // deployment picked it up for dedicated access
                        continue;
                    }
                } else {
                    return null;
                }
            }
        }
    }
    return dest;
}
Also used : StoragePool(com.cloud.storage.StoragePool) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ServiceOfferingDetailsVO(com.cloud.service.ServiceOfferingDetailsVO) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) AffinityGroupProcessor(org.apache.cloudstack.affinity.AffinityGroupProcessor) Pair(com.cloud.utils.Pair) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) Pod(com.cloud.dc.Pod) ServiceOffering(com.cloud.offering.ServiceOffering) Cluster(com.cloud.org.Cluster) Host(com.cloud.host.Host) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) HostVO(com.cloud.host.HostVO) DataCenter(com.cloud.dc.DataCenter) Volume(com.cloud.storage.Volume) Map(java.util.Map) HashMap(java.util.HashMap) ClusterDetailsVO(com.cloud.dc.ClusterDetailsVO) VirtualMachine(com.cloud.vm.VirtualMachine)

Aggregations

ServiceOfferingDetailsVO (com.cloud.service.ServiceOfferingDetailsVO)6 ArrayList (java.util.ArrayList)4 ClusterDetailsVO (com.cloud.dc.ClusterDetailsVO)2 Host (com.cloud.host.Host)2 ServiceOffering (com.cloud.offering.ServiceOffering)2 Cluster (com.cloud.org.Cluster)2 User (com.cloud.user.User)2 VirtualMachine (com.cloud.vm.VirtualMachine)2 HashMap (java.util.HashMap)2 DiskTO (com.cloud.agent.api.to.DiskTO)1 NicTO (com.cloud.agent.api.to.NicTO)1 VirtualMachineTO (com.cloud.agent.api.to.VirtualMachineTO)1 DataCenter (com.cloud.dc.DataCenter)1 Pod (com.cloud.dc.Pod)1 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)1 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)1 HostVO (com.cloud.host.HostVO)1 ServiceOfferingVO (com.cloud.service.ServiceOfferingVO)1 ProvisioningType (com.cloud.storage.Storage.ProvisioningType)1 StoragePool (com.cloud.storage.StoragePool)1