Search in sources :

Example 71 with ServiceOffering

use of com.cloud.offering.ServiceOffering in project cosmic by MissionCriticalCloud.

the class UserConcentratedAllocator method calcHostAllocatedCpuMemoryCapacity.

/**
 * @param hostId       Host id to calculate against
 * @param capacityType CapacityVO.CAPACITY_TYPE_MEMORY or
 *                     CapacityVO.CAPACITY_TYPE_CPU
 * @return
 */
private long calcHostAllocatedCpuMemoryCapacity(final long hostId, final short capacityType) {
    assert (capacityType == Capacity.CAPACITY_TYPE_MEMORY || capacityType == Capacity.CAPACITY_TYPE_CPU) : "Invalid capacity type passed in calcHostAllocatedCpuCapacity()";
    // List<VMInstanceVO> vms = _vmInstanceDao.listByLastHostId(hostId);
    final List<VMInstanceVO> vms = null;
    long usedCapacity = 0;
    if (vms != null) {
        for (final VMInstanceVO vm : vms) {
            if (skipCalculation(vm)) {
                continue;
            }
            final ServiceOffering so;
            if (vm.getType() == VirtualMachine.Type.User) {
                final UserVmVO userVm = _vmDao.findById(vm.getId());
                if (userVm == null) {
                    continue;
                }
            }
            so = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId());
            if (capacityType == Capacity.CAPACITY_TYPE_MEMORY) {
                usedCapacity += so.getRamSize() * 1024L * 1024L;
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Counting memory capacity used by vm: " + vm.getId() + ", size: " + so.getRamSize() + "MB, host: " + hostId + ", currently counted: " + usedCapacity + " Bytes");
                }
            } else if (capacityType == Capacity.CAPACITY_TYPE_CPU) {
                usedCapacity += so.getCpu();
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Counting cpu capacity used by vm: " + vm.getId() + ", cpu: " + so.getCpu() + ", currently counted: " + usedCapacity + " Bytes");
                }
            }
        }
    }
    return usedCapacity;
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) ServiceOffering(com.cloud.offering.ServiceOffering) VMInstanceVO(com.cloud.vm.VMInstanceVO)

Example 72 with ServiceOffering

use of com.cloud.offering.ServiceOffering in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method upgradeRunningVirtualMachine.

private boolean upgradeRunningVirtualMachine(final Long vmId, final Long newServiceOfferingId, final Map<String, String> customParameters) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
    final Account caller = CallContext.current().getCallingAccount();
    VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
    if (vmInstance.getHypervisorType() != HypervisorType.XenServer) {
        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);
    // Check that the specified service offering ID is valid
    _itMgr.checkIfCanUpgrade(vmInstance, newServiceOffering);
    final ServiceOffering currentServiceOffering = _offeringDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId());
    final int newCpu = newServiceOffering.getCpu();
    final int newMemory = newServiceOffering.getRamSize();
    final int currentCpu = currentServiceOffering.getCpu();
    final int currentMemory = currentServiceOffering.getRamSize();
    final int memoryDiff = newMemory - currentMemory;
    final int cpuDiff = newCpu - currentCpu;
    // Don't allow to scale when (Any of the new values less than current values) OR (All current and new values are same)
    if (newMemory < currentMemory || newCpu < currentCpu || newMemory == currentMemory && newCpu == currentCpu) {
        throw new InvalidParameterValueException("Only scaling up the vm is supported, new service offering(cpu=" + newCpu + ",memory=," + newMemory + ")" + " should have at least one value(cpu/ram) greater than old value and no resource value less than older(cpu=" + currentCpu + ",memory=," + currentMemory + ")");
    }
    // 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;
        final ExcludeList excludes = new ExcludeList();
        // Check zone wide flag
        final 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
        final 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) && _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);
                vmInstance = _vmInstanceDao.findById(vmId);
                _itMgr.reConfigureVm(vmInstance.getUuid(), currentServiceOffering, existingHostHasCapacity);
                success = true;
                return success;
            } catch (final InsufficientCapacityException e) {
                s_logger.warn("Received exception while scaling ", e);
            } catch (final ResourceUnavailableException e) {
                s_logger.warn("Received exception while scaling ", e);
            } catch (final ConcurrentOperationException e) {
                s_logger.warn("Received exception while scaling ", e);
            } catch (final 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));
                    }
                    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) ServiceOffering(com.cloud.offering.ServiceOffering) 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) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException)

Example 73 with ServiceOffering

use of com.cloud.offering.ServiceOffering in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method upgradeStoppedVirtualMachine.

private UserVm upgradeStoppedVirtualMachine(final Long vmId, final Long svcOffId, final Map<String, String> customParameters) throws ResourceAllocationException {
    final Account caller = CallContext.current().getCallingAccount();
    // Verify input parameters
    // UserVmVO vmInstance = _vmDao.findById(vmId);
    final VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
    if (vmInstance == null) {
        throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
    }
    _accountMgr.checkAccess(caller, null, true, vmInstance);
    // Check resource limits for CPU and Memory.
    ServiceOfferingVO newServiceOffering = _offeringDao.findById(svcOffId);
    final ServiceOfferingVO currentServiceOffering = _offeringDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId());
    final int newCpu = newServiceOffering.getCpu();
    final int newMemory = newServiceOffering.getRamSize();
    final int currentCpu = currentServiceOffering.getCpu();
    final int currentMemory = currentServiceOffering.getRamSize();
    if (newCpu > currentCpu) {
        _resourceLimitMgr.checkResourceLimit(caller, ResourceType.cpu, newCpu - currentCpu);
    }
    if (newMemory > currentMemory) {
        _resourceLimitMgr.checkResourceLimit(caller, ResourceType.memory, newMemory - currentMemory);
    }
    // Check that the specified service offering ID is valid
    _itMgr.checkIfCanUpgrade(vmInstance, newServiceOffering);
    // Check if the new service offering can be applied to vm instance
    final ServiceOffering newSvcOffering = _offeringDao.findById(svcOffId);
    final Account owner = _accountMgr.getActiveAccountById(vmInstance.getAccountId());
    _accountMgr.checkAccess(owner, newSvcOffering);
    _itMgr.upgradeVmDb(vmId, svcOffId);
    // Increment or decrement CPU and Memory count accordingly.
    if (newCpu > currentCpu) {
        _resourceLimitMgr.incrementResourceCount(caller.getAccountId(), ResourceType.cpu, new Long(newCpu - currentCpu));
    } else if (currentCpu > newCpu) {
        _resourceLimitMgr.decrementResourceCount(caller.getAccountId(), ResourceType.cpu, new Long(currentCpu - newCpu));
    }
    if (newMemory > currentMemory) {
        _resourceLimitMgr.incrementResourceCount(caller.getAccountId(), ResourceType.memory, new Long(newMemory - currentMemory));
    } else if (currentMemory > newMemory) {
        _resourceLimitMgr.decrementResourceCount(caller.getAccountId(), ResourceType.memory, new Long(currentMemory - newMemory));
    }
    return _vmDao.findById(vmInstance.getId());
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ServiceOffering(com.cloud.offering.ServiceOffering) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO)

Example 74 with ServiceOffering

use of com.cloud.offering.ServiceOffering in project cosmic by MissionCriticalCloud.

the class UserVmManagerTest method testScaleVMF4.

// Test scaleVm for Running vm. Full positive test.
public void testScaleVMF4() throws Exception {
    final ScaleVMCmd cmd = new ScaleVMCmd();
    final Class<?> _class = cmd.getClass();
    final Field idField = _class.getDeclaredField("id");
    idField.setAccessible(true);
    idField.set(cmd, 1L);
    final Field serviceOfferingIdField = _class.getDeclaredField("serviceOfferingId");
    serviceOfferingIdField.setAccessible(true);
    serviceOfferingIdField.set(cmd, 1L);
    // UserContext.current().setEventDetails("Vm Id: "+getId());
    // Account account = (Account) new AccountVO("testaccount", 1L, "networkdomain", (short) 0, 1);
    // AccountVO(String accountName, long domainId, String networkDomain, short type, int regionId)
    // UserContext.registerContext(1, account, null, true);
    when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
    doReturn(Hypervisor.HypervisorType.XenServer).when(_vmInstance).getHypervisorType();
    final ServiceOffering so1 = getSvcoffering(512);
    final ServiceOffering so2 = getSvcoffering(256);
    when(_entityMgr.findById(eq(ServiceOffering.class), anyLong())).thenReturn(so2);
    when(_entityMgr.findById(ServiceOffering.class, 1L)).thenReturn(so1);
    doReturn(VirtualMachine.State.Running).when(_vmInstance).getState();
    // when(ApiDBUtils.getCpuOverprovisioningFactor()).thenReturn(3f);
    when(_capacityMgr.checkIfHostHasCapacity(anyLong(), anyInt(), anyLong(), anyBoolean(), anyFloat(), anyFloat(), anyBoolean())).thenReturn(false);
    when(_itMgr.reConfigureVm(_vmInstance.getUuid(), so1, false)).thenReturn(_vmInstance);
    doReturn(true).when(_itMgr).upgradeVmDb(anyLong(), anyLong());
    when(_vmDao.findById(anyLong())).thenReturn(_vmMock);
    final Account account = new AccountVO("testaccount", 1L, "networkdomain", (short) 0, UUID.randomUUID().toString());
    final UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN);
    CallContext.register(user, account);
    try {
        _userVmMgr.upgradeVirtualMachine(cmd);
    } finally {
        CallContext.unregister();
    }
}
Also used : Field(java.lang.reflect.Field) Account(com.cloud.user.Account) UserVO(com.cloud.user.UserVO) ServiceOffering(com.cloud.offering.ServiceOffering) ScaleVMCmd(com.cloud.api.command.user.vm.ScaleVMCmd) AccountVO(com.cloud.user.AccountVO)

Example 75 with ServiceOffering

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

the class VolumeOrchestrator method createVolumeOnPrimaryStorage.

@Override
public VolumeInfo createVolumeOnPrimaryStorage(VirtualMachine vm, VolumeInfo volume, HypervisorType rootDiskHyperType, StoragePool storagePool) throws NoTransitionException {
    VirtualMachineTemplate rootDiskTmplt = _entityMgr.findById(VirtualMachineTemplate.class, vm.getTemplateId());
    DataCenter dcVO = _entityMgr.findById(DataCenter.class, vm.getDataCenterId());
    Long podId = storagePool.getPodId() != null ? storagePool.getPodId() : vm.getPodIdToDeployIn();
    Pod pod = _entityMgr.findById(Pod.class, podId);
    ServiceOffering svo = _entityMgr.findById(ServiceOffering.class, vm.getServiceOfferingId());
    DiskOffering diskVO = _entityMgr.findById(DiskOffering.class, volume.getDiskOfferingId());
    Long clusterId = storagePool.getClusterId();
    VolumeInfo vol = null;
    if (volume.getState() == Volume.State.Allocated) {
        vol = createVolume(volume, vm, rootDiskTmplt, dcVO, pod, clusterId, svo, diskVO, new ArrayList<StoragePool>(), volume.getSize(), rootDiskHyperType);
    } else if (volume.getState() == Volume.State.Uploaded) {
        vol = copyVolume(storagePool, volume, vm, rootDiskTmplt, dcVO, pod, diskVO, svo, rootDiskHyperType);
        if (vol != null) {
            // Moving of Volume is successful, decrement the volume resource count from secondary for an account and increment it into primary storage under same account.
            _resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.secondary_storage, volume.getSize());
            _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, volume.getSize());
        }
    }
    if (vol == null) {
        throw new CloudRuntimeException("Volume shouldn't be null " + volume.getId());
    }
    VolumeVO volVO = _volsDao.findById(vol.getId());
    if (volVO.getFormat() == null) {
        volVO.setFormat(getSupportedImageFormatForCluster(rootDiskHyperType));
    }
    _volsDao.update(volVO.getId(), volVO);
    return volFactory.getVolume(volVO.getId());
}
Also used : DataCenter(com.cloud.dc.DataCenter) DiskOffering(com.cloud.offering.DiskOffering) VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) Pod(com.cloud.dc.Pod) VolumeVO(com.cloud.storage.VolumeVO) ServiceOffering(com.cloud.offering.ServiceOffering) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ArrayList(java.util.ArrayList) VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo)

Aggregations

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