Search in sources :

Example 96 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class NetworkOrchestrator method releaseNic.

@DB
protected void releaseNic(final VirtualMachineProfile vmProfile, final long nicId) throws ConcurrentOperationException, ResourceUnavailableException {
    final Pair<Network, NicProfile> networkToRelease = Transaction.execute(new TransactionCallback<Pair<Network, NicProfile>>() {

        @Override
        public Pair<Network, NicProfile> doInTransaction(final TransactionStatus status) {
            final NicVO nic = _nicDao.lockRow(nicId, true);
            if (nic == null) {
                throw new ConcurrentOperationException("Unable to acquire lock on nic " + nic);
            }
            final Nic.State originalState = nic.getState();
            final NetworkVO network = _networksDao.findById(nic.getNetworkId());
            if (originalState == Nic.State.Reserved || originalState == Nic.State.Reserving) {
                if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) {
                    final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
                    nic.setState(Nic.State.Releasing);
                    _nicDao.update(nic.getId(), nic);
                    final NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, _networkModel.getNetworkTag(vmProfile.getHypervisorType(), network));
                    if (guru.release(profile, vmProfile, nic.getReservationId())) {
                        applyProfileToNicForRelease(nic, profile);
                        nic.setState(Nic.State.Allocated);
                        if (originalState == Nic.State.Reserved) {
                            updateNic(nic, network.getId(), -1);
                        } else {
                            _nicDao.update(nic.getId(), nic);
                        }
                    }
                    // Perform release on network elements
                    return new Pair<>(network, profile);
                } else {
                    nic.setState(Nic.State.Allocated);
                    updateNic(nic, network.getId(), -1);
                }
            }
            return null;
        }
    });
    // cleanup the entry in vm_network_map
    if (vmProfile.getType().equals(VirtualMachineType.User)) {
        final NicVO nic = _nicDao.findById(nicId);
        if (nic != null) {
            final NetworkVO vmNetwork = _networksDao.findById(nic.getNetworkId());
            final VMNetworkMapVO vno = _vmNetworkMapDao.findByVmAndNetworkId(vmProfile.getVirtualMachine().getId(), vmNetwork.getId());
            if (vno != null) {
                _vmNetworkMapDao.remove(vno.getId());
            }
        }
    }
    if (networkToRelease != null) {
        final Network network = networkToRelease.first();
        final NicProfile profile = networkToRelease.second();
        final List<Provider> providersToImplement = getNetworkProviders(network.getId());
        for (final NetworkElement element : networkElements) {
            if (providersToImplement.contains(element.getProvider())) {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Asking " + element.getName() + " to release " + profile);
                }
                // NOTE: Context appear to never be used in release method
                // implementations. Consider removing it from interface Element
                element.release(network, profile, vmProfile, null);
            }
        }
    }
}
Also used : PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkGuru(com.cloud.network.guru.NetworkGuru) TransactionStatus(com.cloud.utils.db.TransactionStatus) NicProfile(com.cloud.vm.NicProfile) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) UserDataServiceProvider(com.cloud.network.element.UserDataServiceProvider) LoadBalancingServiceProvider(com.cloud.network.element.LoadBalancingServiceProvider) StaticNatServiceProvider(com.cloud.network.element.StaticNatServiceProvider) Provider(com.cloud.legacymodel.network.Network.Provider) DhcpServiceProvider(com.cloud.network.element.DhcpServiceProvider) NetworkElement(com.cloud.network.element.NetworkElement) RedundantState(com.cloud.legacymodel.network.VirtualRouter.RedundantState) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.legacymodel.network.Network) VMNetworkMapVO(com.cloud.engine.cloud.entity.api.db.VMNetworkMapVO) NicVO(com.cloud.vm.NicVO) Pair(com.cloud.legacymodel.utils.Pair) DB(com.cloud.utils.db.DB)

Example 97 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class NetworkOrchestrator method implementNetwork.

@Override
@DB
public Pair<NetworkGuru, NetworkVO> implementNetwork(final long networkId, final DeployDestination dest, final ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
    final Pair<NetworkGuru, NetworkVO> implemented = new Pair<>(null, null);
    NetworkVO network = _networksDao.findById(networkId);
    final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
    if (isNetworkImplemented(network)) {
        s_logger.debug("Network id=" + networkId + " is already implemented");
        implemented.set(guru, network);
        return implemented;
    }
    // Acquire lock only when network needs to be implemented
    network = _networksDao.acquireInLockTable(networkId, NetworkLockTimeout.value());
    if (network == null) {
        // see NetworkVO.java
        final ConcurrentOperationException ex = new ConcurrentOperationException("Unable to acquire network configuration");
        ex.addProxyObject(_entityMgr.findById(Network.class, networkId).getUuid());
        throw ex;
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Lock is acquired for network id " + networkId + " as a part of network implement");
    }
    try {
        if (isNetworkImplemented(network)) {
            s_logger.debug("Network id=" + networkId + " is already implemented");
            implemented.set(guru, network);
            return implemented;
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Asking " + guru.getName() + " to implement " + network);
        }
        final NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
        network.setReservationId(context.getReservationId());
        if (isSharedNetworkWithServices(network)) {
            network.setState(Network.State.Implementing);
        } else {
            stateTransitTo(network, Event.ImplementNetwork);
        }
        final Network result = guru.implement(network, offering, dest, context);
        network.setCidr(result.getCidr());
        network.setBroadcastUri(result.getBroadcastUri());
        network.setGateway(result.getGateway());
        network.setMode(result.getMode());
        network.setPhysicalNetworkId(result.getPhysicalNetworkId());
        _networksDao.update(networkId, network);
        // implement network elements and re-apply all the network rules
        implementNetworkElementsAndResources(dest, context, network, offering);
        if (isSharedNetworkWithServices(network)) {
            network.setState(Network.State.Implemented);
        } else {
            stateTransitTo(network, Event.OperationSucceeded);
        }
        network.setRestartRequired(false);
        _networksDao.update(network.getId(), network);
        implemented.set(guru, network);
        return implemented;
    } catch (final NoTransitionException e) {
        s_logger.error(e.getMessage());
        return null;
    } finally {
        if (implemented.first() == null) {
            s_logger.debug("Cleaning up because we're unable to implement the network " + network);
            try {
                if (isSharedNetworkWithServices(network)) {
                    network.setState(Network.State.Shutdown);
                    _networksDao.update(networkId, network);
                } else {
                    stateTransitTo(network, Event.OperationFailed);
                }
            } catch (final NoTransitionException e) {
                s_logger.error(e.getMessage());
            }
            try {
                shutdownNetwork(networkId, context, false);
            } catch (final Exception e) {
                // Don't throw this exception as it would hide the original thrown exception, just log
                s_logger.error("Exception caught while shutting down a network as part of a failed implementation", e);
            }
        }
        _networksDao.releaseFromLockTable(networkId);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Lock is released for network id " + networkId + " as a part of network implement");
        }
    }
}
Also used : PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkGuru(com.cloud.network.guru.NetworkGuru) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.legacymodel.network.Network) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) ConnectionException(com.cloud.legacymodel.exceptions.ConnectionException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) InsufficientVirtualNetworkCapacityException(com.cloud.legacymodel.exceptions.InsufficientVirtualNetworkCapacityException) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) IllegalVirtualMachineException(com.cloud.legacymodel.exceptions.IllegalVirtualMachineException) UnsupportedServiceException(com.cloud.legacymodel.exceptions.UnsupportedServiceException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Pair(com.cloud.legacymodel.utils.Pair) DB(com.cloud.utils.db.DB)

Example 98 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class VolumeOrchestrator method recreateVolume.

private Pair<VolumeVO, DataStore> recreateVolume(final VolumeVO vol, final VirtualMachineProfile vm, final DeployDestination dest) throws StorageUnavailableException {
    VolumeVO newVol;
    final boolean recreate = RecreatableSystemVmEnabled.value();
    DataStore destPool = null;
    if (recreate && (dest.getStorageForDisks() == null || dest.getStorageForDisks().get(vol) == null)) {
        destPool = this.dataStoreMgr.getDataStore(vol.getPoolId(), DataStoreRole.Primary);
        s_logger.debug("existing pool: " + destPool.getId());
    } else {
        final StoragePool pool = dest.getStorageForDisks().get(vol);
        destPool = this.dataStoreMgr.getDataStore(pool.getId(), DataStoreRole.Primary);
    }
    if (vol.getState() == Volume.State.Allocated || vol.getState() == Volume.State.Creating) {
        newVol = vol;
    } else {
        newVol = switchVolume(vol, vm);
        // changed
        if (dest.getStorageForDisks() != null && dest.getStorageForDisks().containsKey(vol)) {
            final StoragePool poolWithOldVol = dest.getStorageForDisks().get(vol);
            dest.getStorageForDisks().put(newVol, poolWithOldVol);
            dest.getStorageForDisks().remove(vol);
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Created new volume " + newVol + " for old volume " + vol);
        }
    }
    VolumeInfo volume = this.volFactory.getVolume(newVol.getId(), destPool);
    final Long templateId = newVol.getTemplateId();
    for (int i = 0; i < 2; i++) {
        // retry one more time in case of template reload is required for Vmware case
        AsyncCallFuture<VolumeService.VolumeApiResult> future = null;
        if (templateId == null) {
            final DiskOffering diskOffering = this._entityMgr.findById(DiskOffering.class, volume.getDiskOfferingId());
            final HypervisorType hyperType = vm.getVirtualMachine().getHypervisorType();
            // update the volume's hv_ss_reserve (hypervisor snapshot reserve) from a disk offering (used for managed storage)
            this.volService.updateHypervisorSnapshotReserveForVolume(diskOffering, volume.getId(), hyperType);
            volume = this.volFactory.getVolume(newVol.getId(), destPool);
            future = this.volService.createVolumeAsync(volume, destPool);
        } else {
            final TemplateInfo templ = this.tmplFactory.getReadyTemplateOnImageStore(templateId, dest.getZone().getId());
            if (templ == null) {
                s_logger.debug("can't find ready template: " + templateId + " for data center " + dest.getZone().getId());
                throw new CloudRuntimeException("can't find ready template: " + templateId + " for data center " + dest.getZone().getId());
            }
            final PrimaryDataStore primaryDataStore = (PrimaryDataStore) destPool;
            if (primaryDataStore.isManaged()) {
                final DiskOffering diskOffering = this._entityMgr.findById(DiskOffering.class, volume.getDiskOfferingId());
                final HypervisorType hyperType = vm.getVirtualMachine().getHypervisorType();
                // update the volume's hv_ss_reserve (hypervisor snapshot reserve) from a disk offering (used for managed storage)
                this.volService.updateHypervisorSnapshotReserveForVolume(diskOffering, volume.getId(), hyperType);
                final long hostId = vm.getVirtualMachine().getHostId();
                future = this.volService.createManagedStorageAndVolumeFromTemplateAsync(volume, destPool.getId(), templ, hostId);
            } else {
                future = this.volService.createVolumeFromTemplateAsync(volume, destPool.getId(), templ);
            }
        }
        VolumeService.VolumeApiResult result = null;
        try {
            result = future.get();
            if (result.isFailed()) {
                if (result.getResult().contains("request template reload") && (i == 0)) {
                    s_logger.debug("Retry template re-deploy for vmware");
                    continue;
                } else {
                    s_logger.debug("Unable to create " + newVol + ":" + result.getResult());
                    throw new StorageUnavailableException("Unable to create " + newVol + ":" + result.getResult(), destPool.getId());
                }
            }
            final StoragePoolVO storagePool = this._storagePoolDao.findById(destPool.getId());
            if (storagePool.isManaged()) {
                final long hostId = vm.getVirtualMachine().getHostId();
                final Host host = this._hostDao.findById(hostId);
                this.volService.grantAccess(this.volFactory.getVolume(newVol.getId()), host, destPool);
            }
            newVol = this._volsDao.findById(newVol.getId());
            // break out of template-redeploy retry loop
            break;
        } catch (final InterruptedException e) {
            s_logger.error("Unable to create " + newVol, e);
            throw new StorageUnavailableException("Unable to create " + newVol + ":" + e.toString(), destPool.getId());
        } catch (final ExecutionException e) {
            s_logger.error("Unable to create " + newVol, e);
            throw new StorageUnavailableException("Unable to create " + newVol + ":" + e.toString(), destPool.getId());
        }
    }
    return new Pair<>(newVol, destPool);
}
Also used : StoragePool(com.cloud.legacymodel.storage.StoragePool) DiskOffering(com.cloud.legacymodel.storage.DiskOffering) VolumeInfo(com.cloud.engine.subsystem.api.storage.VolumeInfo) Host(com.cloud.legacymodel.dc.Host) HypervisorType(com.cloud.model.enumeration.HypervisorType) TemplateInfo(com.cloud.engine.subsystem.api.storage.TemplateInfo) VolumeVO(com.cloud.storage.VolumeVO) StorageUnavailableException(com.cloud.legacymodel.exceptions.StorageUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) VolumeService(com.cloud.engine.subsystem.api.storage.VolumeService) DataStore(com.cloud.engine.subsystem.api.storage.DataStore) PrimaryDataStore(com.cloud.engine.subsystem.api.storage.PrimaryDataStore) StoragePoolVO(com.cloud.storage.datastore.db.StoragePoolVO) ExecutionException(java.util.concurrent.ExecutionException) PrimaryDataStore(com.cloud.engine.subsystem.api.storage.PrimaryDataStore) Pair(com.cloud.legacymodel.utils.Pair)

Example 99 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class ConfigurationManagerImpl method validateIpRange.

public Pair<Boolean, Pair<String, String>> validateIpRange(final String startIP, final String endIP, final String newVlanGateway, final String newVlanNetmask, final List<VlanVO> vlans, final boolean ipv4, final boolean ipv6, String ip6Gateway, String ip6Cidr, final String startIPv6, final String endIPv6, final Network network) {
    String vlanGateway = null;
    String vlanNetmask = null;
    boolean sameSubnet = false;
    if (vlans != null && vlans.size() > 0) {
        for (final VlanVO vlan : vlans) {
            if (ipv4) {
                vlanGateway = vlan.getVlanGateway();
                vlanNetmask = vlan.getVlanNetmask();
                // check if subset or super set or neither.
                final NetUtils.SupersetOrSubset val = checkIfSubsetOrSuperset(newVlanGateway, newVlanNetmask, vlan, startIP, endIP);
                if (val == NetUtils.SupersetOrSubset.isSuperset) {
                    // existing subnet.
                    throw new InvalidParameterValueException("The subnet you are trying to add is a superset of the existing subnet having gateway" + vlan.getVlanGateway() + " and netmask  " + vlan.getVlanNetmask());
                } else if (val == NetUtils.SupersetOrSubset.neitherSubetNorSuperset) {
                    // checking with the other subnets.
                    continue;
                } else if (val == NetUtils.SupersetOrSubset.isSubset) {
                    // this means he is trying to add to the same subnet.
                    throw new InvalidParameterValueException("The subnet you are trying to add is a subset of the existing subnet having gateway" + vlan.getVlanGateway() + " and netmask  " + vlan.getVlanNetmask());
                } else if (val == NetUtils.SupersetOrSubset.sameSubnet) {
                    sameSubnet = true;
                    // check if the gateway provided by the user is same as that of the subnet.
                    if (newVlanGateway != null && !newVlanGateway.equals(vlanGateway)) {
                        throw new InvalidParameterValueException("The gateway of the subnet should be unique. The subnet alreaddy has a gateway " + vlanGateway);
                    }
                    break;
                }
            }
            if (ipv6) {
                if (ip6Gateway != null && !ip6Gateway.equals(network.getIp6Gateway())) {
                    throw new InvalidParameterValueException("The input gateway " + ip6Gateway + " is not same as network gateway " + network.getIp6Gateway());
                }
                if (ip6Cidr != null && !ip6Cidr.equals(network.getIp6Cidr())) {
                    throw new InvalidParameterValueException("The input cidr " + ip6Cidr + " is not same as network ciddr " + network.getIp6Cidr());
                }
                ip6Gateway = network.getIp6Gateway();
                ip6Cidr = network.getIp6Cidr();
                _networkModel.checkIp6Parameters(startIPv6, endIPv6, ip6Gateway, ip6Cidr);
                sameSubnet = true;
            }
        }
    }
    if (newVlanGateway == null && newVlanNetmask == null && sameSubnet == false) {
        throw new InvalidParameterValueException("The ip range dose not belong to any of the existing subnets, Provide the netmask and gateway if you want to add new subnet");
    }
    final Pair<String, String> vlanDetails;
    if (sameSubnet) {
        vlanDetails = new Pair<>(vlanGateway, vlanNetmask);
    } else {
        vlanDetails = new Pair<>(newVlanGateway, newVlanNetmask);
    }
    // check if the gatewayip is the part of the ip range being added.
    if (ipv4 && NetUtils.ipRangesOverlap(startIP, endIP, vlanDetails.first(), vlanDetails.first())) {
        throw new InvalidParameterValueException("The gateway ip should not be the part of the ip range being added.");
    }
    final Pair<Boolean, Pair<String, String>> result = new Pair<>(sameSubnet, vlanDetails);
    return result;
}
Also used : NetUtils(com.cloud.utils.net.NetUtils) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) VlanVO(com.cloud.dc.VlanVO) Pair(com.cloud.legacymodel.utils.Pair)

Example 100 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class ConfigurationManagerImpl method searchForNetworkOfferings.

@Override
public Pair<List<? extends NetworkOffering>, Integer> searchForNetworkOfferings(final ListNetworkOfferingsCmd cmd) {
    Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
    isAscending = isAscending == null ? Boolean.TRUE : isAscending;
    final Filter searchFilter = new Filter(NetworkOfferingVO.class, "sortKey", isAscending, null, null);
    final Account caller = CallContext.current().getCallingAccount();
    final SearchCriteria<NetworkOfferingVO> sc = _networkOfferingDao.createSearchCriteria();
    final Long id = cmd.getId();
    final Object name = cmd.getNetworkOfferingName();
    final Object displayText = cmd.getDisplayText();
    final Object trafficType = cmd.getTrafficType();
    final Object isDefault = cmd.getIsDefault();
    final Object specifyVlan = cmd.getSpecifyVlan();
    final Object availability = cmd.getAvailability();
    final Object state = cmd.getState();
    final Long zoneId = cmd.getZoneId();
    DataCenter zone = null;
    final Long networkId = cmd.getNetworkId();
    final String guestIpType = cmd.getGuestIpType();
    final List<String> supportedServicesStr = cmd.getSupportedServices();
    final Object specifyIpRanges = cmd.getSpecifyIpRanges();
    final String tags = cmd.getTags();
    final Boolean isTagged = cmd.isTagged();
    final Boolean forVpc = cmd.getForVpc();
    if (zoneId != null) {
        zone = _entityMgr.findById(DataCenter.class, zoneId);
        if (zone == null) {
            throw new InvalidParameterValueException("Unable to find the zone by id=" + zoneId);
        }
    }
    final Object keyword = cmd.getKeyword();
    if (keyword != null) {
        final SearchCriteria<NetworkOfferingVO> ssc = _networkOfferingDao.createSearchCriteria();
        ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }
    if (name != null) {
        sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%");
    }
    if (guestIpType != null) {
        sc.addAnd("guestType", SearchCriteria.Op.EQ, guestIpType);
    }
    if (displayText != null) {
        sc.addAnd("displayText", SearchCriteria.Op.LIKE, "%" + displayText + "%");
    }
    if (trafficType != null) {
        sc.addAnd("trafficType", SearchCriteria.Op.EQ, trafficType);
    }
    if (isDefault != null) {
        sc.addAnd("isDefault", SearchCriteria.Op.EQ, isDefault);
    }
    // only root admin can list network offering with specifyVlan = true
    if (specifyVlan != null) {
        sc.addAnd("specifyVlan", SearchCriteria.Op.EQ, specifyVlan);
    }
    if (availability != null) {
        sc.addAnd("availability", SearchCriteria.Op.EQ, availability);
    }
    if (state != null) {
        sc.addAnd("state", SearchCriteria.Op.EQ, state);
    }
    if (specifyIpRanges != null) {
        sc.addAnd("specifyIpRanges", SearchCriteria.Op.EQ, specifyIpRanges);
    }
    if (zone != null) {
        if (zone.getNetworkType() == NetworkType.Basic) {
            // basic zone, and shouldn't display networkOfferings
            return new Pair<>(new ArrayList<>(), 0);
        }
    }
    // Don't return system network offerings to the user except for private gateway offerings
    if (keyword == null || !keyword.equals("private")) {
        sc.addAnd("systemOnly", SearchCriteria.Op.EQ, false);
    }
    // if networkId is specified, list offerings available for upgrade only
    // (for this network)
    Network network = null;
    if (networkId != null) {
        // check if network exists and the caller can operate with it
        network = _networkModel.getNetwork(networkId);
        if (network == null) {
            throw new InvalidParameterValueException("Unable to find the network by id=" + networkId);
        }
        // Don't allow to update system network
        final NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId());
        if (offering.isSystemOnly()) {
            throw new InvalidParameterValueException("Can't update system networks");
        }
        _accountMgr.checkAccess(caller, null, true, network);
        final List<Long> offeringIds = _networkModel.listNetworkOfferingsForUpgrade(networkId);
        if (!offeringIds.isEmpty()) {
            sc.addAnd("id", SearchCriteria.Op.IN, offeringIds.toArray());
        } else {
            return new Pair<>(new ArrayList<>(), 0);
        }
    }
    if (id != null) {
        sc.addAnd("id", SearchCriteria.Op.EQ, id);
    }
    if (tags != null) {
        sc.addAnd("tags", SearchCriteria.Op.EQ, tags);
    }
    if (isTagged != null) {
        if (isTagged) {
            sc.addAnd("tags", SearchCriteria.Op.NNULL);
        } else {
            sc.addAnd("tags", SearchCriteria.Op.NULL);
        }
    }
    final List<NetworkOfferingVO> offerings = _networkOfferingDao.search(sc, searchFilter);
    final Boolean sourceNatSupported = cmd.getSourceNatSupported();
    final List<String> pNtwkTags = new ArrayList<>();
    boolean checkForTags = false;
    if (zone != null) {
        final List<PhysicalNetworkVO> pNtwks = _physicalNetworkDao.listByZoneAndTrafficType(zoneId, TrafficType.Guest);
        if (pNtwks.size() > 1) {
            checkForTags = true;
            // go through tags
            for (final PhysicalNetworkVO pNtwk : pNtwks) {
                final List<String> pNtwkTag = pNtwk.getTags();
                if (pNtwkTag == null || pNtwkTag.isEmpty()) {
                    throw new CloudRuntimeException("Tags are not defined for physical network in the zone id=" + zoneId);
                }
                pNtwkTags.addAll(pNtwkTag);
            }
        }
    }
    // filter by supported services
    final boolean listBySupportedServices = supportedServicesStr != null && !supportedServicesStr.isEmpty() && !offerings.isEmpty();
    final boolean checkIfProvidersAreEnabled = zoneId != null;
    final boolean parseOfferings = listBySupportedServices || sourceNatSupported != null || checkIfProvidersAreEnabled || forVpc != null || network != null;
    if (parseOfferings) {
        final List<NetworkOfferingVO> supportedOfferings = new ArrayList<>();
        Service[] supportedServices = null;
        if (listBySupportedServices) {
            supportedServices = new Service[supportedServicesStr.size()];
            int i = 0;
            for (final String supportedServiceStr : supportedServicesStr) {
                final Service service = Service.getService(supportedServiceStr);
                if (service == null) {
                    throw new InvalidParameterValueException("Invalid service specified " + supportedServiceStr);
                } else {
                    supportedServices[i] = service;
                }
                i++;
            }
        }
        for (final NetworkOfferingVO offering : offerings) {
            boolean addOffering = true;
            final List<Service> checkForProviders;
            if (checkForTags) {
                if (!pNtwkTags.contains(offering.getTags())) {
                    continue;
                }
            }
            if (listBySupportedServices) {
                addOffering = addOffering && _networkModel.areServicesSupportedByNetworkOffering(offering.getId(), supportedServices);
            }
            if (checkIfProvidersAreEnabled) {
                if (supportedServices != null && supportedServices.length > 0) {
                    checkForProviders = Arrays.asList(supportedServices);
                } else {
                    checkForProviders = _networkModel.listNetworkOfferingServices(offering.getId());
                }
                addOffering = addOffering && _networkModel.areServicesEnabledInZone(zoneId, offering, checkForProviders);
            }
            if (sourceNatSupported != null) {
                addOffering = addOffering && _networkModel.areServicesSupportedByNetworkOffering(offering.getId(), Network.Service.SourceNat) == sourceNatSupported;
            }
            if (forVpc != null) {
                addOffering = addOffering && isOfferingForVpc(offering) == forVpc.booleanValue();
            } else if (network != null) {
                addOffering = addOffering && isOfferingForVpc(offering) == (network.getVpcId() != null);
            }
            if (addOffering) {
                supportedOfferings.add(offering);
            }
        }
        // Now apply pagination
        final List<? extends NetworkOffering> wPagination = StringUtils.applyPagination(supportedOfferings, cmd.getStartIndex(), cmd.getPageSizeVal());
        if (wPagination != null) {
            final Pair<List<? extends NetworkOffering>, Integer> listWPagination = new Pair<>(wPagination, offerings.size());
            return listWPagination;
        }
        return new Pair<>(supportedOfferings, supportedOfferings.size());
    } else {
        final List<? extends NetworkOffering> wPagination = StringUtils.applyPagination(offerings, cmd.getStartIndex(), cmd.getPageSizeVal());
        if (wPagination != null) {
            final Pair<List<? extends NetworkOffering>, Integer> listWPagination = new Pair<>(wPagination, offerings.size());
            return listWPagination;
        }
        return new Pair<>(offerings, offerings.size());
    }
}
Also used : Account(com.cloud.legacymodel.user.Account) ArrayList(java.util.ArrayList) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.legacymodel.network.Network) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.legacymodel.utils.Pair) NetworkOffering(com.cloud.offering.NetworkOffering) NetworkOrchestrationService(com.cloud.engine.orchestration.service.NetworkOrchestrationService) NetworkService(com.cloud.network.NetworkService) ManagementService(com.cloud.server.ManagementService) Service(com.cloud.legacymodel.network.Network.Service) ResourceLimitService(com.cloud.user.ResourceLimitService) AffinityGroupService(com.cloud.affinity.AffinityGroupService) DataCenter(com.cloud.legacymodel.dc.DataCenter) Filter(com.cloud.utils.db.Filter) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO)

Aggregations

Pair (com.cloud.legacymodel.utils.Pair)139 ArrayList (java.util.ArrayList)87 List (java.util.List)64 Account (com.cloud.legacymodel.user.Account)49 Filter (com.cloud.utils.db.Filter)48 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)38 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)27 HashMap (java.util.HashMap)27 Ternary (com.cloud.legacymodel.utils.Ternary)23 ListProjectResourcesCriteria (com.cloud.projects.Project.ListProjectResourcesCriteria)22 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)20 SSHKeyPair (com.cloud.legacymodel.user.SSHKeyPair)16 TemplateFilter (com.cloud.legacymodel.storage.VirtualMachineTemplate.TemplateFilter)13 Map (java.util.Map)13 DB (com.cloud.utils.db.DB)11 DomainVO (com.cloud.domain.DomainVO)10 VolumeVO (com.cloud.storage.VolumeVO)10 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)9 Network (com.cloud.legacymodel.network.Network)9 ResourceTagVO (com.cloud.tags.ResourceTagVO)9