Search in sources :

Example 36 with State

use of com.cloud.vm.VirtualMachine.State in project cloudstack by apache.

the class DeploymentPlanningManagerImpl method postStateTransitionEvent.

@Override
public boolean postStateTransitionEvent(StateMachine2.Transition<State, Event> transition, VirtualMachine vo, boolean status, Object opaque) {
    if (!status) {
        return false;
    }
    State oldState = transition.getCurrentState();
    State newState = transition.getToState();
    if ((oldState == State.Starting) && (newState != State.Starting)) {
        // cleanup all VM reservation entries
        SearchCriteria<VMReservationVO> sc = _reservationDao.createSearchCriteria();
        sc.addAnd("vmId", SearchCriteria.Op.EQ, vo.getId());
        _reservationDao.expunge(sc);
    }
    return true;
}
Also used : VMReservationVO(org.apache.cloudstack.engine.cloud.entity.api.db.VMReservationVO) ResourceState(com.cloud.resource.ResourceState) State(com.cloud.vm.VirtualMachine.State)

Example 37 with State

use of com.cloud.vm.VirtualMachine.State in project cloudstack by apache.

the class SecurityGroupManagerImpl method postStateTransitionEvent.

@Override
public boolean postStateTransitionEvent(StateMachine2.Transition<State, Event> transition, VirtualMachine vm, boolean status, Object opaque) {
    if (!status) {
        return false;
    }
    State oldState = transition.getCurrentState();
    State newState = transition.getToState();
    Event event = transition.getEvent();
    if (VirtualMachine.State.isVmStarted(oldState, event, newState)) {
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("Security Group Mgr: handling start of vm id" + vm.getId());
        }
        handleVmStarted((VMInstanceVO) vm);
    } else if (VirtualMachine.State.isVmStopped(oldState, event, newState)) {
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("Security Group Mgr: handling stop of vm id" + vm.getId());
        }
        handleVmStopped((VMInstanceVO) vm);
    } else if (VirtualMachine.State.isVmMigrated(oldState, event, newState)) {
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("Security Group Mgr: handling migration of vm id" + vm.getId());
        }
        handleVmMigrated((VMInstanceVO) vm);
    }
    return true;
}
Also used : State(com.cloud.vm.VirtualMachine.State) Event(com.cloud.vm.VirtualMachine.Event) ActionEvent(com.cloud.event.ActionEvent) VMInstanceVO(com.cloud.vm.VMInstanceVO)

Example 38 with State

use of com.cloud.vm.VirtualMachine.State 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;
    }
    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)

Example 39 with State

use of com.cloud.vm.VirtualMachine.State in project cloudstack by apache.

the class LoadBalanceRuleHandler method deployELBVm.

private DomainRouterVO deployELBVm(Network guestNetwork, final DeployDestination dest, Account owner, final Map<Param, Object> params) throws ConcurrentOperationException, InsufficientCapacityException {
    final long dcId = dest.getDataCenter().getId();
    // lock guest network
    final Long guestNetworkId = guestNetwork.getId();
    guestNetwork = _networkDao.acquireInLockTable(guestNetworkId);
    if (guestNetwork == null) {
        throw new ConcurrentOperationException("Unable to acquire network lock: " + guestNetworkId);
    }
    try {
        if (_networkModel.isNetworkSystem(guestNetwork) || guestNetwork.getGuestType() == Network.GuestType.Shared) {
            owner = _accountService.getSystemAccount();
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Starting a ELB vm for network configurations: " + guestNetwork + " in " + dest);
        }
        assert guestNetwork.getState() == Network.State.Implemented || guestNetwork.getState() == Network.State.Setup || guestNetwork.getState() == Network.State.Implementing : "Network is not yet fully implemented: " + guestNetwork;
        DataCenterDeployment plan = null;
        DomainRouterVO elbVm = null;
        plan = new DataCenterDeployment(dcId, dest.getPod().getId(), null, null, null, null);
        if (elbVm == null) {
            final long id = _routerDao.getNextInSequence(Long.class, "id");
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Creating the ELB vm " + id);
            }
            final List<? extends NetworkOffering> offerings = _networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork);
            final NetworkOffering controlOffering = offerings.get(0);
            final Network controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0);
            final LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>(2);
            final NicProfile guestNic = new NicProfile();
            guestNic.setDefaultNic(true);
            networks.put(controlConfig, new ArrayList<NicProfile>());
            networks.put(guestNetwork, new ArrayList<NicProfile>(Arrays.asList(guestNic)));
            final VMTemplateVO template = _templateDao.findSystemVMTemplate(dcId);
            final String typeString = "ElasticLoadBalancerVm";
            final Long physicalNetworkId = _networkModel.getPhysicalNetworkId(guestNetwork);
            final PhysicalNetworkServiceProvider provider = _physicalProviderDao.findByServiceProvider(physicalNetworkId, typeString);
            if (provider == null) {
                throw new CloudRuntimeException("Cannot find service provider " + typeString + " in physical network " + physicalNetworkId);
            }
            final VirtualRouterProvider vrProvider = _vrProviderDao.findByNspIdAndType(provider.getId(), Type.ElasticLoadBalancerVm);
            if (vrProvider == null) {
                throw new CloudRuntimeException("Cannot find virtual router provider " + typeString + " as service provider " + provider.getId());
            }
            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();
                }
            }
            ServiceOfferingVO elasticLbVmOffering = _serviceOfferingDao.findDefaultSystemOffering(ServiceOffering.elbVmDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dest.getDataCenter().getId()));
            elbVm = new DomainRouterVO(id, elasticLbVmOffering.getId(), vrProvider.getId(), VirtualMachineName.getSystemVmName(id, _instance, ELB_VM_NAME_PREFIX), template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, false, RedundantState.UNKNOWN, elasticLbVmOffering.getOfferHA(), false, null);
            elbVm.setRole(Role.LB);
            elbVm = _routerDao.persist(elbVm);
            _itMgr.allocate(elbVm.getInstanceName(), template, elasticLbVmOffering, networks, plan, null);
            elbVm = _routerDao.findById(elbVm.getId());
        //TODO: create usage stats
        }
        final State state = elbVm.getState();
        if (state != State.Running) {
            elbVm = start(elbVm, params);
        }
        return elbVm;
    } finally {
        _networkDao.releaseFromLockTable(guestNetworkId);
    }
}
Also used : DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) NetworkOffering(com.cloud.offering.NetworkOffering) VMTemplateVO(com.cloud.storage.VMTemplateVO) PhysicalNetworkServiceProvider(com.cloud.network.PhysicalNetworkServiceProvider) NicProfile(com.cloud.vm.NicProfile) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) LinkedHashMap(java.util.LinkedHashMap) UserVO(com.cloud.user.UserVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualRouterProvider(com.cloud.network.VirtualRouterProvider) State(com.cloud.vm.VirtualMachine.State) RedundantState(com.cloud.network.router.VirtualRouter.RedundantState) Network(com.cloud.network.Network) List(java.util.List) ArrayList(java.util.ArrayList) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 40 with State

use of com.cloud.vm.VirtualMachine.State in project cloudstack by apache.

the class TemplateManagerImpl method attachIso.

@Override
@ActionEvent(eventType = EventTypes.EVENT_ISO_ATTACH, eventDescription = "attaching ISO", async = true)
public boolean attachIso(long isoId, long vmId) {
    Account caller = CallContext.current().getCallingAccount();
    Long userId = CallContext.current().getCallingUserId();
    // Verify input parameters
    UserVmVO vm = _userVmDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
    }
    VMTemplateVO iso = _tmpltDao.findById(isoId);
    if (iso == null || iso.getRemoved() != null) {
        throw new InvalidParameterValueException("Unable to find an ISO with id " + isoId);
    }
    // check permissions
    // check if caller has access to VM and ISO
    // and also check if the VM's owner has access to the ISO.
    _accountMgr.checkAccess(caller, null, false, iso, vm);
    Account vmOwner = _accountDao.findById(vm.getAccountId());
    _accountMgr.checkAccess(vmOwner, null, false, iso, vm);
    State vmState = vm.getState();
    if (vmState != State.Running && vmState != State.Stopped) {
        throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
    }
    if ("xen-pv-drv-iso".equals(iso.getDisplayText()) && vm.getHypervisorType() != Hypervisor.HypervisorType.XenServer) {
        throw new InvalidParameterValueException("Cannot attach Xenserver PV drivers to incompatible hypervisor " + vm.getHypervisorType());
    }
    if ("vmware-tools.iso".equals(iso.getName()) && vm.getHypervisorType() != Hypervisor.HypervisorType.VMware) {
        throw new InvalidParameterValueException("Cannot attach VMware tools drivers to incompatible hypervisor " + vm.getHypervisorType());
    }
    boolean result = attachISOToVM(vmId, userId, isoId, true);
    if (result) {
        return result;
    } else {
        throw new CloudRuntimeException("Failed to attach iso");
    }
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) State(com.cloud.vm.VirtualMachine.State) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VMTemplateVO(com.cloud.storage.VMTemplateVO) ActionEvent(com.cloud.event.ActionEvent)

Aggregations

State (com.cloud.vm.VirtualMachine.State)45 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)14 ConfigurationException (javax.naming.ConfigurationException)11 HashMap (java.util.HashMap)9 PowerState (com.cloud.vm.VirtualMachine.PowerState)8 LibvirtException (org.libvirt.LibvirtException)8 CheckVirtualMachineAnswer (com.cloud.agent.api.CheckVirtualMachineAnswer)7 StartAnswer (com.cloud.agent.api.StartAnswer)7 StopAnswer (com.cloud.agent.api.StopAnswer)7 Map (java.util.Map)7 Connect (org.libvirt.Connect)7 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)5 Ovm3ResourceException (com.cloud.hypervisor.ovm3.objects.Ovm3ResourceException)5 FileNotFoundException (java.io.FileNotFoundException)5 IOException (java.io.IOException)5 VmState (com.cloud.agent.api.StartupRoutingCommand.VmState)4 VirtualMachineTO (com.cloud.agent.api.to.VirtualMachineTO)4 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)4 Answer (com.cloud.agent.api.Answer)3 NicTO (com.cloud.agent.api.to.NicTO)3