Search in sources :

Example 26 with LoadBalancerVO

use of com.cloud.network.dao.LoadBalancerVO in project cloudstack by apache.

the class GlobalLoadBalancingRulesServiceImpl method applyGlobalLoadBalancerRuleConfig.

private boolean applyGlobalLoadBalancerRuleConfig(long gslbRuleId, boolean revoke) throws ResourceUnavailableException {
    GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
    assert (gslbRule != null);
    String lbMethod = gslbRule.getAlgorithm();
    String persistenceMethod = gslbRule.getPersistence();
    String serviceType = gslbRule.getServiceType();
    // each Gslb rule will have a FQDN, formed from the domain name associated with the gslb rule
    // and the deployment DNS name configured in global config parameter 'cloud.dns.name'
    String domainName = gslbRule.getGslbDomain();
    String providerDnsName = _globalConfigDao.getValue(Config.CloudDnsName.key());
    String gslbFqdn = domainName + "." + providerDnsName;
    GlobalLoadBalancerConfigCommand gslbConfigCmd = new GlobalLoadBalancerConfigCommand(gslbFqdn, lbMethod, persistenceMethod, serviceType, gslbRuleId, revoke);
    // list of the physical network participating in global load balancing
    List<Pair<Long, Long>> gslbSiteIds = new ArrayList<Pair<Long, Long>>();
    // map of the zone and info corresponding to the load balancer configured in the zone
    Map<Long, SiteLoadBalancerConfig> zoneSiteLoadbalancerMap = new HashMap<Long, SiteLoadBalancerConfig>();
    List<GlobalLoadBalancerLbRuleMapVO> gslbLbMapVos = _gslbLbMapDao.listByGslbRuleId(gslbRuleId);
    assert (gslbLbMapVos != null && !gslbLbMapVos.isEmpty());
    for (GlobalLoadBalancerLbRuleMapVO gslbLbMapVo : gslbLbMapVos) {
        // get the zone in which load balancer rule is deployed
        LoadBalancerVO loadBalancer = _lbDao.findById(gslbLbMapVo.getLoadBalancerId());
        Network network = _networkDao.findById(loadBalancer.getNetworkId());
        long dataCenterId = network.getDataCenterId();
        long physicalNetworkId = network.getPhysicalNetworkId();
        gslbSiteIds.add(new Pair<Long, Long>(dataCenterId, physicalNetworkId));
        IPAddressVO ip = _ipAddressDao.findById(loadBalancer.getSourceIpAddressId());
        SiteLoadBalancerConfig siteLb = new SiteLoadBalancerConfig(gslbLbMapVo.isRevoke(), serviceType, ip.getAddress().addr(), Integer.toString(loadBalancer.getDefaultPortStart()), dataCenterId);
        siteLb.setGslbProviderPublicIp(lookupGslbServiceProvider().getZoneGslbProviderPublicIp(dataCenterId, physicalNetworkId));
        siteLb.setGslbProviderPrivateIp(lookupGslbServiceProvider().getZoneGslbProviderPrivateIp(dataCenterId, physicalNetworkId));
        siteLb.setWeight(gslbLbMapVo.getWeight());
        zoneSiteLoadbalancerMap.put(network.getDataCenterId(), siteLb);
    }
    // to the corresponding GSLB service provider in that zone
    for (Pair<Long, Long> zoneId : gslbSiteIds) {
        List<SiteLoadBalancerConfig> slbs = new ArrayList<SiteLoadBalancerConfig>();
        // set site as 'local' for the site in that zone
        for (Pair<Long, Long> innerLoopZoneId : gslbSiteIds) {
            SiteLoadBalancerConfig siteLb = zoneSiteLoadbalancerMap.get(innerLoopZoneId.first());
            siteLb.setLocal(zoneId.first() == innerLoopZoneId.first());
            slbs.add(siteLb);
        }
        gslbConfigCmd.setSiteLoadBalancers(slbs);
        gslbConfigCmd.setForRevoke(revoke);
        // revoke GSLB configuration completely on the site GSLB provider for the sites that no longer
        // are participants of a GSLB rule
        SiteLoadBalancerConfig siteLb = zoneSiteLoadbalancerMap.get(zoneId.first());
        if (siteLb.forRevoke()) {
            gslbConfigCmd.setForRevoke(true);
        }
        try {
            lookupGslbServiceProvider().applyGlobalLoadBalancerRule(zoneId.first(), zoneId.second(), gslbConfigCmd);
        } catch (ResourceUnavailableException | NullPointerException e) {
            String msg = "Failed to configure GSLB rule in the zone " + zoneId.first() + " due to " + e.getMessage();
            s_logger.warn(msg);
            throw new CloudRuntimeException(msg);
        }
    }
    return true;
}
Also used : GlobalLoadBalancerConfigCommand(com.cloud.agent.api.routing.GlobalLoadBalancerConfigCommand) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) SiteLoadBalancerConfig(com.cloud.agent.api.routing.SiteLoadBalancerConfig) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) IPAddressVO(com.cloud.network.dao.IPAddressVO) Pair(com.cloud.utils.Pair)

Example 27 with LoadBalancerVO

use of com.cloud.network.dao.LoadBalancerVO in project cloudstack by apache.

the class GlobalLoadBalancingRulesServiceImpl method assignToGlobalLoadBalancerRule.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_ASSIGN_TO_GLOBAL_LOAD_BALANCER_RULE, eventDescription = "Assigning a load balancer rule to global load balancer rule", async = true)
public boolean assignToGlobalLoadBalancerRule(AssignToGlobalLoadBalancerRuleCmd assignToGslbCmd) {
    CallContext ctx = CallContext.current();
    Account caller = ctx.getCallingAccount();
    final long gslbRuleId = assignToGslbCmd.getGlobalLoadBalancerRuleId();
    final GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
    if (gslbRule == null) {
        throw new InvalidParameterValueException("Invalid global load balancer rule id: " + gslbRuleId);
    }
    _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, true, gslbRule);
    if (gslbRule.getState() == GlobalLoadBalancerRule.State.Revoke) {
        throw new InvalidParameterValueException("global load balancer rule id: " + gslbRule.getUuid() + " is in revoked state");
    }
    final List<Long> newLbRuleIds = assignToGslbCmd.getLoadBalancerRulesIds();
    if (newLbRuleIds == null || newLbRuleIds.isEmpty()) {
        throw new InvalidParameterValueException("empty list of load balancer rule Ids specified to be assigned" + " global load balancer rule");
    }
    List<Long> oldLbRuleIds = new ArrayList<Long>();
    List<Long> oldZones = new ArrayList<Long>();
    List<Long> newZones = new ArrayList<Long>(oldZones);
    List<Pair<Long, Long>> physcialNetworks = new ArrayList<Pair<Long, Long>>();
    // get the list of load balancer rules id's that are assigned currently to GSLB rule and corresponding zone id's
    List<GlobalLoadBalancerLbRuleMapVO> gslbLbMapVos = _gslbLbMapDao.listByGslbRuleId(gslbRuleId);
    if (gslbLbMapVos != null) {
        for (GlobalLoadBalancerLbRuleMapVO gslbLbMapVo : gslbLbMapVos) {
            LoadBalancerVO loadBalancer = _lbDao.findById(gslbLbMapVo.getLoadBalancerId());
            Network network = _networkDao.findById(loadBalancer.getNetworkId());
            oldZones.add(network.getDataCenterId());
            oldLbRuleIds.add(gslbLbMapVo.getLoadBalancerId());
        }
    }
    /* check each of the load balancer rule id passed in the 'AssignToGlobalLoadBalancerRuleCmd' command is
         *     valid ID
         *     caller has access to the rule
         *     check rule is not revoked
         *     no two rules are in same zone
         *     rule is not already assigned to gslb rule
         */
    for (Long lbRuleId : newLbRuleIds) {
        LoadBalancerVO loadBalancer = _lbDao.findById(lbRuleId);
        if (loadBalancer == null) {
            throw new InvalidParameterValueException("Specified load balancer rule ID does not exist.");
        }
        _accountMgr.checkAccess(caller, null, true, loadBalancer);
        if (gslbRule.getAccountId() != loadBalancer.getAccountId()) {
            throw new InvalidParameterValueException("GSLB rule and load balancer rule does not belong to same account");
        }
        if (loadBalancer.getState() == LoadBalancer.State.Revoke) {
            throw new InvalidParameterValueException("Load balancer ID " + loadBalancer.getUuid() + " is in revoke state");
        }
        if (oldLbRuleIds != null && oldLbRuleIds.contains(loadBalancer.getId())) {
            throw new InvalidParameterValueException("Load balancer ID " + loadBalancer.getUuid() + " is already assigned");
        }
        Network network = _networkDao.findById(loadBalancer.getNetworkId());
        if (oldZones != null && oldZones.contains(network.getDataCenterId()) || newZones != null && newZones.contains(network.getDataCenterId())) {
            throw new InvalidParameterValueException("Load balancer rule specified should be in unique zone");
        }
        newZones.add(network.getDataCenterId());
        physcialNetworks.add(new Pair<Long, Long>(network.getDataCenterId(), network.getPhysicalNetworkId()));
    }
    // for each of the physical network check if GSLB service provider configured
    for (Pair<Long, Long> physicalNetwork : physcialNetworks) {
        if (!checkGslbServiceEnabledInZone(physicalNetwork.first(), physicalNetwork.second())) {
            throw new InvalidParameterValueException("GSLB service is not enabled in the Zone:" + physicalNetwork.first() + " and physical network " + physicalNetwork.second());
        }
    }
    final Map<Long, Long> lbRuleWeightMap = assignToGslbCmd.getLoadBalancerRuleWeightMap();
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            // persist the mapping for the new Lb rule that needs to assigned to a gslb rule
            for (Long lbRuleId : newLbRuleIds) {
                GlobalLoadBalancerLbRuleMapVO newGslbLbMap = new GlobalLoadBalancerLbRuleMapVO();
                newGslbLbMap.setGslbLoadBalancerId(gslbRuleId);
                newGslbLbMap.setLoadBalancerId(lbRuleId);
                if (lbRuleWeightMap != null && lbRuleWeightMap.get(lbRuleId) != null) {
                    newGslbLbMap.setWeight(lbRuleWeightMap.get(lbRuleId));
                }
                _gslbLbMapDao.persist(newGslbLbMap);
            }
            // mark the gslb rule state as add
            if (gslbRule.getState() == GlobalLoadBalancerRule.State.Staged || gslbRule.getState() == GlobalLoadBalancerRule.State.Active) {
                gslbRule.setState(GlobalLoadBalancerRule.State.Add);
                _gslbRuleDao.update(gslbRule.getId(), gslbRule);
            }
        }
    });
    boolean success = false;
    try {
        s_logger.debug("Configuring gslb rule configuration on the gslb service providers in the participating zones");
        // apply the gslb rule on to the back end gslb service providers on zones participating in gslb
        if (!applyGlobalLoadBalancerRuleConfig(gslbRuleId, false)) {
            s_logger.warn("Failed to add load balancer rules " + newLbRuleIds + " to global load balancer rule id " + gslbRuleId);
            CloudRuntimeException ex = new CloudRuntimeException("Failed to add load balancer rules to GSLB rule ");
            throw ex;
        }
        // on success set state to Active
        gslbRule.setState(GlobalLoadBalancerRule.State.Active);
        _gslbRuleDao.update(gslbRule.getId(), gslbRule);
        success = true;
    } catch (ResourceUnavailableException e) {
        throw new CloudRuntimeException("Failed to apply new GSLB configuration while assigning new LB rules to GSLB rule.");
    }
    return success;
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) CallContext(org.apache.cloudstack.context.CallContext) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) Pair(com.cloud.utils.Pair) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 28 with LoadBalancerVO

use of com.cloud.network.dao.LoadBalancerVO in project cloudstack by apache.

the class ExternalDeviceUsageManagerImpl method updateExternalLoadBalancerNetworkUsageStats.

@Override
public void updateExternalLoadBalancerNetworkUsageStats(long loadBalancerRuleId) {
    LoadBalancerVO lb = _loadBalancerDao.findById(loadBalancerRuleId);
    if (lb == null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Cannot update usage stats, LB rule is not found");
        }
        return;
    }
    long networkId = lb.getNetworkId();
    Network network = _networkDao.findById(networkId);
    if (network == null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Cannot update usage stats, Network is not found");
        }
        return;
    }
    ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
    if (lbDeviceVO == null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Cannot update usage stats,  No external LB device found");
        }
        return;
    }
    // Get network stats from the external load balancer
    ExternalNetworkResourceUsageAnswer lbAnswer = null;
    HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId());
    if (externalLoadBalancer != null) {
        ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand();
        lbAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd);
        if (lbAnswer == null || !lbAnswer.getResult()) {
            String details = (lbAnswer != null) ? lbAnswer.getDetails() : "details unavailable";
            String msg = "Unable to get external load balancer stats for network" + networkId + " due to: " + details + ".";
            s_logger.error(msg);
            return;
        }
    }
    long accountId = lb.getAccountId();
    AccountVO account = _accountDao.findById(accountId);
    if (account == null) {
        s_logger.debug("Skipping stats update for external LB for account with ID " + accountId);
        return;
    }
    String publicIp = _networkModel.getIp(lb.getSourceIpAddressId()).getAddress().addr();
    DataCenterVO zone = _dcDao.findById(network.getDataCenterId());
    String statsEntryIdentifier = "account " + account.getAccountName() + ", zone " + zone.getName() + ", network ID " + networkId + ", host ID " + externalLoadBalancer.getName();
    long newCurrentBytesSent = 0;
    long newCurrentBytesReceived = 0;
    if (publicIp != null) {
        long[] bytesSentAndReceived = null;
        statsEntryIdentifier += ", public IP: " + publicIp;
        boolean inline = _networkModel.isNetworkInlineMode(network);
        if (externalLoadBalancer.getType().equals(Host.Type.ExternalLoadBalancer) && inline) {
            // Look up stats for the guest IP address that's mapped to the public IP address
            InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(publicIp);
            if (mapping != null) {
                NicVO nic = _nicDao.findById(mapping.getNicId());
                String loadBalancingIpAddress = nic.getIPv4Address();
                bytesSentAndReceived = lbAnswer.ipBytes.get(loadBalancingIpAddress);
                if (bytesSentAndReceived != null) {
                    bytesSentAndReceived[0] = 0;
                }
            }
        } else {
            bytesSentAndReceived = lbAnswer.ipBytes.get(publicIp);
        }
        if (bytesSentAndReceived == null) {
            s_logger.debug("Didn't get an external network usage answer for public IP " + publicIp);
        } else {
            newCurrentBytesSent += bytesSentAndReceived[0];
            newCurrentBytesReceived += bytesSentAndReceived[1];
        }
        commitStats(networkId, externalLoadBalancer, accountId, publicIp, zone, statsEntryIdentifier, newCurrentBytesSent, newCurrentBytesReceived);
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) NetworkExternalLoadBalancerVO(com.cloud.network.dao.NetworkExternalLoadBalancerVO) ExternalNetworkResourceUsageCommand(com.cloud.agent.api.ExternalNetworkResourceUsageCommand) InlineLoadBalancerNicMapVO(com.cloud.network.dao.InlineLoadBalancerNicMapVO) AccountVO(com.cloud.user.AccountVO) HostVO(com.cloud.host.HostVO) ExternalLoadBalancerDeviceVO(com.cloud.network.dao.ExternalLoadBalancerDeviceVO) ExternalNetworkResourceUsageAnswer(com.cloud.agent.api.ExternalNetworkResourceUsageAnswer) NicVO(com.cloud.vm.NicVO)

Example 29 with LoadBalancerVO

use of com.cloud.network.dao.LoadBalancerVO in project cloudstack by apache.

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<Long>();
    ListProjectResourcesCriteria listProjectResourcesCriteria = null;
    if (isAllocated) {
        final Account caller = getCaller();
        final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(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);
    boolean allocatedOnly = false;
    if (isAllocated != null && isAllocated == true) {
        sb.and("allocated", sb.entity().getAllocatedTime(), SearchCriteria.Op.NNULL);
        allocatedOnly = true;
    }
    VlanType vlanType = null;
    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<List<? extends IpAddress>, Integer>(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 30 with LoadBalancerVO

use of com.cloud.network.dao.LoadBalancerVO in project cloudstack by apache.

the class LoadBalanceRuleHandler method handleCreateLoadBalancerRuleWithLock.

private LoadBalancer handleCreateLoadBalancerRuleWithLock(final CreateLoadBalancerRuleCmd lb, final Account account, final long networkId) throws InsufficientAddressCapacityException, NetworkRuleConflictException {
    Long ipId = null;
    boolean newIp = false;
    List<LoadBalancerVO> existingLbs = findExistingLoadBalancers(lb.getName(), lb.getSourceIpAddressId(), lb.getAccountId(), lb.getDomainId(), lb.getSourcePortStart());
    if (existingLbs == null) {
        existingLbs = findExistingLoadBalancers(lb.getName(), lb.getSourceIpAddressId(), lb.getAccountId(), lb.getDomainId(), null);
        if (existingLbs == null) {
            if (lb.getSourceIpAddressId() != null) {
                throwExceptionIfSuppliedlLbNameIsNotAssociatedWithIpAddress(lb);
            } else {
                s_logger.debug("Could not find any existing frontend ips for this account for this LB rule, acquiring a new frontent IP for ELB");
                final PublicIp ip = allocDirectIp(account, networkId);
                ipId = ip.getId();
                newIp = true;
            }
        } else {
            ipId = existingLbs.get(0).getSourceIpAddressId();
            s_logger.debug("ELB: Found existing frontend ip for this account for this LB rule " + ipId);
        }
    } else {
        s_logger.warn("ELB: Found existing load balancers matching requested new LB");
        throw new NetworkRuleConflictException("ELB: Found existing load balancers matching requested new LB");
    }
    final IPAddressVO ipAddr = _ipAddressDao.findById(ipId);
    LoadBalancer result = null;
    try {
        lb.setSourceIpAddressId(ipId);
        result = _lbMgr.createPublicLoadBalancer(lb.getXid(), lb.getName(), lb.getDescription(), lb.getSourcePortStart(), lb.getDefaultPortStart(), ipId.longValue(), lb.getProtocol(), lb.getAlgorithm(), false, CallContext.current(), lb.getLbProtocol(), true);
    } catch (final NetworkRuleConflictException e) {
        s_logger.warn("Failed to create LB rule, not continuing with ELB deployment");
        if (newIp) {
            releaseIp(ipId, CallContext.current().getCallingUserId(), account);
        }
        throw e;
    }
    DomainRouterVO elbVm = null;
    if (existingLbs == null) {
        elbVm = findElbVmWithCapacity(ipAddr);
        if (elbVm == null) {
            elbVm = deployLoadBalancerVM(networkId, ipAddr);
            if (elbVm == null) {
                final Network network = _networkModel.getNetwork(networkId);
                s_logger.warn("Failed to deploy a new ELB vm for ip " + ipAddr + " in network " + network + "lb name=" + lb.getName());
                if (newIp) {
                    releaseIp(ipId, CallContext.current().getCallingUserId(), account);
                }
            }
        }
    } else {
        final ElasticLbVmMapVO elbVmMap = _elbVmMapDao.findOneByIp(ipId);
        if (elbVmMap != null) {
            elbVm = _routerDao.findById(elbVmMap.getElbVmId());
        }
    }
    if (elbVm == null) {
        s_logger.warn("No ELB VM can be found or deployed");
        s_logger.warn("Deleting LB since we failed to deploy ELB VM");
        _lbDao.remove(result.getId());
        return null;
    }
    final ElasticLbVmMapVO mapping = new ElasticLbVmMapVO(ipId, elbVm.getId(), result.getId());
    _elbVmMapDao.persist(mapping);
    return result;
}
Also used : ElasticLbVmMapVO(com.cloud.network.ElasticLbVmMapVO) PublicIp(com.cloud.network.addr.PublicIp) Network(com.cloud.network.Network) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LoadBalancer(com.cloud.network.rules.LoadBalancer) IPAddressVO(com.cloud.network.dao.IPAddressVO) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Aggregations

LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)56 ArrayList (java.util.ArrayList)29 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)22 Account (com.cloud.user.Account)19 ActionEvent (com.cloud.event.ActionEvent)17 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)17 DB (com.cloud.utils.db.DB)17 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)15 CallContext (org.apache.cloudstack.context.CallContext)12 LoadBalancerVMMapVO (com.cloud.network.dao.LoadBalancerVMMapVO)11 FirewallRule (com.cloud.network.rules.FirewallRule)11 Ip (com.cloud.utils.net.Ip)11 InvalidParameterException (java.security.InvalidParameterException)11 NetworkVO (com.cloud.network.dao.NetworkVO)10 Network (com.cloud.network.Network)9 IPAddressVO (com.cloud.network.dao.IPAddressVO)9 LoadBalancerDao (com.cloud.network.dao.LoadBalancerDao)9 TransactionStatus (com.cloud.utils.db.TransactionStatus)9 List (java.util.List)9 LbHealthCheckPolicy (com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy)8