Search in sources :

Example 71 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class VirtualMachineManagerImpl method reconfigureVmThroughJobQueue.

public Outcome<VirtualMachine> reconfigureVmThroughJobQueue(final String vmUuid, final ServiceOffering newServiceOffering, final boolean reconfiguringOnExistingHost) {
    final CallContext context = CallContext.current();
    final User user = context.getCallingUser();
    final Account account = context.getCallingAccount();
    final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
    final List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vm.getId(), VmWorkReconfigure.class.getName());
    VmWorkJobVO workJob = null;
    if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
        assert pendingWorkJobs.size() == 1;
        workJob = pendingWorkJobs.get(0);
    } else {
        workJob = new VmWorkJobVO(context.getContextId());
        workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
        workJob.setCmd(VmWorkReconfigure.class.getName());
        workJob.setAccountId(account.getId());
        workJob.setUserId(user.getId());
        workJob.setVmType(VirtualMachine.Type.Instance);
        workJob.setVmInstanceId(vm.getId());
        workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
        // save work context info (there are some duplications)
        final VmWorkReconfigure workInfo = new VmWorkReconfigure(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, newServiceOffering.getId(), reconfiguringOnExistingHost);
        workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
        _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
    }
    AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
    return new VmJobVirtualMachineOutcome(workJob, vm.getId());
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) CallContext(org.apache.cloudstack.context.CallContext) VmWorkJobVO(org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)

Example 72 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class VirtualMachineManagerImpl method orchestrateAddVmToNetwork.

private NicProfile orchestrateAddVmToNetwork(final VirtualMachine vm, final Network network, final NicProfile requested) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
    final CallContext cctx = CallContext.current();
    s_logger.debug("Adding vm " + vm + " to network " + network + "; requested nic profile " + requested);
    final VMInstanceVO vmVO = _vmDao.findById(vm.getId());
    final ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
    final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
    final DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
    final Host host = _hostDao.findById(vm.getHostId());
    final DeployDestination dest = new DeployDestination(dc, null, null, host);
    //check vm state
    if (vm.getState() == State.Running) {
        //1) allocate and prepare nic
        final NicProfile nic = _networkMgr.createNicForVm(network, requested, context, vmProfile, true);
        //2) Convert vmProfile to vmTO
        final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
        final VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
        //3) Convert nicProfile to NicTO
        final NicTO nicTO = toNicTO(nic, vmProfile.getVirtualMachine().getHypervisorType());
        //4) plug the nic to the vm
        s_logger.debug("Plugging nic for vm " + vm + " in network " + network);
        boolean result = false;
        try {
            result = plugNic(network, nicTO, vmTO, context, dest);
            if (result) {
                s_logger.debug("Nic is plugged successfully for vm " + vm + " in network " + network + ". Vm  is a part of network now");
                final long isDefault = nic.isDefaultNic() ? 1 : 0;
                // insert nic's Id into DB as resource_name
                if (VirtualMachine.Type.User.equals(vmVO.getType())) {
                    //Log usage event for user Vms only
                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vmVO.getAccountId(), vmVO.getDataCenterId(), vmVO.getId(), Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vmVO.getUuid(), vm.isDisplay());
                }
                return nic;
            } else {
                s_logger.warn("Failed to plug nic to the vm " + vm + " in network " + network);
                return null;
            }
        } finally {
            if (!result) {
                s_logger.debug("Removing nic " + nic + " from vm " + vmProfile.getVirtualMachine() + " as nic plug failed on the backend");
                _networkMgr.removeNic(vmProfile, _nicsDao.findById(nic.getId()));
            }
        }
    } else if (vm.getState() == State.Stopped) {
        //1) allocate nic
        return _networkMgr.createNicForVm(network, requested, context, vmProfile, false);
    } else {
        s_logger.warn("Unable to add vm " + vm + " to network  " + network);
        throw new ResourceUnavailableException("Unable to add vm " + vm + " to network, is not in the right state", DataCenter.class, vm.getDataCenterId());
    }
}
Also used : Host(com.cloud.host.Host) CallContext(org.apache.cloudstack.context.CallContext) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) DataCenter(com.cloud.dc.DataCenter) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) DeployDestination(com.cloud.deploy.DeployDestination) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) NicTO(com.cloud.agent.api.to.NicTO)

Example 73 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class VirtualMachineManagerImpl method addVmToNetworkThroughJobQueue.

public Outcome<VirtualMachine> addVmToNetworkThroughJobQueue(final VirtualMachine vm, final Network network, final NicProfile requested) {
    final CallContext context = CallContext.current();
    final User user = context.getCallingUser();
    final Account account = context.getCallingAccount();
    final List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vm.getId(), VmWorkAddVmToNetwork.class.getName());
    VmWorkJobVO workJob = null;
    if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
        assert pendingWorkJobs.size() == 1;
        workJob = pendingWorkJobs.get(0);
    } else {
        workJob = new VmWorkJobVO(context.getContextId());
        workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
        workJob.setCmd(VmWorkAddVmToNetwork.class.getName());
        workJob.setAccountId(account.getId());
        workJob.setUserId(user.getId());
        workJob.setVmType(VirtualMachine.Type.Instance);
        workJob.setVmInstanceId(vm.getId());
        workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
        // save work context info (there are some duplications)
        final VmWorkAddVmToNetwork workInfo = new VmWorkAddVmToNetwork(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, network.getId(), requested);
        workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
        _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
    }
    AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
    return new VmJobVirtualMachineOutcome(workJob, vm.getId());
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) CallContext(org.apache.cloudstack.context.CallContext) VmWorkJobVO(org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)

Example 74 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class VirtualMachineManagerImpl method orchestrateRemoveVmFromNetwork.

@DB
private boolean orchestrateRemoveVmFromNetwork(final VirtualMachine vm, final Network network, final URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException {
    final CallContext cctx = CallContext.current();
    final VMInstanceVO vmVO = _vmDao.findById(vm.getId());
    final ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
    final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
    final DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
    final Host host = _hostDao.findById(vm.getHostId());
    final DeployDestination dest = new DeployDestination(dc, null, null, host);
    final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
    final VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
    Nic nic = null;
    if (broadcastUri != null) {
        nic = _nicsDao.findByNetworkIdInstanceIdAndBroadcastUri(network.getId(), vm.getId(), broadcastUri.toString());
    } else {
        nic = _networkModel.getNicInNetwork(vm.getId(), network.getId());
    }
    if (nic == null) {
        s_logger.warn("Could not get a nic with " + network);
        return false;
    }
    // don't delete default NIC on a user VM
    if (nic.isDefaultNic() && vm.getType() == VirtualMachine.Type.User) {
        s_logger.warn("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
        throw new CloudRuntimeException("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
    }
    //Lock on nic is needed here
    final Nic lock = _nicsDao.acquireInLockTable(nic.getId());
    if (lock == null) {
        //check if nic is still there. Return if it was released already
        if (_nicsDao.findById(nic.getId()) == null) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Not need to remove the vm " + vm + " from network " + network + " as the vm doesn't have nic in this network");
            }
            return true;
        }
        throw new ConcurrentOperationException("Unable to lock nic " + nic.getId());
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Lock is acquired for nic id " + lock.getId() + " as a part of remove vm " + vm + " from network " + network);
    }
    try {
        final NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(network.getId(), vm.getId()), _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network));
        //1) Unplug the nic
        if (vm.getState() == State.Running) {
            final NicTO nicTO = toNicTO(nicProfile, vmProfile.getVirtualMachine().getHypervisorType());
            s_logger.debug("Un-plugging nic for vm " + vm + " from network " + network);
            final boolean result = unplugNic(network, nicTO, vmTO, context, dest);
            if (result) {
                s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network);
            } else {
                s_logger.warn("Failed to unplug nic for the vm " + vm + " from network " + network);
                return false;
            }
        } else if (vm.getState() != State.Stopped) {
            s_logger.warn("Unable to remove vm " + vm + " from network  " + network);
            throw new ResourceUnavailableException("Unable to remove vm " + vm + " from network, is not in the right state", DataCenter.class, vm.getDataCenterId());
        }
        //2) Release the nic
        _networkMgr.releaseNic(vmProfile, nic);
        s_logger.debug("Successfully released nic " + nic + "for vm " + vm);
        //3) Remove the nic
        _networkMgr.removeNic(vmProfile, nic);
        return true;
    } finally {
        if (lock != null) {
            _nicsDao.releaseFromLockTable(lock.getId());
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Lock is released for nic id " + lock.getId() + " as a part of remove vm " + vm + " from network " + network);
            }
        }
    }
}
Also used : Host(com.cloud.host.Host) CallContext(org.apache.cloudstack.context.CallContext) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) DataCenter(com.cloud.dc.DataCenter) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) DeployDestination(com.cloud.deploy.DeployDestination) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) NicTO(com.cloud.agent.api.to.NicTO) DB(com.cloud.utils.db.DB)

Example 75 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class VirtualMachineManagerImpl method removeNicFromVmThroughJobQueue.

public Outcome<VirtualMachine> removeNicFromVmThroughJobQueue(final VirtualMachine vm, final Nic nic) {
    final CallContext context = CallContext.current();
    final User user = context.getCallingUser();
    final Account account = context.getCallingAccount();
    final List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vm.getId(), VmWorkRemoveNicFromVm.class.getName());
    VmWorkJobVO workJob = null;
    if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
        assert pendingWorkJobs.size() == 1;
        workJob = pendingWorkJobs.get(0);
    } else {
        workJob = new VmWorkJobVO(context.getContextId());
        workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
        workJob.setCmd(VmWorkRemoveNicFromVm.class.getName());
        workJob.setAccountId(account.getId());
        workJob.setUserId(user.getId());
        workJob.setVmType(VirtualMachine.Type.Instance);
        workJob.setVmInstanceId(vm.getId());
        workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
        // save work context info (there are some duplications)
        final VmWorkRemoveNicFromVm workInfo = new VmWorkRemoveNicFromVm(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, nic.getId());
        workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
        _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
    }
    AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
    return new VmJobVirtualMachineOutcome(workJob, vm.getId());
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) CallContext(org.apache.cloudstack.context.CallContext) VmWorkJobVO(org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)

Aggregations

CallContext (org.apache.cloudstack.context.CallContext)76 Account (com.cloud.user.Account)45 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)29 User (com.cloud.user.User)26 ActionEvent (com.cloud.event.ActionEvent)22 VmWorkJobVO (org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)22 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)21 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)21 DB (com.cloud.utils.db.DB)13 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)12 VMInstanceVO (com.cloud.vm.VMInstanceVO)10 FirewallRule (com.cloud.network.rules.FirewallRule)8 ArrayList (java.util.ArrayList)8 ServerApiException (org.apache.cloudstack.api.ServerApiException)8 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)7 Network (com.cloud.network.Network)7 TransactionStatus (com.cloud.utils.db.TransactionStatus)6 DeployDestination (com.cloud.deploy.DeployDestination)5 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)5 IPAddressVO (com.cloud.network.dao.IPAddressVO)5