Search in sources :

Example 61 with ExcludeList

use of com.cloud.deploy.DeploymentPlanner.ExcludeList in project cloudstack by apache.

the class DeploymentPlanningManagerImpl method finalizeReservation.

@DB
@Override
public String finalizeReservation(final DeployDestination plannedDestination, final VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids, final DeploymentPlanner planner) throws InsufficientServerCapacityException, AffinityConflictException {
    final VirtualMachine vm = vmProfile.getVirtualMachine();
    final long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
    return Transaction.execute(new TransactionCallback<String>() {

        @Override
        public String doInTransaction(TransactionStatus status) {
            boolean saveReservation = true;
            if (vmGroupCount > 0) {
                List<Long> groupIds = _affinityGroupVMMapDao.listAffinityGroupIdsByVmId(vm.getId());
                SearchCriteria<AffinityGroupVO> criteria = _affinityGroupDao.createSearchCriteria();
                criteria.addAnd("id", SearchCriteria.Op.IN, groupIds.toArray(new Object[groupIds.size()]));
                _affinityGroupDao.lockRows(criteria, null, true);
                for (AffinityGroupProcessor processor : _affinityProcessors) {
                    if (!processor.check(vmProfile, plannedDestination)) {
                        saveReservation = false;
                        break;
                    }
                }
            }
            if (saveReservation) {
                VMReservationVO vmReservation = new VMReservationVO(vm.getId(), plannedDestination.getDataCenter().getId(), plannedDestination.getPod().getId(), plannedDestination.getCluster().getId(), plannedDestination.getHost().getId());
                if (planner != null) {
                    vmReservation.setDeploymentPlanner(planner.getName());
                }
                Map<Long, Long> volumeReservationMap = new HashMap<Long, Long>();
                if (vm.getHypervisorType() != HypervisorType.BareMetal) {
                    for (Volume vo : plannedDestination.getStorageForDisks().keySet()) {
                        volumeReservationMap.put(vo.getId(), plannedDestination.getStorageForDisks().get(vo).getId());
                    }
                    vmReservation.setVolumeReservation(volumeReservationMap);
                }
                _reservationDao.persist(vmReservation);
                return vmReservation.getUuid();
            }
            return null;
        }
    });
}
Also used : TransactionStatus(com.cloud.utils.db.TransactionStatus) SearchCriteria(com.cloud.utils.db.SearchCriteria) VMReservationVO(org.apache.cloudstack.engine.cloud.entity.api.db.VMReservationVO) Volume(com.cloud.storage.Volume) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) AffinityGroupProcessor(org.apache.cloudstack.affinity.AffinityGroupProcessor) Map(java.util.Map) HashMap(java.util.HashMap) VirtualMachine(com.cloud.vm.VirtualMachine) DB(com.cloud.utils.db.DB)

Example 62 with ExcludeList

use of com.cloud.deploy.DeploymentPlanner.ExcludeList 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: " + toHumanReadableSize(ram_requested));
        s_logger.debug("Is ROOT volume READY (pool already allocated)?: " + (plan.getPoolId() != null ? "Yes" : "No"));
    }
    avoidDisabledResources(vmProfile, dc, avoids);
    String haVmTag = (String) vmProfile.getParameter(VirtualMachineProfile.Param.HaTag);
    String uefiFlag = (String) vmProfile.getParameter(VirtualMachineProfile.Param.UefiFlag);
    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 && StringUtils.isNotBlank(uefiFlag) && "yes".equalsIgnoreCase(uefiFlag)) {
            _hostDao.loadDetails(host);
            if (MapUtils.isNotEmpty(host.getDetails()) && host.getDetails().containsKey(Host.HOST_UEFI_ENABLE) && "false".equalsIgnoreCase(host.getDetails().get(Host.HOST_UEFI_ENABLE))) {
                s_logger.debug("Cannot deploy to specified host as host does n't support uefi vm deployment, returning.");
                return null;
            }
        }
        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());
            boolean displayStorage = getDisplayStorageFromVmProfile(vmProfile);
            if (vm.getHypervisorType() == HypervisorType.BareMetal) {
                DeployDestination dest = new DeployDestination(dc, pod, cluster, host, new HashMap<Volume, StoragePool>(), displayStorage);
                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, plan.getPreferredHosts(), vm);
                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, displayStorage);
                    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 (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) {
                if (checkVmProfileAndHost(vmProfile, host)) {
                    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);
                    }
                    boolean displayStorage = getDisplayStorageFromVmProfile(vmProfile);
                    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>(), displayStorage);
                            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, plan.getPreferredHosts(), vm);
                            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, displayStorage);
                                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("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)

Example 63 with ExcludeList

use of com.cloud.deploy.DeploymentPlanner.ExcludeList in project cloudstack by apache.

the class UserVmManagerImpl method startVirtualMachine.

@Override
public Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> startVirtualMachine(long vmId, Long podId, Long clusterId, Long hostId, Map<VirtualMachineProfile.Param, Object> additionalParams, String deploymentPlannerToUse, boolean isExplicitHost) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException {
    // Input validation
    final Account callerAccount = CallContext.current().getCallingAccount();
    UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
    // if account is removed, return error
    if (callerAccount != null && callerAccount.getRemoved() != null) {
        throw new InvalidParameterValueException("The account " + callerAccount.getId() + " is removed");
    }
    UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
    }
    if (vm.getState() == State.Running) {
        throw new InvalidParameterValueException("The virtual machine " + vm.getUuid() + " (" + vm.getDisplayName() + ") is already running");
    }
    _accountMgr.checkAccess(callerAccount, null, true, vm);
    Account owner = _accountDao.findById(vm.getAccountId());
    if (owner == null) {
        throw new InvalidParameterValueException("The owner of " + vm + " does not exist: " + vm.getAccountId());
    }
    if (owner.getState() == Account.State.disabled) {
        throw new PermissionDeniedException("The owner of " + vm + " is disabled: " + vm.getAccountId());
    }
    if (VirtualMachineManager.ResourceCountRunningVMsonly.value()) {
        // check if account/domain is with in resource limits to start a new vm
        ServiceOfferingVO offering = _serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
        resourceLimitCheck(owner, vm.isDisplayVm(), Long.valueOf(offering.getCpu()), Long.valueOf(offering.getRamSize()));
    }
    // check if vm is security group enabled
    if (_securityGroupMgr.isVmSecurityGroupEnabled(vmId) && _securityGroupMgr.getSecurityGroupsForVm(vmId).isEmpty() && !_securityGroupMgr.isVmMappedToDefaultSecurityGroup(vmId) && _networkModel.canAddDefaultSecurityGroup()) {
        // if vm is not mapped to security group, create a mapping
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Vm " + vm + " is security group enabled, but not mapped to default security group; creating the mapping automatically");
        }
        SecurityGroup defaultSecurityGroup = _securityGroupMgr.getDefaultSecurityGroup(vm.getAccountId());
        if (defaultSecurityGroup != null) {
            List<Long> groupList = new ArrayList<Long>();
            groupList.add(defaultSecurityGroup.getId());
            _securityGroupMgr.addInstanceToGroups(vmId, groupList);
        }
    }
    // Choose deployment planner
    // Host takes 1st preference, Cluster takes 2nd preference and Pod takes 3rd
    // Default behaviour is invoked when host, cluster or pod are not specified
    boolean isRootAdmin = _accountService.isRootAdmin(callerAccount.getId());
    Pod destinationPod = getDestinationPod(podId, isRootAdmin);
    Cluster destinationCluster = getDestinationCluster(clusterId, isRootAdmin);
    Host destinationHost = getDestinationHost(hostId, isRootAdmin, isExplicitHost);
    DataCenterDeployment plan = null;
    boolean deployOnGivenHost = false;
    if (destinationHost != null) {
        s_logger.debug("Destination Host to deploy the VM is specified, specifying a deployment plan to deploy the VM");
        final ServiceOfferingVO offering = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId());
        Pair<Boolean, Boolean> cpuCapabilityAndCapacity = _capacityMgr.checkIfHostHasCpuCapabilityAndCapacity(destinationHost, offering, false);
        if (!cpuCapabilityAndCapacity.first() || !cpuCapabilityAndCapacity.second()) {
            String errorMsg = "Cannot deploy the VM to specified host " + hostId + "; host has cpu capability? " + cpuCapabilityAndCapacity.first() + ", host has capacity? " + cpuCapabilityAndCapacity.second();
            s_logger.info(errorMsg);
            if (!AllowDeployVmIfGivenHostFails.value()) {
                throw new InvalidParameterValueException(errorMsg);
            }
            ;
        } else {
            plan = new DataCenterDeployment(vm.getDataCenterId(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null, null);
            if (!AllowDeployVmIfGivenHostFails.value()) {
                deployOnGivenHost = true;
            }
        }
    } else if (destinationCluster != null) {
        s_logger.debug("Destination Cluster to deploy the VM is specified, specifying a deployment plan to deploy the VM");
        plan = new DataCenterDeployment(vm.getDataCenterId(), destinationCluster.getPodId(), destinationCluster.getId(), null, null, null);
        if (!AllowDeployVmIfGivenHostFails.value()) {
            deployOnGivenHost = true;
        }
    } else if (destinationPod != null) {
        s_logger.debug("Destination Pod to deploy the VM is specified, specifying a deployment plan to deploy the VM");
        plan = new DataCenterDeployment(vm.getDataCenterId(), destinationPod.getId(), null, null, null, null);
        if (!AllowDeployVmIfGivenHostFails.value()) {
            deployOnGivenHost = true;
        }
    }
    // Set parameters
    Map<VirtualMachineProfile.Param, Object> params = null;
    VMTemplateVO template = null;
    if (vm.isUpdateParameters()) {
        _vmDao.loadDetails(vm);
        // Check that the password was passed in and is valid
        template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId());
        String password = "saved_password";
        if (template.isEnablePassword()) {
            if (vm.getDetail("password") != null) {
                password = DBEncryptionUtil.decrypt(vm.getDetail("password"));
            } else {
                password = _mgr.generateRandomPassword();
                vm.setPassword(password);
            }
        }
        if (!validPassword(password)) {
            throw new InvalidParameterValueException("A valid password for this virtual machine was not provided.");
        }
        // Check if an SSH key pair was selected for the instance and if so
        // use it to encrypt & save the vm password
        encryptAndStorePassword(vm, password);
        params = createParameterInParameterMap(params, additionalParams, VirtualMachineProfile.Param.VmPassword, password);
    }
    if (null != additionalParams && additionalParams.containsKey(VirtualMachineProfile.Param.BootIntoSetup)) {
        if (!HypervisorType.VMware.equals(vm.getHypervisorType())) {
            throw new InvalidParameterValueException(ApiConstants.BOOT_INTO_SETUP + " makes no sense for " + vm.getHypervisorType());
        }
        Object paramValue = additionalParams.get(VirtualMachineProfile.Param.BootIntoSetup);
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("It was specified whether to enter setup mode: " + paramValue.toString());
        }
        params = createParameterInParameterMap(params, additionalParams, VirtualMachineProfile.Param.BootIntoSetup, paramValue);
    }
    VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
    DeploymentPlanner planner = null;
    if (deploymentPlannerToUse != null) {
        // if set to null, the deployment planner would be later figured out either from global config var, or from
        // the service offering
        planner = _planningMgr.getDeploymentPlannerByName(deploymentPlannerToUse);
        if (planner == null) {
            throw new InvalidParameterValueException("Can't find a planner by name " + deploymentPlannerToUse);
        }
    }
    vmEntity.setParamsToEntity(additionalParams);
    String reservationId = vmEntity.reserve(planner, plan, new ExcludeList(), Long.toString(callerUser.getId()));
    vmEntity.deploy(reservationId, Long.toString(callerUser.getId()), params, deployOnGivenHost);
    Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> vmParamPair = new Pair(vm, params);
    if (vm != null && vm.isUpdateParameters()) {
        // display purposes
        if (template.isEnablePassword()) {
            if (vm.getDetail(VmDetailConstants.PASSWORD) != null) {
                userVmDetailsDao.removeDetail(vm.getId(), VmDetailConstants.PASSWORD);
            }
            vm.setUpdateParameters(false);
            _vmDao.update(vm.getId(), vm);
        }
    }
    return vmParamPair;
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) VMTemplateVO(com.cloud.storage.VMTemplateVO) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Pair(com.cloud.utils.Pair) SSHKeyPair(com.cloud.user.SSHKeyPair) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) Pod(com.cloud.dc.Pod) VirtualMachineEntity(org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity) Cluster(com.cloud.org.Cluster) Host(com.cloud.host.Host) SecurityGroup(com.cloud.network.security.SecurityGroup) UserVO(com.cloud.user.UserVO) DeploymentPlanner(com.cloud.deploy.DeploymentPlanner) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 64 with ExcludeList

use of com.cloud.deploy.DeploymentPlanner.ExcludeList in project cloudstack by apache.

the class FirstFitPlannerTest method initializeForTest.

private void initializeForTest(VirtualMachineProfileImpl vmProfile, DataCenterDeployment plan, ExcludeList avoids) {
    DataCenterVO mockDc = mock(DataCenterVO.class);
    VMInstanceVO vm = mock(VMInstanceVO.class);
    UserVmVO userVm = mock(UserVmVO.class);
    ServiceOfferingVO offering = mock(ServiceOfferingVO.class);
    AccountVO account = mock(AccountVO.class);
    when(account.getId()).thenReturn(accountId);
    when(account.getAccountId()).thenReturn(accountId);
    when(vmProfile.getOwner()).thenReturn(account);
    when(vmProfile.getVirtualMachine()).thenReturn(vm);
    when(vmProfile.getId()).thenReturn(12L);
    when(vmDao.findById(12L)).thenReturn(userVm);
    when(userVm.getAccountId()).thenReturn(accountId);
    when(vm.getDataCenterId()).thenReturn(dataCenterId);
    when(dcDao.findById(1L)).thenReturn(mockDc);
    when(avoids.shouldAvoid(mockDc)).thenReturn(false);
    when(plan.getDataCenterId()).thenReturn(dataCenterId);
    when(plan.getClusterId()).thenReturn(null);
    when(plan.getPodId()).thenReturn(null);
    // Mock offering details.
    when(vmProfile.getServiceOffering()).thenReturn(offering);
    when(offering.getId()).thenReturn(offeringId);
    when(vmProfile.getServiceOfferingId()).thenReturn(offeringId);
    when(offering.getCpu()).thenReturn(noOfCpusInOffering);
    when(offering.getSpeed()).thenReturn(cpuSpeedInOffering);
    when(offering.getRamSize()).thenReturn(ramInOffering);
    List<Long> clustersWithEnoughCapacity = new ArrayList<Long>();
    clustersWithEnoughCapacity.add(1L);
    clustersWithEnoughCapacity.add(2L);
    clustersWithEnoughCapacity.add(3L);
    clustersWithEnoughCapacity.add(4L);
    clustersWithEnoughCapacity.add(5L);
    clustersWithEnoughCapacity.add(6L);
    when(capacityDao.listClustersInZoneOrPodByHostCapacities(dataCenterId, 12L, noOfCpusInOffering * cpuSpeedInOffering, ramInOffering * 1024L * 1024L, Capacity.CAPACITY_TYPE_CPU, true)).thenReturn(clustersWithEnoughCapacity);
    Map<Long, Double> clusterCapacityMap = new HashMap<Long, Double>();
    clusterCapacityMap.put(1L, 2048D);
    clusterCapacityMap.put(2L, 2048D);
    clusterCapacityMap.put(3L, 2048D);
    clusterCapacityMap.put(4L, 2048D);
    clusterCapacityMap.put(5L, 2048D);
    clusterCapacityMap.put(6L, 2048D);
    Pair<List<Long>, Map<Long, Double>> clustersOrderedByCapacity = new Pair<List<Long>, Map<Long, Double>>(clustersWithEnoughCapacity, clusterCapacityMap);
    when(capacityDao.orderClustersByAggregateCapacity(dataCenterId, 12L, Capacity.CAPACITY_TYPE_CPU, true)).thenReturn(clustersOrderedByCapacity);
    List<Long> disabledClusters = new ArrayList<Long>();
    List<Long> clustersWithDisabledPods = new ArrayList<Long>();
    when(clusterDao.listDisabledClusters(dataCenterId, null)).thenReturn(disabledClusters);
    when(clusterDao.listClustersWithDisabledPods(dataCenterId)).thenReturn(clustersWithDisabledPods);
    List<Long> hostList0 = new ArrayList<Long>();
    List<Long> hostList1 = new ArrayList<Long>();
    List<Long> hostList2 = new ArrayList<Long>();
    List<Long> hostList3 = new ArrayList<Long>();
    List<Long> hostList4 = new ArrayList<Long>();
    List<Long> hostList5 = new ArrayList<Long>();
    List<Long> hostList6 = new ArrayList<Long>();
    hostList0.add(new Long(1));
    hostList1.add(new Long(10));
    hostList2.add(new Long(11));
    hostList3.add(new Long(12));
    hostList4.add(new Long(13));
    hostList5.add(new Long(14));
    hostList6.add(new Long(15));
    String[] implicitHostTags = { "GPU" };
    int ramInBytes = ramInOffering * 1024 * 1024;
    when(serviceOfferingDetailsDao.findDetail(Matchers.anyLong(), anyString())).thenReturn(null);
    when(hostGpuGroupsDao.listHostIds()).thenReturn(hostList0);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering * cpuSpeedInOffering, ramInBytes, new Long(1), Host.Type.Routing.toString())).thenReturn(hostList1);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering * cpuSpeedInOffering, ramInBytes, new Long(2), Host.Type.Routing.toString())).thenReturn(hostList2);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering * cpuSpeedInOffering, ramInBytes, new Long(3), Host.Type.Routing.toString())).thenReturn(hostList3);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering * cpuSpeedInOffering, ramInBytes, new Long(4), Host.Type.Routing.toString())).thenReturn(hostList4);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering * cpuSpeedInOffering, ramInBytes, new Long(5), Host.Type.Routing.toString())).thenReturn(hostList5);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering * cpuSpeedInOffering, ramInBytes, new Long(6), Host.Type.Routing.toString())).thenReturn(hostList6);
    when(hostTagsDao.getDistinctImplicitHostTags(hostList1, implicitHostTags)).thenReturn(Arrays.asList("abc", "pqr", "xyz"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList2, implicitHostTags)).thenReturn(Arrays.asList("abc", "123", "pqr", "456", "xyz"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList3, implicitHostTags)).thenReturn(Arrays.asList("abc", "pqr"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList4, implicitHostTags)).thenReturn(Arrays.asList("abc"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList5, implicitHostTags)).thenReturn(Arrays.asList("abc", "pqr", "xyz"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList6, implicitHostTags)).thenReturn(Arrays.asList("abc", "123", "pqr", "xyz"));
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) AccountVO(com.cloud.user.AccountVO) List(java.util.List) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) Map(java.util.Map) HashMap(java.util.HashMap) Pair(com.cloud.utils.Pair)

Example 65 with ExcludeList

use of com.cloud.deploy.DeploymentPlanner.ExcludeList in project cloudstack by apache.

the class FirstFitPlannerTest method checkClusterReorderingForDeployVMWithThresholdCheckDisabled.

@Test
public void checkClusterReorderingForDeployVMWithThresholdCheckDisabled() throws InsufficientServerCapacityException {
    VirtualMachineProfileImpl vmProfile = mock(VirtualMachineProfileImpl.class);
    DataCenterDeployment plan = mock(DataCenterDeployment.class);
    ExcludeList avoids = mock(ExcludeList.class);
    initializeForTest(vmProfile, plan, avoids);
    List<Long> clustersCrossingThreshold = initializeForClusterThresholdDisabled();
    Map<String, String> details = new HashMap<String, String>();
    details.put("deployvm", "true");
    when(vmDetailsDao.listDetailsKeyPairs(vmProfile.getVirtualMachine().getId())).thenReturn(details);
    List<Long> clusterList = planner.orderClusters(vmProfile, plan, avoids);
    assertTrue("Reordered cluster list have clusters exceeding threshold", (!clusterList.containsAll(clustersCrossingThreshold)));
}
Also used : ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) HashMap(java.util.HashMap) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.junit.Test)

Aggregations

ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)78 DataCenterDeployment (com.cloud.deploy.DataCenterDeployment)45 ArrayList (java.util.ArrayList)32 StoragePool (com.cloud.storage.StoragePool)30 Test (org.junit.Test)30 HashMap (java.util.HashMap)23 Volume (com.cloud.storage.Volume)21 VirtualMachineProfileImpl (com.cloud.vm.VirtualMachineProfileImpl)18 List (java.util.List)18 Host (com.cloud.host.Host)16 HostVO (com.cloud.host.HostVO)16 Pair (com.cloud.utils.Pair)16 StoragePoolAllocator (org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator)16 DiskProfile (com.cloud.vm.DiskProfile)15 VirtualMachineProfile (com.cloud.vm.VirtualMachineProfile)15 DiskOfferingVO (com.cloud.storage.DiskOfferingVO)14 VolumeVO (com.cloud.storage.VolumeVO)14 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)14 Account (com.cloud.user.Account)12 Map (java.util.Map)11