Search in sources :

Example 1 with CallContext

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

the class VolumeApiServiceImpl method migrateVolumeThroughJobQueue.

public Outcome<Volume> migrateVolumeThroughJobQueue(final Long vmId, final long volumeId, final long destPoolId, final boolean liveMigrate) {
    final CallContext context = CallContext.current();
    final User callingUser = context.getCallingUser();
    final Account callingAccount = context.getCallingAccount();
    final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
    VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
    workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
    workJob.setCmd(VmWorkMigrateVolume.class.getName());
    workJob.setAccountId(callingAccount.getId());
    workJob.setUserId(callingUser.getId());
    workJob.setStep(VmWorkJobVO.Step.Starting);
    workJob.setVmType(VirtualMachine.Type.Instance);
    workJob.setVmInstanceId(vm.getId());
    workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
    // save work context info (there are some duplications)
    VmWorkMigrateVolume workInfo = new VmWorkMigrateVolume(callingUser.getId(), callingAccount.getId(), vm.getId(), VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, destPoolId, liveMigrate);
    workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
    _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
    AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
    return new VmJobVolumeOutcome(workJob, volumeId);
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) VMInstanceVO(com.cloud.vm.VMInstanceVO) VmWorkMigrateVolume(com.cloud.vm.VmWorkMigrateVolume) CallContext(org.apache.cloudstack.context.CallContext) VmWorkJobVO(org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)

Example 2 with CallContext

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

the class ProjectManagerImpl method deleteProject.

@Override
@ActionEvent(eventType = EventTypes.EVENT_PROJECT_DELETE, eventDescription = "deleting project", async = true)
public boolean deleteProject(long projectId) {
    CallContext ctx = CallContext.current();
    ProjectVO project = getProject(projectId);
    //verify input parameters
    if (project == null) {
        throw new InvalidParameterValueException("Unable to find project by id " + projectId);
    }
    _accountMgr.checkAccess(ctx.getCallingAccount(), AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId()));
    return deleteProject(ctx.getCallingAccount(), ctx.getCallingUserId(), project);
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CallContext(org.apache.cloudstack.context.CallContext) ActionEvent(com.cloud.event.ActionEvent)

Example 3 with CallContext

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

the class LoadBalancingRulesManagerImpl method assignToLoadBalancer.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_ASSIGN_TO_LOAD_BALANCER_RULE, eventDescription = "assigning to load balancer", async = true)
public boolean assignToLoadBalancer(long loadBalancerId, List<Long> instanceIds, Map<Long, List<String>> vmIdIpMap) {
    CallContext ctx = CallContext.current();
    Account caller = ctx.getCallingAccount();
    final LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId);
    if (loadBalancer == null) {
        throw new InvalidParameterValueException("Failed to assign to load balancer " + loadBalancerId + ", the load balancer was not found.");
    }
    if (instanceIds == null && vmIdIpMap.isEmpty()) {
        throw new InvalidParameterValueException("Both instanceids and vmidipmap  can't be null");
    }
    // instanceIds and vmIdipmap is passed
    if (instanceIds != null && !vmIdIpMap.isEmpty()) {
        for (long instanceId : instanceIds) {
            if (!vmIdIpMap.containsKey(instanceId)) {
                vmIdIpMap.put(instanceId, null);
            }
        }
    }
    // only instanceids list passed
    if (instanceIds != null && vmIdIpMap.isEmpty()) {
        vmIdIpMap = new HashMap<Long, List<String>>();
        for (long instanceId : instanceIds) {
            vmIdIpMap.put(instanceId, null);
        }
    }
    List<LoadBalancerVMMapVO> mappedInstances = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId, false);
    Set<Long> mappedInstanceIds = new HashSet<Long>();
    for (LoadBalancerVMMapVO mappedInstance : mappedInstances) {
        mappedInstanceIds.add(Long.valueOf(mappedInstance.getInstanceId()));
    }
    Map<Long, List<String>> existingVmIdIps = new HashMap<Long, List<String>>();
    // now get the ips of vm and add it to map
    for (LoadBalancerVMMapVO mappedInstance : mappedInstances) {
        List<String> ipsList = null;
        if (existingVmIdIps.containsKey(mappedInstance.getInstanceId())) {
            ipsList = existingVmIdIps.get(mappedInstance.getInstanceId());
        } else {
            ipsList = new ArrayList<String>();
        }
        ipsList.add(mappedInstance.getInstanceIp());
        existingVmIdIps.put(mappedInstance.getInstanceId(), ipsList);
    }
    final List<UserVm> vmsToAdd = new ArrayList<UserVm>();
    // check for conflict
    Set<Long> passedInstanceIds = vmIdIpMap.keySet();
    for (Long instanceId : passedInstanceIds) {
        UserVm vm = _vmDao.findById(instanceId);
        if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging) {
            InvalidParameterValueException ex = new InvalidParameterValueException("Invalid instance id specified");
            if (vm == null) {
                ex.addProxyObject(instanceId.toString(), "instanceId");
            } else {
                ex.addProxyObject(vm.getUuid(), "instanceId");
            }
            throw ex;
        }
        _rulesMgr.checkRuleAndUserVm(loadBalancer, vm, caller);
        if (vm.getAccountId() != loadBalancer.getAccountId()) {
            throw new PermissionDeniedException("Cannot add virtual machines that do not belong to the same owner.");
        }
        // Let's check to make sure the vm has a nic in the same network as
        // the load balancing rule.
        List<? extends Nic> nics = _networkModel.getNics(vm.getId());
        Nic nicInSameNetwork = null;
        for (Nic nic : nics) {
            if (nic.getNetworkId() == loadBalancer.getNetworkId()) {
                nicInSameNetwork = nic;
                break;
            }
        }
        if (nicInSameNetwork == null) {
            InvalidParameterValueException ex = new InvalidParameterValueException("VM with id specified cannot be added because it doesn't belong in the same network.");
            ex.addProxyObject(vm.getUuid(), "instanceId");
            throw ex;
        }
        String priIp = nicInSameNetwork.getIPv4Address();
        if (existingVmIdIps.containsKey(instanceId)) {
            // now check for ip address
            List<String> mappedIps = existingVmIdIps.get(instanceId);
            List<String> newIps = vmIdIpMap.get(instanceId);
            if (newIps == null) {
                newIps = new ArrayList<String>();
                newIps.add(priIp);
            }
            for (String newIp : newIps) {
                if (mappedIps.contains(newIp)) {
                    throw new InvalidParameterValueException("VM " + instanceId + " with " + newIp + " is already mapped to load balancer.");
                }
            }
        }
        List<String> vmIpsList = vmIdIpMap.get(instanceId);
        String vmLbIp = null;
        if (vmIpsList != null) {
            // check if the ips belongs to nic secondary ip
            for (String ip : vmIpsList) {
                // skip the primary ip from vm secondary ip comparisions
                if (ip.equals(priIp)) {
                    continue;
                }
                if (_nicSecondaryIpDao.findByIp4AddressAndNicId(ip, nicInSameNetwork.getId()) == null) {
                    throw new InvalidParameterValueException("VM ip " + ip + " specified does not belong to " + "nic in network " + nicInSameNetwork.getNetworkId());
                }
            }
        } else {
            vmIpsList = new ArrayList<String>();
            vmIpsList.add(priIp);
        }
        // assign for primary ip and ip passed in vmidipmap
        if (instanceIds != null) {
            if (instanceIds.contains(instanceId)) {
                vmIpsList.add(priIp);
            }
        }
        vmIdIpMap.put(instanceId, vmIpsList);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Adding " + vm + " to the load balancer pool");
        }
        vmsToAdd.add(vm);
    }
    final Set<Long> vmIds = vmIdIpMap.keySet();
    final Map<Long, List<String>> newMap = vmIdIpMap;
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            for (Long vmId : vmIds) {
                final Set<String> lbVmIps = new HashSet<String>(newMap.get(vmId));
                for (String vmIp : lbVmIps) {
                    LoadBalancerVMMapVO map = new LoadBalancerVMMapVO(loadBalancer.getId(), vmId, vmIp, false);
                    map = _lb2VmMapDao.persist(map);
                }
            }
        }
    });
    if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancerId)) {
        // We can consider the job done.
        return true;
    }
    boolean success = false;
    FirewallRule.State backupState = loadBalancer.getState();
    try {
        loadBalancer.setState(FirewallRule.State.Add);
        _lbDao.persist(loadBalancer);
        applyLoadBalancerConfig(loadBalancerId);
        success = true;
    } catch (ResourceUnavailableException e) {
        s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
        success = false;
    } finally {
        if (!success) {
            final List<Long> vmInstanceIds = new ArrayList<Long>();
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    for (Long vmId : vmIds) {
                        vmInstanceIds.add(vmId);
                    }
                }
            });
            if (!vmInstanceIds.isEmpty()) {
                _lb2VmMapDao.remove(loadBalancer.getId(), vmInstanceIds, null);
                s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + "  while attaching VM: " + vmInstanceIds);
            }
            loadBalancer.setState(backupState);
            _lbDao.persist(loadBalancer);
            CloudRuntimeException ex = new CloudRuntimeException("Failed to add specified loadbalancerruleid for vms " + vmInstanceIds);
            ex.addProxyObject(loadBalancer.getUuid(), "loadBalancerId");
            // right VO object or table name.
            throw ex;
        }
    }
    return success;
}
Also used : Account(com.cloud.user.Account) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) UserVm(com.cloud.uservm.UserVm) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) FirewallRule(com.cloud.network.rules.FirewallRule) HashSet(java.util.HashSet) Nic(com.cloud.vm.Nic) CallContext(org.apache.cloudstack.context.CallContext) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 4 with CallContext

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

the class LoadBalancingRulesManagerImpl method removeFromLoadBalancerInternal.

private boolean removeFromLoadBalancerInternal(long loadBalancerId, List<Long> instanceIds, boolean rollBack, Map<Long, List<String>> vmIdIpMap) {
    CallContext caller = CallContext.current();
    LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(loadBalancerId));
    if (loadBalancer == null) {
        throw new InvalidParameterException("Invalid load balancer value: " + loadBalancerId);
    }
    _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer);
    if (instanceIds == null && vmIdIpMap.isEmpty()) {
        throw new InvalidParameterValueException("Both instanceids and vmidipmap  can't be null");
    }
    // instanceIds and vmIdipmap is passed
    if (instanceIds != null && !vmIdIpMap.isEmpty()) {
        for (long instanceId : instanceIds) {
            if (!vmIdIpMap.containsKey(instanceId)) {
                vmIdIpMap.put(instanceId, null);
            }
        }
    }
    // only instanceids list passed
    if (instanceIds != null && vmIdIpMap.isEmpty()) {
        vmIdIpMap = new HashMap<Long, List<String>>();
        for (long instanceId : instanceIds) {
            vmIdIpMap.put(instanceId, null);
        }
    }
    boolean success = false;
    FirewallRule.State backupState = loadBalancer.getState();
    Set<Long> vmIds = vmIdIpMap.keySet();
    try {
        loadBalancer.setState(FirewallRule.State.Add);
        _lbDao.persist(loadBalancer);
        for (long instanceId : vmIds) {
            List<String> lbVmIps = vmIdIpMap.get(instanceId);
            if (lbVmIps == null || lbVmIps.isEmpty()) {
                List<LoadBalancerVMMapVO> lbVms = _lb2VmMapDao.listByLoadBalancerIdAndVmId(loadBalancerId, instanceId);
                if (lbVms == null) {
                    throw new InvalidParameterValueException("The instance id: " + instanceId + " is not configured " + " for LB rule id " + loadBalancerId);
                }
                for (LoadBalancerVMMapVO lbvm : lbVms) {
                    lbvm.setRevoke(true);
                    _lb2VmMapDao.persist(lbvm);
                }
                s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", vmId " + instanceId);
            } else {
                for (String vmIp : lbVmIps) {
                    LoadBalancerVMMapVO map = _lb2VmMapDao.findByLoadBalancerIdAndVmIdVmIp(loadBalancerId, instanceId, vmIp);
                    if (map == null) {
                        throw new InvalidParameterValueException("The instance id: " + instanceId + " is not configured " + " for LB rule id " + loadBalancerId);
                    }
                    map.setRevoke(true);
                    _lb2VmMapDao.persist(map);
                    s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", vmId " + instanceId + ", vmip " + vmIp);
                }
            }
        }
        if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancerId)) {
            // For autoscaled loadbalancer, the rules need not be applied,
            // meaning the call need not reach the resource layer.
            // We can consider the job done and only need to remove the
            // rules in DB
            _lb2VmMapDao.remove(loadBalancer.getId(), instanceIds, null);
            return true;
        }
        if (!applyLoadBalancerConfig(loadBalancerId)) {
            s_logger.warn("Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds);
            CloudRuntimeException ex = new CloudRuntimeException("Failed to remove specified load balancer rule id for vms " + instanceIds);
            ex.addProxyObject(loadBalancer.getUuid(), "loadBalancerId");
            throw ex;
        }
        success = true;
    } catch (ResourceUnavailableException e) {
        if (rollBack && isRollBackAllowedForProvider(loadBalancer)) {
            for (long instanceId : vmIds) {
                List<String> lbVmIps = vmIdIpMap.get(instanceId);
                if (lbVmIps == null || lbVmIps.isEmpty()) {
                    LoadBalancerVMMapVO map = _lb2VmMapDao.findByLoadBalancerIdAndVmId(loadBalancerId, instanceId);
                    map.setRevoke(false);
                    _lb2VmMapDao.persist(map);
                    s_logger.debug("LB Rollback rule id: " + loadBalancerId + ",while removing vmId " + instanceId);
                } else {
                    for (String vmIp : lbVmIps) {
                        LoadBalancerVMMapVO map = _lb2VmMapDao.findByLoadBalancerIdAndVmIdVmIp(loadBalancerId, instanceId, vmIp);
                        map.setRevoke(true);
                        _lb2VmMapDao.persist(map);
                        s_logger.debug("LB Rollback rule id: " + loadBalancerId + ",while removing vmId " + instanceId + ", vmip " + vmIp);
                    }
                }
            }
            loadBalancer.setState(backupState);
            _lbDao.persist(loadBalancer);
            s_logger.debug("LB Rollback rule id: " + loadBalancerId + " while removing vm instances");
        }
        s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
    }
    if (!success) {
        CloudRuntimeException ex = new CloudRuntimeException("Failed to remove specified load balancer rule id for vms " + vmIds);
        ex.addProxyObject(loadBalancer.getUuid(), "loadBalancerId");
        throw ex;
    }
    return success;
}
Also used : LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) CallContext(org.apache.cloudstack.context.CallContext) InvalidParameterException(java.security.InvalidParameterException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ArrayList(java.util.ArrayList) List(java.util.List) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) FirewallRule(com.cloud.network.rules.FirewallRule)

Example 5 with CallContext

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

the class CreatePortForwardingRuleCmd method execute.

@Override
public void execute() throws ResourceUnavailableException {
    CallContext callerContext = CallContext.current();
    boolean success = true;
    PortForwardingRule rule = null;
    try {
        CallContext.current().setEventDetails("Rule Id: " + getEntityId());
        if (getOpenFirewall()) {
            success = success && _firewallService.applyIngressFirewallRules(ipAddressId, callerContext.getCallingAccount());
        }
        success = success && _rulesService.applyPortForwardingRules(ipAddressId, callerContext.getCallingAccount());
        // State is different after the rule is applied, so get new object here
        rule = _entityMgr.findById(PortForwardingRule.class, getEntityId());
        FirewallRuleResponse fwResponse = new FirewallRuleResponse();
        if (rule != null) {
            fwResponse = _responseGenerator.createPortForwardingRuleResponse(rule);
            setResponseObject(fwResponse);
        }
        fwResponse.setResponseName(getCommandName());
    } finally {
        if (!success || rule == null) {
            if (getOpenFirewall()) {
                _firewallService.revokeRelatedFirewallRule(getEntityId(), true);
            }
            try {
                _rulesService.revokePortForwardingRule(getEntityId(), true);
            } catch (Exception ex) {
            // Ignore e.g. failed to apply rules to device error
            }
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to apply port forwarding rule");
        }
    }
}
Also used : ServerApiException(org.apache.cloudstack.api.ServerApiException) CallContext(org.apache.cloudstack.context.CallContext) PortForwardingRule(com.cloud.network.rules.PortForwardingRule) FirewallRuleResponse(org.apache.cloudstack.api.response.FirewallRuleResponse) ServerApiException(org.apache.cloudstack.api.ServerApiException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException)

Aggregations

CallContext (org.apache.cloudstack.context.CallContext)83 Account (com.cloud.user.Account)46 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)32 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)25 ActionEvent (com.cloud.event.ActionEvent)23 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)23 User (com.cloud.user.User)19 DB (com.cloud.utils.db.DB)15 VmWorkJobVO (org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)15 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)12 ArrayList (java.util.ArrayList)11 VMInstanceVO (com.cloud.vm.VMInstanceVO)10 FirewallRule (com.cloud.network.rules.FirewallRule)9 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)7 DeployDestination (com.cloud.deploy.DeployDestination)6 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)6 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)6