Search in sources :

Example 41 with ActionEvent

use of com.cloud.event.ActionEvent in project cloudstack by apache.

the class VirtualNetworkApplianceManagerImpl method rebootRouter.

@Override
@ActionEvent(eventType = EventTypes.EVENT_ROUTER_REBOOT, eventDescription = "rebooting router Vm", async = true)
public VirtualRouter rebootRouter(final long routerId, final boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
    final Account caller = CallContext.current().getCallingAccount();
    // verify parameters
    final DomainRouterVO router = _routerDao.findById(routerId);
    if (router == null) {
        throw new InvalidParameterValueException("Unable to find domain router with id " + routerId + ".");
    }
    _accountMgr.checkAccess(caller, null, true, router);
    // Can reboot domain router only in Running state
    if (router == null || router.getState() != VirtualMachine.State.Running) {
        s_logger.warn("Unable to reboot, virtual router is not in the right state " + router.getState());
        throw new ResourceUnavailableException("Unable to reboot domR, it is not in right state " + router.getState(), DataCenter.class, router.getDataCenterId());
    }
    final UserVO user = _userDao.findById(CallContext.current().getCallingUserId());
    s_logger.debug("Stopping and starting router " + router + " as a part of router reboot");
    if (stop(router, false, user, caller) != null) {
        return startRouter(routerId, reprogramNetwork);
    } else {
        throw new CloudRuntimeException("Failed to reboot router " + router);
    }
}
Also used : Account(com.cloud.user.Account) UserVO(com.cloud.user.UserVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) DomainRouterVO(com.cloud.vm.DomainRouterVO) ActionEvent(com.cloud.event.ActionEvent)

Example 42 with ActionEvent

use of com.cloud.event.ActionEvent 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 43 with ActionEvent

use of com.cloud.event.ActionEvent in project cloudstack by apache.

the class LoadBalancingRulesManagerImpl method updateLBStickinessPolicy.

@Override
@ActionEvent(eventType = EventTypes.EVENT_LB_STICKINESSPOLICY_UPDATE, eventDescription = "updating lb stickiness policy", async = true)
public StickinessPolicy updateLBStickinessPolicy(long id, String customId, Boolean forDisplay) {
    LBStickinessPolicyVO policy = _lb2stickinesspoliciesDao.findById(id);
    if (policy == null) {
        throw new InvalidParameterValueException("Fail to find stickiness policy with " + id);
    }
    LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(policy.getLoadBalancerId()));
    if (loadBalancer == null) {
        throw new InvalidParameterException("Invalid Load balancer : " + policy.getLoadBalancerId() + " for Stickiness policy id: " + id);
    }
    _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, loadBalancer);
    if (customId != null) {
        policy.setUuid(customId);
    }
    if (forDisplay != null) {
        policy.setDisplay(forDisplay);
    }
    _lb2stickinesspoliciesDao.update(id, policy);
    return _lb2stickinesspoliciesDao.findById(id);
}
Also used : InvalidParameterException(java.security.InvalidParameterException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LBStickinessPolicyVO(com.cloud.network.dao.LBStickinessPolicyVO) ActionEvent(com.cloud.event.ActionEvent)

Example 44 with ActionEvent

use of com.cloud.event.ActionEvent in project cloudstack by apache.

the class LoadBalancingRulesManagerImpl method updateLBHealthCheckPolicy.

@Override
@ActionEvent(eventType = EventTypes.EVENT_LB_HEALTHCHECKPOLICY_UPDATE, eventDescription = "updating lb healthcheck policy", async = true)
public HealthCheckPolicy updateLBHealthCheckPolicy(long id, String customId, Boolean forDisplay) {
    LBHealthCheckPolicyVO policy = _lb2healthcheckDao.findById(id);
    if (policy == null) {
        throw new InvalidParameterValueException("Fail to find stickiness policy with " + id);
    }
    LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(policy.getLoadBalancerId()));
    if (loadBalancer == null) {
        throw new InvalidParameterException("Invalid Load balancer : " + policy.getLoadBalancerId() + " for Stickiness policy id: " + id);
    }
    _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, loadBalancer);
    if (customId != null) {
        policy.setUuid(customId);
    }
    if (forDisplay != null) {
        policy.setDisplay(forDisplay);
    }
    _lb2healthcheckDao.update(id, policy);
    return _lb2healthcheckDao.findById(id);
}
Also used : InvalidParameterException(java.security.InvalidParameterException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LBHealthCheckPolicyVO(com.cloud.network.LBHealthCheckPolicyVO) ActionEvent(com.cloud.event.ActionEvent)

Example 45 with ActionEvent

use of com.cloud.event.ActionEvent in project cloudstack by apache.

the class LoadBalancingRulesManagerImpl method updateLoadBalancerRule.

@Override
@ActionEvent(eventType = EventTypes.EVENT_LOAD_BALANCER_UPDATE, eventDescription = "updating load balancer", async = true)
public LoadBalancer updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd) {
    Account caller = CallContext.current().getCallingAccount();
    Long lbRuleId = cmd.getId();
    String name = cmd.getLoadBalancerName();
    String description = cmd.getDescription();
    String algorithm = cmd.getAlgorithm();
    LoadBalancerVO lb = _lbDao.findById(lbRuleId);
    LoadBalancerVO lbBackup = _lbDao.findById(lbRuleId);
    String customId = cmd.getCustomId();
    Boolean forDisplay = cmd.getDisplay();
    if (lb == null) {
        throw new InvalidParameterValueException("Unable to find lb rule by id=" + lbRuleId);
    }
    // check permissions
    _accountMgr.checkAccess(caller, null, true, lb);
    if (name != null) {
        lb.setName(name);
    }
    if (description != null) {
        lb.setDescription(description);
    }
    if (algorithm != null) {
        lb.setAlgorithm(algorithm);
    }
    if (customId != null) {
        lb.setUuid(customId);
    }
    if (forDisplay != null) {
        lb.setDisplay(forDisplay);
    }
    // Validate rule in LB provider
    LoadBalancingRule rule = getLoadBalancerRuleToApply(lb);
    if (!validateLbRule(rule)) {
        throw new InvalidParameterValueException("Modifications in lb rule " + lbRuleId + " are not supported.");
    }
    boolean success = _lbDao.update(lbRuleId, lb);
    // If algorithm is changed, have to reapply the lb config
    if (algorithm != null) {
        try {
            lb.setState(FirewallRule.State.Add);
            _lbDao.persist(lb);
            applyLoadBalancerConfig(lbRuleId);
        } catch (ResourceUnavailableException e) {
            if (isRollBackAllowedForProvider(lb)) {
                /*
                     * NOTE : We use lb object to update db instead of lbBackup
                     * object since db layer will fail to update if there is no
                     * change in the object.
                     */
                if (lbBackup.getName() != null) {
                    lb.setName(lbBackup.getName());
                }
                if (lbBackup.getDescription() != null) {
                    lb.setDescription(lbBackup.getDescription());
                }
                if (lbBackup.getAlgorithm() != null) {
                    lb.setAlgorithm(lbBackup.getAlgorithm());
                }
                lb.setState(lbBackup.getState());
                _lbDao.update(lb.getId(), lb);
                _lbDao.persist(lb);
                s_logger.debug("LB Rollback rule id: " + lbRuleId + " while updating LB rule.");
            }
            s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
            success = false;
        }
    }
    if (!success) {
        throw new CloudRuntimeException("Failed to update load balancer rule: " + lbRuleId);
    }
    return lb;
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ActionEvent(com.cloud.event.ActionEvent)

Aggregations

ActionEvent (com.cloud.event.ActionEvent)209 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)174 Account (com.cloud.user.Account)114 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)80 DB (com.cloud.utils.db.DB)79 TransactionStatus (com.cloud.utils.db.TransactionStatus)40 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)32 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)32 ArrayList (java.util.ArrayList)31 CallContext (org.apache.cloudstack.context.CallContext)22 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)20 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)20 DataCenterVO (com.cloud.dc.DataCenterVO)18 Network (com.cloud.network.Network)18 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)17 InvalidParameterException (java.security.InvalidParameterException)16 List (java.util.List)16 NetworkVO (com.cloud.network.dao.NetworkVO)15 ConfigurationException (javax.naming.ConfigurationException)15 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)14