Search in sources :

Example 1 with VirtualMachineEntity

use of org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity in project cloudstack by apache.

the class UserVmManagerImpl method startVirtualMachine.

@Override
public Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> startVirtualMachine(long vmId, Long hostId, Map<VirtualMachineProfile.Param, Object> additionalParams, String deploymentPlannerToUse) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
    // Input validation
    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);
    }
    _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());
    }
    Host destinationHost = null;
    if (hostId != null) {
        Account account = CallContext.current().getCallingAccount();
        if (!_accountService.isRootAdmin(account.getId())) {
            throw new PermissionDeniedException("Parameter hostid can only be specified by a Root Admin, permission denied");
        }
        destinationHost = _hostDao.findById(hostId);
        if (destinationHost == null) {
            throw new InvalidParameterValueException("Unable to find the host to deploy the VM, host id=" + hostId);
        }
    }
    // 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);
        }
    }
    DataCenterDeployment plan = null;
    if (destinationHost != null) {
        s_logger.debug("Destination Host to deploy the VM is specified, specifying a deployment plan to deploy the VM");
        plan = new DataCenterDeployment(vm.getDataCenterId(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null, null);
    }
    // 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.getEnablePassword()) {
            if (vm.getDetail("password") != null) {
                password = DBEncryptionUtil.decrypt(vm.getDetail("password"));
            } else {
                password = _mgr.generateRandomPassword();
            }
        }
        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 = new HashMap<VirtualMachineProfile.Param, Object>();
        if (additionalParams != null) {
            params.putAll(additionalParams);
        }
        params.put(VirtualMachineProfile.Param.VmPassword, password);
    }
    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);
        }
    }
    String reservationId = vmEntity.reserve(planner, plan, new ExcludeList(), Long.toString(callerUser.getId()));
    vmEntity.deploy(reservationId, Long.toString(callerUser.getId()), params);
    Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> vmParamPair = new Pair(vm, params);
    if (vm != null && vm.isUpdateParameters()) {
        // display purposes
        if (template.getEnablePassword()) {
            vm.setPassword((String) vmParamPair.second().get(VirtualMachineProfile.Param.VmPassword));
            vm.setUpdateParameters(false);
            if (vm.getDetail("password") != null) {
                _vmDetailsDao.remove(_vmDetailsDao.findDetail(vm.getId(), "password").getId());
            }
            _vmDao.update(vm.getId(), vm);
        }
    }
    return vmParamPair;
}
Also used : ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) Account(com.cloud.user.Account) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) VirtualMachineEntity(org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity) ArrayList(java.util.ArrayList) VMTemplateVO(com.cloud.storage.VMTemplateVO) Host(com.cloud.host.Host) SecurityGroup(com.cloud.network.security.SecurityGroup) UserVO(com.cloud.user.UserVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) 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) Pair(com.cloud.utils.Pair) SSHKeyPair(com.cloud.user.SSHKeyPair)

Example 2 with VirtualMachineEntity

use of org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity in project cloudstack by apache.

the class UserVmManagerImpl method stopVirtualMachine.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_STOP, eventDescription = "stopping Vm", async = true)
public UserVm stopVirtualMachine(long vmId, boolean forced) throws ConcurrentOperationException {
    // Input validation
    Account caller = CallContext.current().getCallingAccount();
    Long userId = CallContext.current().getCallingUserId();
    // if account is removed, return error
    if (caller != null && caller.getRemoved() != null) {
        throw new PermissionDeniedException("The account " + caller.getUuid() + " is removed");
    }
    UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
    }
    statsCollector.removeVirtualMachineStats(vmId);
    _userDao.findById(userId);
    boolean status = false;
    try {
        VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
        if (forced) {
            status = vmEntity.stopForced(Long.toString(userId));
        } else {
            status = vmEntity.stop(Long.toString(userId));
        }
        if (status) {
            return _vmDao.findById(vmId);
        } else {
            return null;
        }
    } catch (ResourceUnavailableException e) {
        throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e);
    } catch (CloudException e) {
        throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e);
    }
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualMachineEntity(org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) CloudException(com.cloud.exception.CloudException) ActionEvent(com.cloud.event.ActionEvent)

Example 3 with VirtualMachineEntity

use of org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity in project cloudstack by apache.

the class UserVmManagerImpl method stopVirtualMachine.

@Override
public boolean stopVirtualMachine(long userId, long vmId) {
    boolean status = false;
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Stopping vm=" + vmId);
    }
    UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null || vm.getRemoved() != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("VM is either removed or deleted.");
        }
        return true;
    }
    _userDao.findById(userId);
    try {
        VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
        status = vmEntity.stop(Long.toString(userId));
    } catch (ResourceUnavailableException e) {
        s_logger.debug("Unable to stop due to ", e);
        status = false;
    } catch (CloudException e) {
        throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e);
    }
    return status;
}
Also used : CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualMachineEntity(org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudException(com.cloud.exception.CloudException)

Example 4 with VirtualMachineEntity

use of org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity 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 5 with VirtualMachineEntity

use of org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity in project cloudstack by apache.

the class UserVmManagerImpl method destroyVm.

@Override
public UserVm destroyVm(long vmId, boolean expunge) throws ResourceUnavailableException, ConcurrentOperationException {
    // Account caller = CallContext.current().getCallingAccount();
    // Long userId = CallContext.current().getCallingUserId();
    Long userId = 2L;
    // Verify input parameters
    UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null || vm.getRemoved() != null) {
        InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a virtual machine with specified vmId");
        throw ex;
    }
    if (vm.getState() == State.Destroyed || vm.getState() == State.Expunging) {
        s_logger.trace("Vm id=" + vmId + " is already destroyed");
        return vm;
    }
    statsCollector.removeVirtualMachineStats(vmId);
    boolean status;
    State vmState = vm.getState();
    try {
        VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
        status = vmEntity.destroy(Long.toString(userId), expunge);
    } catch (CloudException e) {
        CloudRuntimeException ex = new CloudRuntimeException("Unable to destroy with specified vmId", e);
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    if (status) {
        // Mark the account's volumes as destroyed
        List<VolumeVO> volumes = _volsDao.findByInstance(vmId);
        for (VolumeVO volume : volumes) {
            if (volume.getVolumeType().equals(Volume.Type.ROOT)) {
                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), Volume.class.getName(), volume.getUuid(), volume.isDisplayVolume());
            }
        }
        if (vmState != State.Error) {
            // Get serviceOffering for Virtual Machine
            ServiceOfferingVO offering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId());
            // Update Resource Count for the given account
            resourceCountDecrement(vm.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
        }
        return _vmDao.findById(vmId);
    } else {
        CloudRuntimeException ex = new CloudRuntimeException("Failed to destroy vm with specified vmId");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
}
Also used : VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Volume(com.cloud.storage.Volume) ResourceState(com.cloud.resource.ResourceState) State(com.cloud.vm.VirtualMachine.State) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualMachineEntity(org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity) CloudException(com.cloud.exception.CloudException) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO)

Aggregations

VirtualMachineEntity (org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity)6 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)4 CloudException (com.cloud.exception.CloudException)3 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)3 ServiceOfferingVO (com.cloud.service.ServiceOfferingVO)3 Account (com.cloud.user.Account)3 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)3 ArrayList (java.util.ArrayList)3 DataCenterDeployment (com.cloud.deploy.DataCenterDeployment)2 DeploymentPlanner (com.cloud.deploy.DeploymentPlanner)2 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)2 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)2 Host (com.cloud.host.Host)2 SecurityGroup (com.cloud.network.security.SecurityGroup)2 VMTemplateVO (com.cloud.storage.VMTemplateVO)2 VolumeVO (com.cloud.storage.VolumeVO)2 SSHKeyPair (com.cloud.user.SSHKeyPair)2 UserVO (com.cloud.user.UserVO)2 Pair (com.cloud.utils.Pair)2 HashMap (java.util.HashMap)2