Search in sources :

Example 1 with DomainVlanMapVO

use of com.cloud.dc.DomainVlanMapVO in project cloudstack by apache.

the class ConfigurationManagerImpl method deleteVlanAndPublicIpRange.

@Override
@DB
public boolean deleteVlanAndPublicIpRange(final long userId, final long vlanDbId, final Account caller) {
    VlanVO vlanRange = _vlanDao.findById(vlanDbId);
    if (vlanRange == null) {
        throw new InvalidParameterValueException("Please specify a valid IP range id.");
    }
    boolean isAccountSpecific = false;
    final List<AccountVlanMapVO> acctVln = _accountVlanMapDao.listAccountVlanMapsByVlan(vlanRange.getId());
    // account_vlan_map.
    if (acctVln != null && !acctVln.isEmpty()) {
        isAccountSpecific = true;
    }
    boolean isDomainSpecific = false;
    List<DomainVlanMapVO> domainVlan = _domainVlanMapDao.listDomainVlanMapsByVlan(vlanRange.getId());
    // Check for domain wide pool. It will have an entry for domain_vlan_map.
    if (domainVlan != null && !domainVlan.isEmpty()) {
        isDomainSpecific = true;
    }
    // Check if the VLAN has any allocated public IPs
    final List<IPAddressVO> ips = _publicIpAddressDao.listByVlanId(vlanDbId);
    if (isAccountSpecific) {
        int resourceCountToBeDecrement = 0;
        try {
            vlanRange = _vlanDao.acquireInLockTable(vlanDbId, 30);
            if (vlanRange == null) {
                throw new CloudRuntimeException("Unable to acquire vlan configuration: " + vlanDbId);
            }
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("lock vlan " + vlanDbId + " is acquired");
            }
            for (final IPAddressVO ip : ips) {
                boolean success = true;
                if (ip.isOneToOneNat()) {
                    throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range is used for static nat purposes. Cleanup the rules first");
                }
                if (ip.isSourceNat()) {
                    throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range is a source nat ip for the network id=" + ip.getSourceNetworkId() + ". IP range with the source nat ip address can be removed either as a part of Network, or account removal");
                }
                if (_firewallDao.countRulesByIpId(ip.getId()) > 0) {
                    throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId + " as ip " + ip + " belonging to the range has firewall rules applied. Cleanup the rules first");
                }
                if (ip.getAllocatedTime() != null) {
                    // This means IP is allocated
                    // release public ip address here
                    success = _ipAddrMgr.disassociatePublicIpAddress(ip.getId(), userId, caller);
                }
                if (!success) {
                    s_logger.warn("Some ip addresses failed to be released as a part of vlan " + vlanDbId + " removal");
                } else {
                    resourceCountToBeDecrement++;
                    final boolean usageHidden = _ipAddrMgr.isUsageHidden(ip);
                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_RELEASE, acctVln.get(0).getAccountId(), ip.getDataCenterId(), ip.getId(), ip.getAddress().toString(), ip.isSourceNat(), vlanRange.getVlanType().toString(), ip.getSystem(), usageHidden, ip.getClass().getName(), ip.getUuid());
                }
            }
        } finally {
            _vlanDao.releaseFromLockTable(vlanDbId);
            if (resourceCountToBeDecrement > 0) {
                // Making sure to decrement the count of only success operations above. For any reaason if disassociation fails then this number will vary from original range length.
                _resourceLimitMgr.decrementResourceCount(acctVln.get(0).getAccountId(), ResourceType.public_ip, new Long(resourceCountToBeDecrement));
            }
        }
    } else {
        // !isAccountSpecific
        final NicIpAliasVO ipAlias = _nicIpAliasDao.findByGatewayAndNetworkIdAndState(vlanRange.getVlanGateway(), vlanRange.getNetworkId(), NicIpAlias.State.active);
        // check if the ipalias belongs to the vlan range being deleted.
        if (ipAlias != null && vlanDbId == _publicIpAddressDao.findByIpAndSourceNetworkId(vlanRange.getNetworkId(), ipAlias.getIp4Address()).getVlanId()) {
            throw new InvalidParameterValueException("Cannot delete vlan range " + vlanDbId + " as " + ipAlias.getIp4Address() + "is being used for providing dhcp service in this subnet. Delete all VMs in this subnet and try again");
        }
        final long allocIpCount = _publicIpAddressDao.countIPs(vlanRange.getDataCenterId(), vlanDbId, true);
        if (allocIpCount > 0) {
            throw new InvalidParameterValueException(allocIpCount + "  Ips are in use. Cannot delete this vlan");
        }
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            _publicIpAddressDao.deletePublicIPRange(vlanDbId);
            s_logger.debug(String.format("Delete Public IP Range (from user_ip_address, where vlan_db_d=%s)", vlanDbId));
            _vlanDao.remove(vlanDbId);
            s_logger.debug(String.format("Mark vlan as Remove vlan (vlan_db_id=%s)", vlanDbId));
            SearchBuilder<PodVlanMapVO> sb = podVlanMapDao.createSearchBuilder();
            sb.and("vlan_db_id", sb.entity().getVlanDbId(), SearchCriteria.Op.EQ);
            SearchCriteria<PodVlanMapVO> sc = sb.create();
            sc.setParameters("vlan_db_id", vlanDbId);
            podVlanMapDao.remove(sc);
            s_logger.debug(String.format("Delete vlan_db_id=%s in pod_vlan_map", vlanDbId));
        }
    });
    return true;
}
Also used : AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) SearchBuilder(com.cloud.utils.db.SearchBuilder) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) NicIpAliasVO(com.cloud.vm.dao.NicIpAliasVO) DomainVlanMapVO(com.cloud.dc.DomainVlanMapVO) SearchCriteria(com.cloud.utils.db.SearchCriteria) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) DB(com.cloud.utils.db.DB)

Example 2 with DomainVlanMapVO

use of com.cloud.dc.DomainVlanMapVO in project cloudstack by apache.

the class ConfigurationManagerImpl method commitVlanAndIpRange.

private VlanVO commitVlanAndIpRange(final long zoneId, final long networkId, final long physicalNetworkId, final Long podId, final String startIP, final String endIP, final String vlanGateway, final String vlanNetmask, final String vlanId, final Domain domain, final Account vlanOwner, final String vlanIp6Gateway, final String vlanIp6Cidr, final boolean ipv4, final DataCenterVO zone, final VlanType vlanType, final String ipv6Range, final String ipRange, final boolean forSystemVms) {
    return Transaction.execute(new TransactionCallback<VlanVO>() {

        @Override
        public VlanVO doInTransaction(final TransactionStatus status) {
            VlanVO vlan = new VlanVO(vlanType, vlanId, vlanGateway, vlanNetmask, zone.getId(), ipRange, networkId, physicalNetworkId, vlanIp6Gateway, vlanIp6Cidr, ipv6Range);
            s_logger.debug("Saving vlan range " + vlan);
            vlan = _vlanDao.persist(vlan);
            // public ip range
            if (ipv4) {
                if (!savePublicIPRange(startIP, endIP, zoneId, vlan.getId(), networkId, physicalNetworkId, forSystemVms)) {
                    throw new CloudRuntimeException("Failed to save IPv4 range. Please contact Cloud Support.");
                }
            }
            if (vlanOwner != null) {
                // This VLAN is account-specific, so create an AccountVlanMapVO
                // entry
                final AccountVlanMapVO accountVlanMapVO = new AccountVlanMapVO(vlanOwner.getId(), vlan.getId());
                _accountVlanMapDao.persist(accountVlanMapVO);
                // generate usage event for dedication of every ip address in the
                // range
                final List<IPAddressVO> ips = _publicIpAddressDao.listByVlanId(vlan.getId());
                for (final IPAddressVO ip : ips) {
                    final boolean usageHidden = _ipAddrMgr.isUsageHidden(ip);
                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, vlanOwner.getId(), ip.getDataCenterId(), ip.getId(), ip.getAddress().toString(), ip.isSourceNat(), vlan.getVlanType().toString(), ip.getSystem(), usageHidden, ip.getClass().getName(), ip.getUuid());
                }
                // increment resource count for dedicated public ip's
                _resourceLimitMgr.incrementResourceCount(vlanOwner.getId(), ResourceType.public_ip, new Long(ips.size()));
            } else if (domain != null && !forSystemVms) {
                // This VLAN is domain-wide, so create a DomainVlanMapVO entry
                final DomainVlanMapVO domainVlanMapVO = new DomainVlanMapVO(domain.getId(), vlan.getId());
                _domainVlanMapDao.persist(domainVlanMapVO);
            } else if (podId != null) {
                // This VLAN is pod-wide, so create a PodVlanMapVO entry
                final PodVlanMapVO podVlanMapVO = new PodVlanMapVO(podId, vlan.getId());
                podVlanMapDao.persist(podVlanMapVO);
            }
            return vlan;
        }
    });
}
Also used : CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) PodVlanMapVO(com.cloud.dc.PodVlanMapVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) ArrayList(java.util.ArrayList) List(java.util.List) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) DomainVlanMapVO(com.cloud.dc.DomainVlanMapVO)

Example 3 with DomainVlanMapVO

use of com.cloud.dc.DomainVlanMapVO in project cloudstack by apache.

the class ConfigurationManagerImpl method releasePublicIpRange.

@DB
public boolean releasePublicIpRange(final long vlanDbId, final long userId, final Account caller) {
    VlanVO vlan = _vlanDao.findById(vlanDbId);
    if (vlan == null) {
        // Nothing to do if vlan can't be found
        s_logger.warn(String.format("Skipping the process for releasing public IP range as could not find a VLAN with ID '%s' for Account '%s' and User '%s'.", vlanDbId, caller, userId));
        return true;
    }
    // Verify range is dedicated
    boolean isAccountSpecific = false;
    final List<AccountVlanMapVO> acctVln = _accountVlanMapDao.listAccountVlanMapsByVlan(vlanDbId);
    // Verify range is dedicated
    if (acctVln != null && !acctVln.isEmpty()) {
        isAccountSpecific = true;
    }
    boolean isDomainSpecific = false;
    final List<DomainVlanMapVO> domainVlan = _domainVlanMapDao.listDomainVlanMapsByVlan(vlanDbId);
    // Check for domain wide pool. It will have an entry for domain_vlan_map.
    if (domainVlan != null && !domainVlan.isEmpty()) {
        isDomainSpecific = true;
    }
    if (!isAccountSpecific && !isDomainSpecific) {
        throw new InvalidParameterValueException("Can't release Public IP range " + vlanDbId + " as it not dedicated to any domain and any account");
    }
    // Check if range has any allocated public IPs
    final long allocIpCount = _publicIpAddressDao.countIPs(vlan.getDataCenterId(), vlanDbId, true);
    final List<IPAddressVO> ips = _publicIpAddressDao.listByVlanId(vlanDbId);
    boolean success = true;
    final List<IPAddressVO> ipsInUse = new ArrayList<IPAddressVO>();
    if (allocIpCount > 0) {
        try {
            vlan = _vlanDao.acquireInLockTable(vlanDbId, 30);
            if (vlan == null) {
                throw new CloudRuntimeException("Unable to acquire vlan configuration: " + vlanDbId);
            }
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("lock vlan " + vlanDbId + " is acquired");
            }
            for (final IPAddressVO ip : ips) {
                // Disassociate allocated IP's that are not in use
                if (!ip.isOneToOneNat() && !ip.isSourceNat() && !(_firewallDao.countRulesByIpId(ip.getId()) > 0)) {
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug("Releasing Public IP addresses" + ip + " of vlan " + vlanDbId + " as part of Public IP" + " range release to the system pool");
                    }
                    success = success && _ipAddrMgr.disassociatePublicIpAddress(ip.getId(), userId, caller);
                } else {
                    ipsInUse.add(ip);
                }
            }
            if (!success) {
                s_logger.warn("Some Public IP addresses that were not in use failed to be released as a part of" + " vlan " + vlanDbId + "release to the system pool");
            }
        } finally {
            _vlanDao.releaseFromLockTable(vlanDbId);
        }
    }
    // A Public IP range can only be dedicated to one account at a time
    if (isAccountSpecific && _accountVlanMapDao.remove(acctVln.get(0).getId())) {
        // generate usage events to remove dedication for every ip in the range that has been disassociated
        for (final IPAddressVO ip : ips) {
            if (!ipsInUse.contains(ip)) {
                final boolean usageHidden = _ipAddrMgr.isUsageHidden(ip);
                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_RELEASE, acctVln.get(0).getAccountId(), ip.getDataCenterId(), ip.getId(), ip.getAddress().toString(), ip.isSourceNat(), vlan.getVlanType().toString(), ip.getSystem(), usageHidden, ip.getClass().getName(), ip.getUuid());
            }
        }
        // decrement resource count for dedicated public ip's
        _resourceLimitMgr.decrementResourceCount(acctVln.get(0).getAccountId(), ResourceType.public_ip, new Long(ips.size()));
        success = true;
    } else if (isDomainSpecific && _domainVlanMapDao.remove(domainVlan.get(0).getId())) {
        s_logger.debug("Remove the vlan from domain_vlan_map successfully.");
        success = true;
    } else {
        success = false;
    }
    return success;
}
Also used : AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) ArrayList(java.util.ArrayList) DomainVlanMapVO(com.cloud.dc.DomainVlanMapVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) DB(com.cloud.utils.db.DB)

Example 4 with DomainVlanMapVO

use of com.cloud.dc.DomainVlanMapVO in project cloudstack by apache.

the class IpAddressManagerImpl method listAvailablePublicIps.

@Override
public List<IPAddressVO> listAvailablePublicIps(final long dcId, final Long podId, final List<Long> vlanDbIds, final Account owner, final VlanType vlanUse, final Long guestNetworkId, final boolean sourceNat, final boolean assign, final boolean allocate, final String requestedIp, final String requestedGateway, final boolean isSystem, final Long vpcId, final Boolean displayIp, final boolean forSystemVms, final boolean lockOneRow) throws InsufficientAddressCapacityException {
    return Transaction.execute(new TransactionCallbackWithException<List<IPAddressVO>, InsufficientAddressCapacityException>() {

        @Override
        public List<IPAddressVO> doInTransaction(TransactionStatus status) throws InsufficientAddressCapacityException {
            StringBuilder errorMessage = new StringBuilder("Unable to get ip address in ");
            boolean fetchFromDedicatedRange = false;
            List<Long> dedicatedVlanDbIds = new ArrayList<Long>();
            List<Long> nonDedicatedVlanDbIds = new ArrayList<Long>();
            DataCenter zone = _entityMgr.findById(DataCenter.class, dcId);
            SearchCriteria<IPAddressVO> sc = null;
            if (podId != null) {
                sc = AssignIpAddressFromPodVlanSearch.create();
                sc.setJoinParameters("podVlanMapSB", "podId", podId);
                errorMessage.append(" pod id=" + podId);
            } else {
                sc = AssignIpAddressSearch.create();
                errorMessage.append(" zone id=" + dcId);
            }
            // If owner has dedicated Public IP ranges, fetch IP from the dedicated range
            // Otherwise fetch IP from the system pool
            Network network = _networksDao.findById(guestNetworkId);
            // Checking if network is null in the case of system VM's. At the time of allocation of IP address to systemVm, no network is present.
            if (network == null || !(network.getGuestType() == GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced)) {
                List<AccountVlanMapVO> maps = _accountVlanMapDao.listAccountVlanMapsByAccount(owner.getId());
                for (AccountVlanMapVO map : maps) {
                    if (vlanDbIds == null || vlanDbIds.contains(map.getVlanDbId()))
                        dedicatedVlanDbIds.add(map.getVlanDbId());
                }
            }
            List<DomainVlanMapVO> domainMaps = _domainVlanMapDao.listDomainVlanMapsByDomain(owner.getDomainId());
            for (DomainVlanMapVO map : domainMaps) {
                if (vlanDbIds == null || vlanDbIds.contains(map.getVlanDbId()))
                    dedicatedVlanDbIds.add(map.getVlanDbId());
            }
            List<VlanVO> nonDedicatedVlans = _vlanDao.listZoneWideNonDedicatedVlans(dcId);
            for (VlanVO nonDedicatedVlan : nonDedicatedVlans) {
                if (vlanDbIds == null || vlanDbIds.contains(nonDedicatedVlan.getId()))
                    nonDedicatedVlanDbIds.add(nonDedicatedVlan.getId());
            }
            if (vlanUse == VlanType.VirtualNetwork) {
                if (!dedicatedVlanDbIds.isEmpty()) {
                    fetchFromDedicatedRange = true;
                    sc.setParameters("vlanId", dedicatedVlanDbIds.toArray());
                    errorMessage.append(", vlanId id=" + Arrays.toString(dedicatedVlanDbIds.toArray()));
                } else if (!nonDedicatedVlanDbIds.isEmpty()) {
                    sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray());
                    errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray()));
                } else {
                    if (podId != null) {
                        InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", Pod.class, podId);
                        ex.addProxyObject(ApiDBUtils.findPodById(podId).getUuid());
                        throw ex;
                    }
                    s_logger.warn(errorMessage.toString());
                    InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", DataCenter.class, dcId);
                    ex.addProxyObject(ApiDBUtils.findZoneById(dcId).getUuid());
                    throw ex;
                }
            }
            sc.setParameters("dc", dcId);
            // for direct network take ip addresses only from the vlans belonging to the network
            if (vlanUse == VlanType.DirectAttached) {
                sc.setJoinParameters("vlan", "networkId", guestNetworkId);
                errorMessage.append(", network id=" + guestNetworkId);
            }
            if (requestedGateway != null) {
                sc.setJoinParameters("vlan", "vlanGateway", requestedGateway);
                errorMessage.append(", requested gateway=" + requestedGateway);
            }
            sc.setJoinParameters("vlan", "type", vlanUse);
            String routerIpAddress = null;
            if (network != null) {
                NetworkDetailVO routerIpDetail = _networkDetailsDao.findDetail(network.getId(), ApiConstants.ROUTER_IP);
                routerIpAddress = routerIpDetail != null ? routerIpDetail.getValue() : null;
            }
            if (requestedIp != null) {
                sc.addAnd("address", SearchCriteria.Op.EQ, requestedIp);
                errorMessage.append(": requested ip " + requestedIp + " is not available");
            } else if (routerIpAddress != null) {
                sc.addAnd("address", Op.NEQ, routerIpAddress);
            }
            boolean ascOrder = !forSystemVms;
            Filter filter = new Filter(IPAddressVO.class, "forSystemVms", ascOrder, 0l, 1l);
            if (SystemVmPublicIpReservationModeStrictness.value()) {
                sc.setParameters("forSystemVms", forSystemVms);
            }
            filter.addOrderBy(IPAddressVO.class, "vlanId", true);
            List<IPAddressVO> addrs;
            if (lockOneRow) {
                addrs = _ipAddressDao.lockRows(sc, filter, true);
            } else {
                addrs = new ArrayList<>(_ipAddressDao.search(sc, null));
            }
            // If all the dedicated IPs of the owner are in use fetch an IP from the system pool
            if ((!lockOneRow || (lockOneRow && addrs.size() == 0)) && fetchFromDedicatedRange && vlanUse == VlanType.VirtualNetwork) {
                // Verify if account is allowed to acquire IPs from the system
                boolean useSystemIps = UseSystemPublicIps.valueIn(owner.getId());
                if (useSystemIps && !nonDedicatedVlanDbIds.isEmpty()) {
                    fetchFromDedicatedRange = false;
                    sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray());
                    errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray()));
                    if (lockOneRow) {
                        addrs = _ipAddressDao.lockRows(sc, filter, true);
                    } else {
                        addrs.addAll(_ipAddressDao.search(sc, null));
                    }
                }
            }
            if (lockOneRow && addrs.size() == 0) {
                if (podId != null) {
                    InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", Pod.class, podId);
                    // for now, we hardcode the table names, but we should ideally do a lookup for the tablename from the VO object.
                    ex.addProxyObject(ApiDBUtils.findPodById(podId).getUuid());
                    throw ex;
                }
                s_logger.warn(errorMessage.toString());
                InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", DataCenter.class, dcId);
                ex.addProxyObject(ApiDBUtils.findZoneById(dcId).getUuid());
                throw ex;
            }
            if (lockOneRow) {
                assert (addrs.size() == 1) : "Return size is incorrect: " + addrs.size();
            }
            if (assign) {
                assignAndAllocateIpAddressEntry(owner, vlanUse, guestNetworkId, sourceNat, allocate, isSystem, vpcId, displayIp, fetchFromDedicatedRange, addrs);
            }
            return addrs;
        }
    });
}
Also used : Pod(com.cloud.dc.Pod) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) SearchCriteria(com.cloud.utils.db.SearchCriteria) DomainVlanMapVO(com.cloud.dc.DomainVlanMapVO) DataCenter(com.cloud.dc.DataCenter) Filter(com.cloud.utils.db.Filter) ArrayList(java.util.ArrayList) List(java.util.List) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) NetworkDetailVO(com.cloud.network.dao.NetworkDetailVO)

Example 5 with DomainVlanMapVO

use of com.cloud.dc.DomainVlanMapVO in project cloudstack by apache.

the class ManagementServerImpl method searchForVlans.

@Override
public Pair<List<? extends Vlan>, Integer> searchForVlans(final ListVlanIpRangesCmd cmd) {
    // If an account name and domain ID are specified, look up the account
    final String accountName = cmd.getAccountName();
    final Long domainId = cmd.getDomainId();
    Long accountId = null;
    final Long networkId = cmd.getNetworkId();
    final Boolean forVirtual = cmd.isForVirtualNetwork();
    String vlanType = null;
    final Long projectId = cmd.getProjectId();
    final Long physicalNetworkId = cmd.getPhysicalNetworkId();
    if (accountName != null && domainId != null) {
        if (projectId != null) {
            throw new InvalidParameterValueException("Account and projectId can't be specified together");
        }
        final Account account = _accountDao.findActiveAccount(accountName, domainId);
        if (account == null) {
            final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain");
            // Since we don't have a DomainVO object here, we directly set
            // tablename to "domain".
            final DomainVO domain = ApiDBUtils.findDomainById(domainId);
            String domainUuid = domainId.toString();
            if (domain != null) {
                domainUuid = domain.getUuid();
            }
            ex.addProxyObject(domainUuid, "domainId");
            throw ex;
        } else {
            accountId = account.getId();
        }
    }
    if (forVirtual != null) {
        if (forVirtual) {
            vlanType = VlanType.VirtualNetwork.toString();
        } else {
            vlanType = VlanType.DirectAttached.toString();
        }
    }
    // set project information
    if (projectId != null) {
        final Project project = _projectMgr.getProject(projectId);
        if (project == null) {
            final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project by id " + projectId);
            ex.addProxyObject(projectId.toString(), "projectId");
            throw ex;
        }
        accountId = project.getProjectAccountId();
    }
    final Filter searchFilter = new Filter(VlanVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    final Object id = cmd.getId();
    final Object vlan = cmd.getVlan();
    final Object dataCenterId = cmd.getZoneId();
    final Object podId = cmd.getPodId();
    final Object keyword = cmd.getKeyword();
    final SearchBuilder<VlanVO> sb = _vlanDao.createSearchBuilder();
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("vlan", sb.entity().getVlanTag(), SearchCriteria.Op.EQ);
    sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
    sb.and("vlan", sb.entity().getVlanTag(), SearchCriteria.Op.EQ);
    sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ);
    sb.and("vlanType", sb.entity().getVlanType(), SearchCriteria.Op.EQ);
    sb.and("physicalNetworkId", sb.entity().getPhysicalNetworkId(), SearchCriteria.Op.EQ);
    if (accountId != null) {
        final SearchBuilder<AccountVlanMapVO> accountVlanMapSearch = _accountVlanMapDao.createSearchBuilder();
        accountVlanMapSearch.and("accountId", accountVlanMapSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
        sb.join("accountVlanMapSearch", accountVlanMapSearch, sb.entity().getId(), accountVlanMapSearch.entity().getVlanDbId(), JoinBuilder.JoinType.INNER);
    }
    if (domainId != null) {
        DomainVO domain = ApiDBUtils.findDomainById(domainId);
        if (domain == null) {
            throw new InvalidParameterValueException("Unable to find domain with id " + domainId);
        }
        final SearchBuilder<DomainVlanMapVO> domainVlanMapSearch = _domainVlanMapDao.createSearchBuilder();
        domainVlanMapSearch.and("domainId", domainVlanMapSearch.entity().getDomainId(), SearchCriteria.Op.EQ);
        sb.join("domainVlanMapSearch", domainVlanMapSearch, sb.entity().getId(), domainVlanMapSearch.entity().getVlanDbId(), JoinType.INNER);
    }
    if (podId != null) {
        final SearchBuilder<PodVlanMapVO> podVlanMapSearch = _podVlanMapDao.createSearchBuilder();
        podVlanMapSearch.and("podId", podVlanMapSearch.entity().getPodId(), SearchCriteria.Op.EQ);
        sb.join("podVlanMapSearch", podVlanMapSearch, sb.entity().getId(), podVlanMapSearch.entity().getVlanDbId(), JoinBuilder.JoinType.INNER);
    }
    final SearchCriteria<VlanVO> sc = sb.create();
    if (keyword != null) {
        final SearchCriteria<VlanVO> ssc = _vlanDao.createSearchCriteria();
        ssc.addOr("vlanTag", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("ipRange", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("vlanTag", SearchCriteria.Op.SC, ssc);
    } else {
        if (id != null) {
            sc.setParameters("id", id);
        }
        if (vlan != null) {
            sc.setParameters("vlan", vlan);
        }
        if (dataCenterId != null) {
            sc.setParameters("dataCenterId", dataCenterId);
        }
        if (networkId != null) {
            sc.setParameters("networkId", networkId);
        }
        if (accountId != null) {
            sc.setJoinParameters("accountVlanMapSearch", "accountId", accountId);
        }
        if (podId != null) {
            sc.setJoinParameters("podVlanMapSearch", "podId", podId);
        }
        if (vlanType != null) {
            sc.setParameters("vlanType", vlanType);
        }
        if (physicalNetworkId != null) {
            sc.setParameters("physicalNetworkId", physicalNetworkId);
        }
        if (domainId != null) {
            sc.setJoinParameters("domainVlanMapSearch", "domainId", domainId);
        }
    }
    final Pair<List<VlanVO>, Integer> result = _vlanDao.searchAndCount(sc, searchFilter);
    return new Pair<List<? extends Vlan>, Integer>(result.first(), result.second());
}
Also used : Account(com.cloud.user.Account) AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) DomainVlanMapVO(com.cloud.dc.DomainVlanMapVO) NetworkDomainVO(com.cloud.network.dao.NetworkDomainVO) DomainVO(com.cloud.domain.DomainVO) Project(com.cloud.projects.Project) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Filter(com.cloud.utils.db.Filter) PodVlanMapVO(com.cloud.dc.PodVlanMapVO) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) VlanVO(com.cloud.dc.VlanVO) Pair(com.cloud.utils.Pair) SSHKeyPair(com.cloud.user.SSHKeyPair)

Aggregations

DomainVlanMapVO (com.cloud.dc.DomainVlanMapVO)13 AccountVlanMapVO (com.cloud.dc.AccountVlanMapVO)12 VlanVO (com.cloud.dc.VlanVO)12 IPAddressVO (com.cloud.network.dao.IPAddressVO)9 DB (com.cloud.utils.db.DB)8 ArrayList (java.util.ArrayList)7 TransactionStatus (com.cloud.utils.db.TransactionStatus)6 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)6 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)5 List (java.util.List)5 PodVlanMapVO (com.cloud.dc.PodVlanMapVO)3 ActionEvent (com.cloud.event.ActionEvent)3 Project (com.cloud.projects.Project)3 Account (com.cloud.user.Account)3 Filter (com.cloud.utils.db.Filter)3 SearchCriteria (com.cloud.utils.db.SearchCriteria)3 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)3 DataCenter (com.cloud.dc.DataCenter)2 DataCenterVO (com.cloud.dc.DataCenterVO)2 Pod (com.cloud.dc.Pod)2