Search in sources :

Example 56 with LoadBalancerVO

use of com.cloud.network.dao.LoadBalancerVO in project cosmic by MissionCriticalCloud.

the class ManagementServerImpl method searchForIPAddresses.

@Override
public Pair<List<? extends IpAddress>, Integer> searchForIPAddresses(final ListPublicIpAddressesCmd cmd) {
    final Object keyword = cmd.getKeyword();
    final Long physicalNetworkId = cmd.getPhysicalNetworkId();
    final Long associatedNetworkId = cmd.getAssociatedNetworkId();
    final Long zone = cmd.getZoneId();
    final String address = cmd.getIpAddress();
    final Long vlan = cmd.getVlanId();
    final Boolean forVirtualNetwork = cmd.isForVirtualNetwork();
    final Boolean forLoadBalancing = cmd.isForLoadBalancing();
    final Long ipId = cmd.getId();
    final Boolean sourceNat = cmd.getIsSourceNat();
    final Boolean staticNat = cmd.getIsStaticNat();
    final Long vpcId = cmd.getVpcId();
    final Boolean forDisplay = cmd.getDisplay();
    final Map<String, String> tags = cmd.getTags();
    final String state = cmd.getState();
    Boolean isAllocated = cmd.isAllocatedOnly();
    if (isAllocated == null) {
        isAllocated = Boolean.TRUE;
        if (state != null) {
            isAllocated = Boolean.FALSE;
        }
    }
    final Filter searchFilter = new Filter(IPAddressVO.class, "address", false, cmd.getStartIndex(), cmd.getPageSizeVal());
    final SearchBuilder<IPAddressVO> sb = _publicIpAddressDao.createSearchBuilder();
    Long domainId = null;
    Boolean isRecursive = null;
    final List<Long> permittedAccounts = new ArrayList<>();
    ListProjectResourcesCriteria listProjectResourcesCriteria = null;
    if (isAllocated) {
        final Account caller = getCaller();
        final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
        _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
        domainId = domainIdRecursiveListProject.first();
        isRecursive = domainIdRecursiveListProject.second();
        listProjectResourcesCriteria = domainIdRecursiveListProject.third();
        _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    }
    sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
    sb.and("address", sb.entity().getAddress(), SearchCriteria.Op.EQ);
    sb.and("vlanDbId", sb.entity().getVlanId(), SearchCriteria.Op.EQ);
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("physicalNetworkId", sb.entity().getPhysicalNetworkId(), SearchCriteria.Op.EQ);
    sb.and("associatedNetworkIdEq", sb.entity().getAssociatedWithNetworkId(), SearchCriteria.Op.EQ);
    sb.and("isSourceNat", sb.entity().isSourceNat(), SearchCriteria.Op.EQ);
    sb.and("isStaticNat", sb.entity().isOneToOneNat(), SearchCriteria.Op.EQ);
    sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ);
    sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);
    sb.and("display", sb.entity().isDisplay(), SearchCriteria.Op.EQ);
    if (forLoadBalancing != null && forLoadBalancing) {
        final SearchBuilder<LoadBalancerVO> lbSearch = _loadbalancerDao.createSearchBuilder();
        sb.join("lbSearch", lbSearch, sb.entity().getId(), lbSearch.entity().getSourceIpAddressId(), JoinType.INNER);
        sb.groupBy(sb.entity().getId());
    }
    if (keyword != null && address == null) {
        sb.and("addressLIKE", sb.entity().getAddress(), SearchCriteria.Op.LIKE);
    }
    if (tags != null && !tags.isEmpty()) {
        final SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
        for (int count = 0; count < tags.size(); count++) {
            tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
            tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
            tagSearch.cp();
        }
        tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
        sb.groupBy(sb.entity().getId());
        sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
    }
    final SearchBuilder<VlanVO> vlanSearch = _vlanDao.createSearchBuilder();
    vlanSearch.and("vlanType", vlanSearch.entity().getVlanType(), SearchCriteria.Op.EQ);
    sb.join("vlanSearch", vlanSearch, sb.entity().getVlanId(), vlanSearch.entity().getId(), JoinBuilder.JoinType.INNER);
    if (isAllocated != null && isAllocated == true) {
        sb.and("allocated", sb.entity().getAllocatedTime(), SearchCriteria.Op.NNULL);
    }
    final VlanType vlanType;
    if (forVirtualNetwork != null) {
        vlanType = forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached;
    } else {
        vlanType = VlanType.VirtualNetwork;
    }
    final SearchCriteria<IPAddressVO> sc = sb.create();
    if (isAllocated) {
        _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    }
    sc.setJoinParameters("vlanSearch", "vlanType", vlanType);
    if (tags != null && !tags.isEmpty()) {
        int count = 0;
        sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.PublicIpAddress.toString());
        for (final String key : tags.keySet()) {
            sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key);
            sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key));
            count++;
        }
    }
    if (zone != null) {
        sc.setParameters("dataCenterId", zone);
    }
    if (vpcId != null) {
        sc.setParameters("vpcId", vpcId);
    }
    if (ipId != null) {
        sc.setParameters("id", ipId);
    }
    if (sourceNat != null) {
        sc.setParameters("isSourceNat", sourceNat);
    }
    if (staticNat != null) {
        sc.setParameters("isStaticNat", staticNat);
    }
    if (address == null && keyword != null) {
        sc.setParameters("addressLIKE", "%" + keyword + "%");
    }
    if (address != null) {
        sc.setParameters("address", address);
    }
    if (vlan != null) {
        sc.setParameters("vlanDbId", vlan);
    }
    if (physicalNetworkId != null) {
        sc.setParameters("physicalNetworkId", physicalNetworkId);
    }
    if (associatedNetworkId != null) {
        sc.setParameters("associatedNetworkIdEq", associatedNetworkId);
    }
    if (forDisplay != null) {
        sc.setParameters("display", forDisplay);
    }
    if (state != null) {
        sc.setParameters("state", state);
    }
    final Pair<List<IPAddressVO>, Integer> result = _publicIpAddressDao.searchAndCount(sc, searchFilter);
    return new Pair<>(result.first(), result.second());
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ResourceTagVO(com.cloud.tags.ResourceTagVO) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) VlanVO(com.cloud.dc.VlanVO) VlanType(com.cloud.dc.Vlan.VlanType) Pair(com.cloud.utils.Pair) SSHKeyPair(com.cloud.user.SSHKeyPair) Ternary(com.cloud.utils.Ternary) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) Filter(com.cloud.utils.db.Filter) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 57 with LoadBalancerVO

use of com.cloud.network.dao.LoadBalancerVO in project cosmic by MissionCriticalCloud.

the class LoadBalancingRulesManagerImpl method assignCertToLoadBalancer.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_LB_CERT_ASSIGN, eventDescription = "assigning certificate to load balancer", async = true)
public boolean assignCertToLoadBalancer(final long lbRuleId, final Long certId) {
    final CallContext caller = CallContext.current();
    final LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(lbRuleId));
    if (loadBalancer == null) {
        throw new InvalidParameterException("Invalid load balancer id: " + lbRuleId);
    }
    final SslCertVO certVO = _entityMgr.findById(SslCertVO.class, certId);
    if (certVO == null) {
        throw new InvalidParameterException("Invalid certificate id: " + certId);
    }
    _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer);
    // check if LB and Cert belong to the same account
    if (loadBalancer.getAccountId() != certVO.getAccountId()) {
        throw new InvalidParameterValueException("Access denied for account " + certVO.getAccountId());
    }
    final String capability = getLBCapability(loadBalancer.getNetworkId(), Capability.SslTermination.getName());
    if (capability == null) {
        throw new InvalidParameterValueException("Ssl termination not supported by the loadbalancer");
    }
    // check if the lb is already bound
    final LoadBalancerCertMapVO certMapRule = _lbCertMapDao.findByLbRuleId(loadBalancer.getId());
    if (certMapRule != null) {
        throw new InvalidParameterValueException("Another certificate is already bound to the LB");
    }
    // check for correct port
    if (loadBalancer.getLbProtocol() == null || !(loadBalancer.getLbProtocol().equals(NetUtils.SSL_PROTO))) {
        throw new InvalidParameterValueException("Bad LB protocol: Expected ssl got " + loadBalancer.getLbProtocol());
    }
    boolean success = false;
    final FirewallRule.State backupState = loadBalancer.getState();
    try {
        loadBalancer.setState(FirewallRule.State.Add);
        _lbDao.persist(loadBalancer);
        final LoadBalancerCertMapVO certMap = new LoadBalancerCertMapVO(lbRuleId, certId, false);
        _lbCertMapDao.persist(certMap);
        applyLoadBalancerConfig(loadBalancer.getId());
        success = true;
    } catch (final ResourceUnavailableException e) {
        if (isRollBackAllowedForProvider(loadBalancer)) {
            loadBalancer.setState(backupState);
            _lbDao.persist(loadBalancer);
            final LoadBalancerCertMapVO certMap = _lbCertMapDao.findByLbRuleId(lbRuleId);
            _lbCertMapDao.remove(certMap.getId());
            s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " while adding cert");
        }
        s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
    }
    return success;
}
Also used : InvalidParameterException(java.security.InvalidParameterException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) SslCertVO(com.cloud.network.dao.SslCertVO) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) LoadBalancerCertMapVO(com.cloud.network.dao.LoadBalancerCertMapVO) CallContext(com.cloud.context.CallContext) FirewallRule(com.cloud.network.rules.FirewallRule) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 58 with LoadBalancerVO

use of com.cloud.network.dao.LoadBalancerVO in project cosmic by MissionCriticalCloud.

the class LoadBalancingRulesManagerImpl method applyLBStickinessPolicy.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_LB_STICKINESSPOLICY_CREATE, eventDescription = "Apply Stickinesspolicy to load balancer ", async = true)
public boolean applyLBStickinessPolicy(final CreateLBStickinessPolicyCmd cmd) {
    boolean success = true;
    FirewallRule.State backupState = null;
    long oldStickinessPolicyId = 0;
    final LoadBalancerVO loadBalancer = _lbDao.findById(cmd.getLbRuleId());
    if (loadBalancer == null) {
        throw new InvalidParameterException("Invalid Load balancer Id:" + cmd.getLbRuleId());
    }
    final List<LBStickinessPolicyVO> stickinessPolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(cmd.getLbRuleId(), false);
    for (final LBStickinessPolicyVO stickinessPolicy : stickinessPolicies) {
        if (stickinessPolicy.getId() == cmd.getEntityId()) {
            backupState = loadBalancer.getState();
            loadBalancer.setState(FirewallRule.State.Add);
            _lbDao.persist(loadBalancer);
        } else {
            oldStickinessPolicyId = stickinessPolicy.getId();
            stickinessPolicy.setRevoke(true);
            _lb2stickinesspoliciesDao.persist(stickinessPolicy);
        }
    }
    try {
        applyLoadBalancerConfig(cmd.getLbRuleId());
    } catch (final ResourceUnavailableException e) {
        s_logger.warn("Unable to apply Stickiness policy to the lb rule: " + cmd.getLbRuleId() + " because resource is unavaliable:", e);
        if (isRollBackAllowedForProvider(loadBalancer)) {
            loadBalancer.setState(backupState);
            _lbDao.persist(loadBalancer);
            deleteLBStickinessPolicy(cmd.getEntityId(), false);
            s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " lb state rolback while creating sticky policy");
        } else {
            deleteLBStickinessPolicy(cmd.getEntityId(), false);
            if (oldStickinessPolicyId != 0) {
                final LBStickinessPolicyVO stickinessPolicy = _lb2stickinesspoliciesDao.findById(oldStickinessPolicyId);
                stickinessPolicy.setRevoke(false);
                _lb2stickinesspoliciesDao.persist(stickinessPolicy);
                try {
                    if (backupState.equals(FirewallRule.State.Active)) {
                        applyLoadBalancerConfig(cmd.getLbRuleId());
                    }
                } catch (final ResourceUnavailableException e1) {
                    s_logger.info("[ignored] applying load balancer config.", e1);
                } finally {
                    loadBalancer.setState(backupState);
                    _lbDao.persist(loadBalancer);
                }
            }
        }
        success = false;
    }
    return success;
}
Also used : InvalidParameterException(java.security.InvalidParameterException) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) LBStickinessPolicyVO(com.cloud.network.dao.LBStickinessPolicyVO) FirewallRule(com.cloud.network.rules.FirewallRule) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 59 with LoadBalancerVO

use of com.cloud.network.dao.LoadBalancerVO in project cosmic by MissionCriticalCloud.

the class LoadBalancingRulesManagerImpl method searchForLoadBalancers.

@Override
public Pair<List<? extends LoadBalancer>, Integer> searchForLoadBalancers(final ListLoadBalancerRulesCmd cmd) {
    final Long ipId = cmd.getPublicIpId();
    final Long zoneId = cmd.getZoneId();
    final Long id = cmd.getId();
    final String name = cmd.getLoadBalancerRuleName();
    final String keyword = cmd.getKeyword();
    final Long instanceId = cmd.getVirtualMachineId();
    final Long networkId = cmd.getNetworkId();
    final Map<String, String> tags = cmd.getTags();
    final Boolean forDisplay = cmd.getDisplay();
    final Account caller = CallContext.current().getCallingAccount();
    final List<Long> permittedAccounts = new ArrayList<>();
    final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
    final Long domainId = domainIdRecursiveListProject.first();
    final Boolean isRecursive = domainIdRecursiveListProject.second();
    final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    final Filter searchFilter = new Filter(LoadBalancerVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    final SearchBuilder<LoadBalancerVO> sb = _lbDao.createSearchBuilder();
    _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
    sb.and("sourceIpAddress", sb.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ);
    sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ);
    sb.and("scheme", sb.entity().getScheme(), SearchCriteria.Op.EQ);
    sb.and("display", sb.entity().isDisplay(), SearchCriteria.Op.EQ);
    if (instanceId != null) {
        final SearchBuilder<LoadBalancerVMMapVO> lbVMSearch = _lb2VmMapDao.createSearchBuilder();
        lbVMSearch.and("instanceId", lbVMSearch.entity().getInstanceId(), SearchCriteria.Op.EQ);
        sb.join("lbVMSearch", lbVMSearch, sb.entity().getId(), lbVMSearch.entity().getLoadBalancerId(), JoinBuilder.JoinType.INNER);
    }
    if (zoneId != null) {
        final SearchBuilder<IPAddressVO> ipSearch = _ipAddressDao.createSearchBuilder();
        ipSearch.and("zoneId", ipSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
        sb.join("ipSearch", ipSearch, sb.entity().getSourceIpAddressId(), ipSearch.entity().getId(), JoinBuilder.JoinType.INNER);
    }
    if (tags != null && !tags.isEmpty()) {
        final SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
        for (int count = 0; count < tags.size(); count++) {
            tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
            tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
            tagSearch.cp();
        }
        tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
        sb.groupBy(sb.entity().getId());
        sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
    }
    final SearchCriteria<LoadBalancerVO> sc = sb.create();
    _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    if (keyword != null) {
        final SearchCriteria<LoadBalancerVO> ssc = _lbDao.createSearchCriteria();
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }
    if (name != null) {
        sc.setParameters("name", "%" + name + "%");
    }
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (ipId != null) {
        sc.setParameters("sourceIpAddress", ipId);
    }
    if (instanceId != null) {
        sc.setJoinParameters("lbVMSearch", "instanceId", instanceId);
    }
    if (zoneId != null) {
        sc.setJoinParameters("ipSearch", "zoneId", zoneId);
    }
    if (networkId != null) {
        sc.setParameters("networkId", networkId);
    }
    if (tags != null && !tags.isEmpty()) {
        int count = 0;
        sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.LoadBalancer.toString());
        for (final String key : tags.keySet()) {
            sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key);
            sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key));
            count++;
        }
    }
    if (forDisplay != null) {
        sc.setParameters("display", forDisplay);
    }
    // list only Public load balancers using this command
    sc.setParameters("scheme", Scheme.Public);
    final Pair<List<LoadBalancerVO>, Integer> result = _lbDao.searchAndCount(sc, searchFilter);
    return new Pair<>(result.first(), result.second());
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) ResourceTagVO(com.cloud.tags.ResourceTagVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair) Ternary(com.cloud.utils.Ternary) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) Filter(com.cloud.utils.db.Filter) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 60 with LoadBalancerVO

use of com.cloud.network.dao.LoadBalancerVO in project cosmic by MissionCriticalCloud.

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(final long loadBalancerId, final List<Long> instanceIds, Map<Long, List<String>> vmIdIpMap) {
    final CallContext ctx = CallContext.current();
    final 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 (final long instanceId : instanceIds) {
            if (!vmIdIpMap.containsKey(instanceId)) {
                vmIdIpMap.put(instanceId, null);
            }
        }
    }
    // only instanceids list passed
    if (instanceIds != null && vmIdIpMap.isEmpty()) {
        vmIdIpMap = new HashMap<>();
        for (final long instanceId : instanceIds) {
            vmIdIpMap.put(instanceId, null);
        }
    }
    final List<LoadBalancerVMMapVO> mappedInstances = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId, false);
    final Set<Long> mappedInstanceIds = new HashSet<>();
    for (final LoadBalancerVMMapVO mappedInstance : mappedInstances) {
        mappedInstanceIds.add(Long.valueOf(mappedInstance.getInstanceId()));
    }
    final Map<Long, List<String>> existingVmIdIps = new HashMap<>();
    // now get the ips of vm and add it to map
    for (final LoadBalancerVMMapVO mappedInstance : mappedInstances) {
        List<String> ipsList = null;
        if (existingVmIdIps.containsKey(mappedInstance.getInstanceId())) {
            ipsList = existingVmIdIps.get(mappedInstance.getInstanceId());
        } else {
            ipsList = new ArrayList<>();
        }
        ipsList.add(mappedInstance.getInstanceIp());
        existingVmIdIps.put(mappedInstance.getInstanceId(), ipsList);
    }
    final List<UserVm> vmsToAdd = new ArrayList<>();
    // check for conflict
    final Set<Long> passedInstanceIds = vmIdIpMap.keySet();
    for (final Long instanceId : passedInstanceIds) {
        final UserVm vm = _vmDao.findById(instanceId);
        if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging) {
            final 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.
        final List<? extends Nic> nics = _networkModel.getNics(vm.getId());
        Nic nicInSameNetwork = null;
        for (final Nic nic : nics) {
            if (nic.getNetworkId() == loadBalancer.getNetworkId()) {
                nicInSameNetwork = nic;
                break;
            }
        }
        if (nicInSameNetwork == null) {
            final 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;
        }
        final String priIp = nicInSameNetwork.getIPv4Address();
        if (existingVmIdIps.containsKey(instanceId)) {
            // now check for ip address
            final List<String> mappedIps = existingVmIdIps.get(instanceId);
            List<String> newIps = vmIdIpMap.get(instanceId);
            if (newIps == null) {
                newIps = new ArrayList<>();
                newIps.add(priIp);
            }
            for (final 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);
        final String vmLbIp = null;
        if (vmIpsList != null) {
            // check if the ips belongs to nic secondary ip
            for (final 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<>();
            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(final TransactionStatus status) {
            for (final Long vmId : vmIds) {
                final Set<String> lbVmIps = new HashSet<>(newMap.get(vmId));
                for (final String vmIp : lbVmIps) {
                    LoadBalancerVMMapVO map = new LoadBalancerVMMapVO(loadBalancer.getId(), vmId, vmIp, false);
                    map = _lb2VmMapDao.persist(map);
                }
            }
        }
    });
    boolean success = false;
    final FirewallRule.State backupState = loadBalancer.getState();
    try {
        loadBalancer.setState(FirewallRule.State.Add);
        _lbDao.persist(loadBalancer);
        applyLoadBalancerConfig(loadBalancerId);
        success = true;
    } catch (final 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<>();
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    for (final 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);
            final 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.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) ArrayList(java.util.ArrayList) List(java.util.List) FirewallRule(com.cloud.network.rules.FirewallRule) HashSet(java.util.HashSet) Nic(com.cloud.vm.Nic) CallContext(com.cloud.context.CallContext) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)96 ArrayList (java.util.ArrayList)45 ActionEvent (com.cloud.event.ActionEvent)31 Account (com.cloud.user.Account)30 DB (com.cloud.utils.db.DB)30 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)29 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)27 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)23 LoadBalancerVMMapVO (com.cloud.network.dao.LoadBalancerVMMapVO)23 InvalidParameterException (java.security.InvalidParameterException)22 FirewallRule (com.cloud.network.rules.FirewallRule)21 Ip (com.cloud.utils.net.Ip)18 List (java.util.List)17 NetworkVO (com.cloud.network.dao.NetworkVO)15 TransactionStatus (com.cloud.utils.db.TransactionStatus)14 IPAddressVO (com.cloud.network.dao.IPAddressVO)13 LoadBalancerDao (com.cloud.network.dao.LoadBalancerDao)13 LbDestination (com.cloud.network.lb.LoadBalancingRule.LbDestination)13 LbHealthCheckPolicy (com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy)13 HashMap (java.util.HashMap)13