Search in sources :

Example 61 with DataCenterDeployment

use of com.cloud.deploy.DataCenterDeployment 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 62 with DataCenterDeployment

use of com.cloud.deploy.DataCenterDeployment in project cloudstack by apache.

the class NetworkMigrationManagerImpl method upgradeNetworkToNewNetworkOffering.

@Override
public Network upgradeNetworkToNewNetworkOffering(long networkId, long newPhysicalNetworkId, long networkOfferingId, Long vpcId) {
    s_logger.debug("upgrading network to network with new offering.");
    NetworkVO network = _networksDao.findById(networkId);
    NetworkOffering newOffering = _networkOfferingDao.findByIdIncludingRemoved(networkOfferingId);
    long gurusImplementing = 0;
    network.setBroadcastUri(null);
    AccountVO networkAccount = _accountDao.findById(network.getAccountId());
    DataCenterDeployment plan = new DataCenterDeployment(network.getDataCenterId(), null, null, null, null, newPhysicalNetworkId);
    for (final NetworkGuru guru : _networkMgr.getNetworkGurus()) {
        final Network designedNetwork = guru.design(newOffering, plan, network, networkAccount);
        if (designedNetwork == null) {
            continue;
        }
        gurusImplementing++;
        if (gurusImplementing > 1) {
            throw new CloudRuntimeException("Failed to migrate network to new physical network. Multiple network guru's for the same network are currently not supported.");
        }
        network.setTrafficType(designedNetwork.getTrafficType());
        network.setMode(designedNetwork.getMode());
        network.setBroadcastDomainType(designedNetwork.getBroadcastDomainType());
        network.setBroadcastUri(designedNetwork.getBroadcastUri());
        network.setNetworkOfferingId(designedNetwork.getNetworkOfferingId());
        network.setState(designedNetwork.getState());
        network.setPhysicalNetworkId(designedNetwork.getPhysicalNetworkId());
        network.setRedundant(designedNetwork.isRedundant());
        network.setGateway(designedNetwork.getGateway());
        network.setCidr(designedNetwork.getCidr());
        network.setGuruName(guru.getName());
        network.setVpcId(vpcId);
    }
    _networksDao.update(network.getId(), network, _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), newPhysicalNetworkId));
    return network;
}
Also used : RouterNetworkVO(com.cloud.network.dao.RouterNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) NetworkOffering(com.cloud.offering.NetworkOffering) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NetworkGuru(com.cloud.network.guru.NetworkGuru) AccountVO(com.cloud.user.AccountVO)

Example 63 with DataCenterDeployment

use of com.cloud.deploy.DataCenterDeployment in project cloudstack by apache.

the class NetworkMigrationManagerImpl method makeCopyOfNetwork.

@Override
public long makeCopyOfNetwork(Network network, NetworkOffering networkOffering, Long vpcId) {
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Making a copy of network with uuid " + network.getUuid() + " and id " + network.getId() + " for migration.");
    }
    long originalNetworkId = network.getId();
    NetworkDomainVO domainNetworkMapByNetworkId = _networkDomainDao.getDomainNetworkMapByNetworkId(originalNetworkId);
    AccountVO networkAccount = _accountDao.findById(network.getAccountId());
    boolean subdomainAccess = true;
    if (domainNetworkMapByNetworkId != null) {
        subdomainAccess = domainNetworkMapByNetworkId.isSubdomainAccess();
    }
    DataCenterDeployment plan = new DataCenterDeployment(network.getDataCenterId(), null, null, null, null, network.getPhysicalNetworkId());
    List<? extends Network> networks = _networkMgr.setupNetwork(networkAccount, networkOffering, network, plan, network.getName(), network.getDisplayText(), true, network.getDomainId(), network.getAclType(), subdomainAccess, vpcId, true);
    _resourceLimitMgr.incrementResourceCount(network.getAccountId(), Resource.ResourceType.network, network.isDisplay());
    long networkCopyId;
    if (networks == null || networks.isEmpty()) {
        throw new CloudRuntimeException("Fail to create a network");
    } else {
        DataCenter zone = _dcDao.findById(network.getDataCenterId());
        String guestNetworkCidr = zone.getGuestNetworkCidr();
        if (networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == Networks.TrafficType.Guest) {
            Network networkCopy = networks.get(0);
            for (final Network nw : networks) {
                if (nw.getCidr() != null && nw.getCidr().equals(guestNetworkCidr)) {
                    networkCopy = nw;
                }
            }
            networkCopyId = networkCopy.getId();
        } else {
            // For shared network
            networkCopyId = networks.get(0).getId();
        }
    }
    // Update the related network
    NetworkVO originalNetwork = _networksDao.findById(originalNetworkId);
    originalNetwork.setRelated(networkCopyId);
    _networksDao.update(originalNetworkId, originalNetwork);
    NetworkVO copiedNetwork = _networksDao.findById(networkCopyId);
    copiedNetwork.setRelated(originalNetworkId);
    copiedNetwork.setDisplayNetwork(false);
    copiedNetwork.setBroadcastUri(network.getBroadcastUri());
    copiedNetwork.setState(network.getState());
    _networksDao.update(networkCopyId, copiedNetwork);
    copyNetworkDetails(originalNetworkId, networkCopyId);
    copyFirewallRulesToNewNetwork(network, networkCopyId);
    assignUserNicsToNewNetwork(originalNetworkId, networkCopyId);
    assignRouterNicsToNewNetwork(network.getId(), networkCopyId);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Succesfully created a copy of network  " + originalNetwork.getName() + "(" + originalNetwork.getUuid() + ") id is " + originalNetwork.getId() + " for migration. The network copy has uuid " + network.getUuid() + " and id " + network.getId());
    }
    return networkCopyId;
}
Also used : RouterNetworkVO(com.cloud.network.dao.RouterNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) DataCenter(com.cloud.dc.DataCenter) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NetworkDomainVO(com.cloud.network.dao.NetworkDomainVO) AccountVO(com.cloud.user.AccountVO)

Example 64 with DataCenterDeployment

use of com.cloud.deploy.DataCenterDeployment 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)

Example 65 with DataCenterDeployment

use of com.cloud.deploy.DataCenterDeployment in project cloudstack by apache.

the class FirstFitPlannerTest method checkClusterReorderingBasedOnImplicitHostTags.

@Test
public void checkClusterReorderingBasedOnImplicitHostTags() throws InsufficientServerCapacityException {
    VirtualMachineProfileImpl vmProfile = mock(VirtualMachineProfileImpl.class);
    DataCenterDeployment plan = mock(DataCenterDeployment.class);
    ExcludeList avoids = mock(ExcludeList.class);
    initializeForTest(vmProfile, plan, avoids);
    List<Long> clusterList = planner.orderClusters(vmProfile, plan, avoids);
    List<Long> reorderedClusterList = new ArrayList<Long>();
    reorderedClusterList.add(4L);
    reorderedClusterList.add(3L);
    reorderedClusterList.add(1L);
    reorderedClusterList.add(5L);
    reorderedClusterList.add(6L);
    reorderedClusterList.add(2L);
    assertTrue("Reordered cluster list is not honoring the implict host tags", (clusterList.equals(reorderedClusterList)));
}
Also used : ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Aggregations

DataCenterDeployment (com.cloud.deploy.DataCenterDeployment)89 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)45 ArrayList (java.util.ArrayList)28 Test (org.junit.Test)28 VirtualMachineProfileImpl (com.cloud.vm.VirtualMachineProfileImpl)24 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)23 StoragePool (com.cloud.storage.StoragePool)19 HashMap (java.util.HashMap)19 VirtualMachineProfile (com.cloud.vm.VirtualMachineProfile)18 ServiceOfferingVO (com.cloud.service.ServiceOfferingVO)17 DeployDestination (com.cloud.deploy.DeployDestination)16 VolumeVO (com.cloud.storage.VolumeVO)16 LinkedHashMap (java.util.LinkedHashMap)16 StoragePoolAllocator (org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator)14 DeploymentPlan (com.cloud.deploy.DeploymentPlan)13 NetworkVO (com.cloud.network.dao.NetworkVO)13 List (java.util.List)13 DiskProfile (com.cloud.vm.DiskProfile)12 VMInstanceVO (com.cloud.vm.VMInstanceVO)12 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)11