Search in sources :

Example 6 with ServiceOfferingVO

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

the class ServiceOfferingDaoImpl method findByIdIncludingRemoved.

@Override
public ServiceOfferingVO findByIdIncludingRemoved(Long vmId, long serviceOfferingId) {
    ServiceOfferingVO offering = super.findByIdIncludingRemoved(serviceOfferingId);
    if (offering.isDynamic()) {
        offering.setDynamicFlag(true);
        if (vmId == null) {
            throw new CloudRuntimeException("missing argument vmId");
        }
        Map<String, String> dynamicOffering = userVmDetailsDao.listDetailsKeyPairs(vmId);
        return getcomputeOffering(offering, dynamicOffering);
    }
    return offering;
}
Also used : CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO)

Example 7 with ServiceOfferingVO

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

the class InternalLoadBalancerVMManagerImpl method deployInternalLbVm.

protected DomainRouterVO deployInternalLbVm(final Account owner, final DeployDestination dest, final DeploymentPlan plan, final Map<Param, Object> params, final long internalLbProviderId, final long svcOffId, final Long vpcId, final LinkedHashMap<Network, List<? extends NicProfile>> networks, final boolean startVm) throws ConcurrentOperationException, InsufficientAddressCapacityException, InsufficientServerCapacityException, InsufficientCapacityException, StorageUnavailableException, ResourceUnavailableException {
    final ServiceOfferingVO routerOffering = _serviceOfferingDao.findById(svcOffId);
    // Internal lb is the network element, we don't know the hypervisor type yet.
    // Try to allocate the internal lb twice using diff hypervisors, and when failed both times, throw the exception up
    final List<HypervisorType> hypervisors = getHypervisors(dest, plan, null);
    int allocateRetry = 0;
    int startRetry = 0;
    DomainRouterVO internalLbVm = null;
    for (final Iterator<HypervisorType> iter = hypervisors.iterator(); iter.hasNext(); ) {
        final HypervisorType hType = iter.next();
        try {
            final long id = _internalLbVmDao.getNextInSequence(Long.class, "id");
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Creating the internal lb vm " + id + " in datacenter " + dest.getDataCenter() + " with hypervisor type " + hType);
            }
            String templateName = null;
            switch(hType) {
                case XenServer:
                    templateName = VirtualNetworkApplianceManager.RouterTemplateXen.valueIn(dest.getDataCenter().getId());
                    break;
                case KVM:
                    templateName = VirtualNetworkApplianceManager.RouterTemplateKvm.valueIn(dest.getDataCenter().getId());
                    break;
                case VMware:
                    templateName = VirtualNetworkApplianceManager.RouterTemplateVmware.valueIn(dest.getDataCenter().getId());
                    break;
                case Hyperv:
                    templateName = VirtualNetworkApplianceManager.RouterTemplateHyperV.valueIn(dest.getDataCenter().getId());
                    break;
                case LXC:
                    templateName = VirtualNetworkApplianceManager.RouterTemplateLxc.valueIn(dest.getDataCenter().getId());
                    break;
                default:
                    break;
            }
            final VMTemplateVO template = _templateDao.findRoutingTemplate(hType, templateName);
            if (template == null) {
                s_logger.debug(hType + " won't support system vm, skip it");
                continue;
            }
            long userId = CallContext.current().getCallingUserId();
            if (CallContext.current().getCallingAccount().getId() != owner.getId()) {
                List<UserVO> userVOs = _userDao.listByAccount(owner.getAccountId());
                if (!userVOs.isEmpty()) {
                    userId = userVOs.get(0).getId();
                }
            }
            internalLbVm = new DomainRouterVO(id, routerOffering.getId(), internalLbProviderId, VirtualMachineName.getSystemVmName(id, _instance, InternalLbVmNamePrefix), template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, false, RedundantState.UNKNOWN, false, false, VirtualMachine.Type.InternalLoadBalancerVm, vpcId);
            internalLbVm.setRole(Role.INTERNAL_LB_VM);
            internalLbVm = _internalLbVmDao.persist(internalLbVm);
            _itMgr.allocate(internalLbVm.getInstanceName(), template, routerOffering, networks, plan, null);
            internalLbVm = _internalLbVmDao.findById(internalLbVm.getId());
        } catch (final InsufficientCapacityException ex) {
            if (allocateRetry < 2 && iter.hasNext()) {
                s_logger.debug("Failed to allocate the Internal lb vm with hypervisor type " + hType + ", retrying one more time");
                continue;
            } else {
                throw ex;
            }
        } finally {
            allocateRetry++;
        }
        if (startVm) {
            try {
                internalLbVm = startInternalLbVm(internalLbVm, _accountMgr.getSystemAccount(), User.UID_SYSTEM, params);
                break;
            } catch (final InsufficientCapacityException ex) {
                if (startRetry < 2 && iter.hasNext()) {
                    s_logger.debug("Failed to start the Internal lb vm  " + internalLbVm + " with hypervisor type " + hType + ", " + "destroying it and recreating one more time");
                    // destroy the internal lb vm
                    destroyInternalLbVm(internalLbVm.getId(), _accountMgr.getSystemAccount(), User.UID_SYSTEM);
                    continue;
                } else {
                    throw ex;
                }
            } finally {
                startRetry++;
            }
        } else {
            //return stopped internal lb vm
            return internalLbVm;
        }
    }
    return internalLbVm;
}
Also used : HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) UserVO(com.cloud.user.UserVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 8 with ServiceOfferingVO

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

the class UserVmManagerImpl method recoverVirtualMachine.

@Override
@DB
public UserVm recoverVirtualMachine(RecoverVMCmd cmd) throws ResourceAllocationException, CloudRuntimeException {
    final Long vmId = cmd.getId();
    Account caller = CallContext.current().getCallingAccount();
    final Long userId = caller.getAccountId();
    // Verify input parameters
    final UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
    }
    // When trying to expunge, permission is denied when the caller is not an admin and the AllowUserExpungeRecoverVm is false for the caller.
    if (!_accountMgr.isAdmin(userId) && !AllowUserExpungeRecoverVm.valueIn(userId)) {
        throw new PermissionDeniedException("Recovering a vm can only be done by an Admin. Or when the allow.user.expunge.recover.vm key is set.");
    }
    if (vm.getRemoved() != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Unable to find vm or vm is removed: " + vmId);
        }
        throw new InvalidParameterValueException("Unable to find vm by id " + vmId);
    }
    if (vm.getState() != State.Destroyed) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("vm is not in the right state: " + vmId);
        }
        throw new InvalidParameterValueException("Vm with id " + vmId + " is not in the right state");
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Recovering vm " + vmId);
    }
    Transaction.execute(new TransactionCallbackWithExceptionNoReturn<ResourceAllocationException>() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) throws ResourceAllocationException {
            Account account = _accountDao.lockRow(vm.getAccountId(), true);
            // if the account is deleted, throw error
            if (account.getRemoved() != null) {
                throw new CloudRuntimeException("Unable to recover VM as the account is deleted");
            }
            // Get serviceOffering for Virtual Machine
            ServiceOfferingVO serviceOffering = _serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
            // First check that the maximum number of UserVMs, CPU and Memory limit for the given
            // accountId will not be exceeded
            resourceLimitCheck(account, vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
            _haMgr.cancelDestroy(vm, vm.getHostId());
            try {
                if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.RecoveryRequested, null)) {
                    s_logger.debug("Unable to recover the vm because it is not in the correct state: " + vmId);
                    throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
                }
            } catch (NoTransitionException e) {
                throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
            }
            // Recover the VM's disks
            List<VolumeVO> volumes = _volsDao.findByInstance(vmId);
            for (VolumeVO volume : volumes) {
                if (volume.getVolumeType().equals(Volume.Type.ROOT)) {
                    // Create an event
                    Long templateId = volume.getTemplateId();
                    Long diskOfferingId = volume.getDiskOfferingId();
                    Long offeringId = null;
                    if (diskOfferingId != null) {
                        DiskOfferingVO offering = _diskOfferingDao.findById(diskOfferingId);
                        if (offering != null && (offering.getType() == DiskOfferingVO.Type.Disk)) {
                            offeringId = offering.getId();
                        }
                    }
                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), offeringId, templateId, volume.getSize(), Volume.class.getName(), volume.getUuid(), volume.isDisplayVolume());
                }
            }
            //Update Resource Count for the given account
            resourceCountIncrement(account.getId(), vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
        }
    });
    return _vmDao.findById(vmId);
}
Also used : Account(com.cloud.user.Account) TransactionStatus(com.cloud.utils.db.TransactionStatus) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) DB(com.cloud.utils.db.DB)

Example 9 with ServiceOfferingVO

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

the class UserVmManagerImpl method createVirtualMachine.

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

Example 10 with ServiceOfferingVO

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

the class UserVmManagerImpl method upgradeRunningVirtualMachine.

private boolean upgradeRunningVirtualMachine(Long vmId, Long newServiceOfferingId, Map<String, String> customParameters) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
    Account caller = CallContext.current().getCallingAccount();
    VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
    if (vmInstance.getHypervisorType() != HypervisorType.XenServer && vmInstance.getHypervisorType() != HypervisorType.VMware && vmInstance.getHypervisorType() != HypervisorType.Simulator) {
        s_logger.info("Scaling the VM dynamically is not supported for VMs running on Hypervisor " + vmInstance.getHypervisorType());
        throw new InvalidParameterValueException("Scaling the VM dynamically is not supported for VMs running on Hypervisor " + vmInstance.getHypervisorType());
    }
    _accountMgr.checkAccess(caller, null, true, vmInstance);
    //Check if its a scale "up"
    ServiceOfferingVO newServiceOffering = _offeringDao.findById(newServiceOfferingId);
    if (newServiceOffering.isDynamic()) {
        newServiceOffering.setDynamicFlag(true);
        validateCustomParameters(newServiceOffering, customParameters);
        newServiceOffering = _offeringDao.getcomputeOffering(newServiceOffering, customParameters);
    }
    // Check that the specified service offering ID is valid
    _itMgr.checkIfCanUpgrade(vmInstance, newServiceOffering);
    ServiceOfferingVO currentServiceOffering = _offeringDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId());
    int newCpu = newServiceOffering.getCpu();
    int newMemory = newServiceOffering.getRamSize();
    int newSpeed = newServiceOffering.getSpeed();
    int currentCpu = currentServiceOffering.getCpu();
    int currentMemory = currentServiceOffering.getRamSize();
    int currentSpeed = currentServiceOffering.getSpeed();
    int memoryDiff = newMemory - currentMemory;
    int cpuDiff = newCpu * newSpeed - currentCpu * currentSpeed;
    // Don't allow to scale when (Any of the new values less than current values) OR (All current and new values are same)
    if ((newSpeed < currentSpeed || newMemory < currentMemory || newCpu < currentCpu) || (newSpeed == currentSpeed && newMemory == currentMemory && newCpu == currentCpu)) {
        throw new InvalidParameterValueException("Only scaling up the vm is supported, new service offering(speed=" + newSpeed + ",cpu=" + newCpu + ",memory=," + newMemory + ")" + " should have at least one value(cpu/ram) greater than old value and no resource value less than older(speed=" + currentSpeed + ",cpu=" + currentCpu + ",memory=," + currentMemory + ")");
    }
    _offeringDao.loadDetails(currentServiceOffering);
    _offeringDao.loadDetails(newServiceOffering);
    Map<String, String> currentDetails = currentServiceOffering.getDetails();
    Map<String, String> newDetails = newServiceOffering.getDetails();
    String currentVgpuType = currentDetails.get("vgpuType");
    String newVgpuType = newDetails.get("vgpuType");
    if (currentVgpuType != null) {
        if (newVgpuType == null || !newVgpuType.equalsIgnoreCase(currentVgpuType)) {
            throw new InvalidParameterValueException("Dynamic scaling of vGPU type is not supported. VM has vGPU Type: " + currentVgpuType);
        }
    }
    // Check resource limits
    if (newCpu > currentCpu) {
        _resourceLimitMgr.checkResourceLimit(caller, ResourceType.cpu, newCpu - currentCpu);
    }
    if (newMemory > currentMemory) {
        _resourceLimitMgr.checkResourceLimit(caller, ResourceType.memory, newMemory - currentMemory);
    }
    // Dynamically upgrade the running vms
    boolean success = false;
    if (vmInstance.getState().equals(State.Running)) {
        int retry = _scaleRetry;
        ExcludeList excludes = new ExcludeList();
        // Check zone wide flag
        boolean enableDynamicallyScaleVm = EnableDynamicallyScaleVm.valueIn(vmInstance.getDataCenterId());
        if (!enableDynamicallyScaleVm) {
            throw new PermissionDeniedException("Dynamically scaling virtual machines is disabled for this zone, please contact your admin");
        }
        // Check vm flag
        if (!vmInstance.isDynamicallyScalable()) {
            throw new CloudRuntimeException("Unable to Scale the vm: " + vmInstance.getUuid() + " as vm does not have tools to support dynamic scaling");
        }
        // Check disable threshold for cluster is not crossed
        HostVO host = _hostDao.findById(vmInstance.getHostId());
        if (_capacityMgr.checkIfClusterCrossesThreshold(host.getClusterId(), cpuDiff, memoryDiff)) {
            throw new CloudRuntimeException("Unable to scale vm: " + vmInstance.getUuid() + " due to insufficient resources");
        }
        while (retry-- != 0) {
            // It's != so that it can match -1.
            try {
                boolean existingHostHasCapacity = false;
                // Increment CPU and Memory count accordingly.
                if (newCpu > currentCpu) {
                    _resourceLimitMgr.incrementResourceCount(caller.getAccountId(), ResourceType.cpu, new Long(newCpu - currentCpu));
                }
                if (memoryDiff > 0) {
                    _resourceLimitMgr.incrementResourceCount(caller.getAccountId(), ResourceType.memory, new Long(memoryDiff));
                }
                // #1 Check existing host has capacity
                if (!excludes.shouldAvoid(ApiDBUtils.findHostById(vmInstance.getHostId()))) {
                    existingHostHasCapacity = _capacityMgr.checkIfHostHasCpuCapability(vmInstance.getHostId(), newCpu, newSpeed) && _capacityMgr.checkIfHostHasCapacity(vmInstance.getHostId(), cpuDiff, (memoryDiff) * 1024L * 1024L, false, _capacityMgr.getClusterOverProvisioningFactor(host.getClusterId(), Capacity.CAPACITY_TYPE_CPU), _capacityMgr.getClusterOverProvisioningFactor(host.getClusterId(), Capacity.CAPACITY_TYPE_MEMORY), false);
                    excludes.addHost(vmInstance.getHostId());
                }
                // #2 migrate the vm if host doesn't have capacity or is in avoid set
                if (!existingHostHasCapacity) {
                    _itMgr.findHostAndMigrate(vmInstance.getUuid(), newServiceOfferingId, excludes);
                }
                // #3 scale the vm now
                _itMgr.upgradeVmDb(vmId, newServiceOfferingId);
                if (newServiceOffering.isDynamic()) {
                    //save the custom values to the database.
                    saveCustomOfferingDetails(vmId, newServiceOffering);
                }
                vmInstance = _vmInstanceDao.findById(vmId);
                _itMgr.reConfigureVm(vmInstance.getUuid(), currentServiceOffering, existingHostHasCapacity);
                success = true;
                if (currentServiceOffering.isDynamic() && !newServiceOffering.isDynamic()) {
                    removeCustomOfferingDetails(vmId);
                }
                return success;
            } catch (InsufficientCapacityException e) {
                s_logger.warn("Received exception while scaling ", e);
            } catch (ResourceUnavailableException e) {
                s_logger.warn("Received exception while scaling ", e);
            } catch (ConcurrentOperationException e) {
                s_logger.warn("Received exception while scaling ", e);
            } catch (Exception e) {
                s_logger.warn("Received exception while scaling ", e);
            } finally {
                if (!success) {
                    // rollback
                    _itMgr.upgradeVmDb(vmId, currentServiceOffering.getId());
                    // Decrement CPU and Memory count accordingly.
                    if (newCpu > currentCpu) {
                        _resourceLimitMgr.decrementResourceCount(caller.getAccountId(), ResourceType.cpu, new Long(newCpu - currentCpu));
                    }
                    //restoring old service offering will take care of removing new SO.
                    if (currentServiceOffering.isDynamic()) {
                        saveCustomOfferingDetails(vmId, currentServiceOffering);
                    }
                    if (memoryDiff > 0) {
                        _resourceLimitMgr.decrementResourceCount(caller.getAccountId(), ResourceType.memory, new Long(memoryDiff));
                    }
                }
            }
        }
    }
    return success;
}
Also used : ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) Account(com.cloud.user.Account) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) HostVO(com.cloud.host.HostVO) ExecutionException(com.cloud.utils.exception.ExecutionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) CloudException(com.cloud.exception.CloudException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConfigurationException(javax.naming.ConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException)

Aggregations

ServiceOfferingVO (com.cloud.service.ServiceOfferingVO)72 ArrayList (java.util.ArrayList)24 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)18 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)18 Account (com.cloud.user.Account)17 List (java.util.List)14 Network (com.cloud.network.Network)10 DB (com.cloud.utils.db.DB)10 VolumeVO (com.cloud.storage.VolumeVO)9 NicProfile (com.cloud.vm.NicProfile)9 VMInstanceVO (com.cloud.vm.VMInstanceVO)9 HashMap (java.util.HashMap)9 LinkedHashMap (java.util.LinkedHashMap)9 ConfigurationException (javax.naming.ConfigurationException)9 DataCenterDeployment (com.cloud.deploy.DataCenterDeployment)8 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)8 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)8 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)8 HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)8 DomainRouterVO (com.cloud.vm.DomainRouterVO)8