Search in sources :

Example 66 with NetworkOfferingVO

use of com.cloud.offerings.NetworkOfferingVO in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method updateGuestNetwork.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true)
public Network updateGuestNetwork(final long networkId, final String name, final String displayText, final Account callerAccount, final User callerUser, final String domainSuffix, final Long networkOfferingId, final Boolean changeCidr, final String guestVmCidr, final Boolean displayNetwork, final String customId, final String dns1, final String dns2, final String ipExclusionList) {
    boolean restartNetwork = false;
    // verify input parameters
    final NetworkVO network = _networksDao.findById(networkId);
    if (network == null) {
        // see NetworkVO.java
        final InvalidParameterValueException ex = new InvalidParameterValueException("Specified network id doesn't exist in the system");
        ex.addProxyObject(String.valueOf(networkId), "networkId");
        throw ex;
    }
    // perform below validation if the network is vpc network
    if (network.getVpcId() != null && networkOfferingId != null) {
        final Vpc vpc = _entityMgr.findById(Vpc.class, network.getVpcId());
        _vpcMgr.validateNtwkOffForNtwkInVpc(networkId, networkOfferingId, null, null, vpc, null, _accountMgr.getAccount(network.getAccountId()), null);
    }
    // don't allow to update network in Destroy state
    if (network.getState() == Network.State.Destroy) {
        throw new InvalidParameterValueException("Don't allow to update network in state " + Network.State.Destroy);
    }
    // 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");
    }
    // allow to upgrade only Guest networks
    if (network.getTrafficType() != Networks.TrafficType.Guest) {
        throw new InvalidParameterValueException("Can't allow networks which traffic type is not " + TrafficType.Guest);
    }
    _accountMgr.checkAccess(callerAccount, null, true, network);
    if (name != null) {
        network.setName(name);
    }
    if (displayText != null) {
        network.setDisplayText(displayText);
    }
    if (customId != null) {
        network.setUuid(customId);
    }
    if (dns1 != null) {
        network.setDns1(dns1);
        restartNetwork = true;
    }
    if (dns2 != null) {
        network.setDns2(dns2);
        restartNetwork = true;
    }
    if (ipExclusionList != null) {
        String networkCidr = null;
        if (guestVmCidr == null) {
            networkCidr = network.getNetworkCidr();
        }
        final List<NicVO> nicsPresent = _nicDao.listByNetworkId(networkId);
        checkIpExclusionList(ipExclusionList, networkCidr, nicsPresent);
        network.setIpExclusionList(ipExclusionList);
    }
    // display flag is not null and has changed
    if (displayNetwork != null && displayNetwork != network.getDisplayNetwork()) {
        // Update resource count if it needs to be updated
        final NetworkOffering networkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
        if (_networkMgr.resourceCountNeedsUpdate(networkOffering, network.getAclType())) {
            _resourceLimitMgr.changeResourceCount(network.getAccountId(), Resource.ResourceType.network, displayNetwork);
        }
        network.setDisplayNetwork(displayNetwork);
    }
    // network offering and domain suffix can be updated for Isolated networks only in 3.0
    if ((networkOfferingId != null || domainSuffix != null) && network.getGuestType() != GuestType.Isolated) {
        throw new InvalidParameterValueException("NetworkOffering and domain suffix upgrade can be perfomed for Isolated networks only");
    }
    boolean networkOfferingChanged = false;
    final long oldNetworkOfferingId = network.getNetworkOfferingId();
    final NetworkOffering oldNtwkOff = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId);
    final NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId);
    if (networkOfferingId != null) {
        if (networkOffering == null || networkOffering.isSystemOnly()) {
            final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering with specified id");
            ex.addProxyObject(networkOfferingId.toString(), "networkOfferingId");
            throw ex;
        }
        // network offering should be in Enabled state
        if (networkOffering.getState() != NetworkOffering.State.Enabled) {
            final InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id is not in " + NetworkOffering.State.Enabled + " state, can't upgrade to it");
            ex.addProxyObject(networkOffering.getUuid(), "networkOfferingId");
            throw ex;
        }
        // can't update from vpc to non-vpc network offering
        final boolean forVpcNew = _configMgr.isOfferingForVpc(networkOffering);
        final boolean vorVpcOriginal = _configMgr.isOfferingForVpc(_entityMgr.findById(NetworkOffering.class, oldNetworkOfferingId));
        if (forVpcNew != vorVpcOriginal) {
            final String errMsg = forVpcNew ? "a vpc offering " : "not a vpc offering";
            throw new InvalidParameterValueException("Can't update as the new offering is " + errMsg);
        }
        if (networkOfferingId != oldNetworkOfferingId) {
            final Collection<String> newProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(networkOffering, network.getPhysicalNetworkId()).values();
            final Collection<String> oldProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(oldNtwkOff, network.getPhysicalNetworkId()).values();
            if (changeCidr) {
                if (!checkForNonStoppedVmInNetwork(network.getId())) {
                    final InvalidParameterValueException ex = new InvalidParameterValueException("All user vm of network of specified id should be stopped before changing " + "CIDR!");
                    ex.addProxyObject(network.getUuid(), "networkId");
                    throw ex;
                }
            }
            // check if the network is upgradable
            if (!canUpgrade(network, oldNetworkOfferingId, networkOfferingId)) {
                throw new InvalidParameterValueException("Can't upgrade from network offering " + oldNtwkOff.getUuid() + " to " + networkOffering.getUuid() + "; check logs for more information");
            }
            restartNetwork = true;
            networkOfferingChanged = true;
            // Setting the new network's isRedundant to the new network offering's RedundantRouter.
            network.setIsRedundant(_networkOfferingDao.findById(networkOfferingId).getRedundantRouter());
        }
    }
    final Map<String, String> newSvcProviders = networkOfferingChanged ? _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()) : new HashMap<>();
    // don't allow to modify network domain if the service is not supported
    if (domainSuffix != null) {
        // validate network domain
        if (!NetUtils.verifyDomainName(domainSuffix)) {
            throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters " + "'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
        }
        long offeringId = oldNetworkOfferingId;
        if (networkOfferingId != null) {
            offeringId = networkOfferingId;
        }
        final Map<Network.Capability, String> dnsCapabilities = getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, offeringId), Service.Dns);
        final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
        if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
            // TBD: use uuid instead of networkOfferingId. May need to hardcode tablename in call to addProxyObject().
            throw new InvalidParameterValueException("Domain name change is not supported by the network offering id=" + networkOfferingId);
        }
        network.setNetworkDomain(domainSuffix);
        // have to restart the network
        restartNetwork = true;
    }
    // IP reservation checks
    // allow reservation only to Isolated Guest networks
    final DataCenter dc = _dcDao.findById(network.getDataCenterId());
    final String networkCidr = network.getNetworkCidr();
    if (guestVmCidr != null) {
        if (dc.getNetworkType() == NetworkType.Basic) {
            throw new InvalidParameterValueException("Guest VM CIDR can't be specified for zone with " + NetworkType.Basic + " networking");
        }
        if (network.getGuestType() != GuestType.Isolated) {
            throw new InvalidParameterValueException("Can only allow IP Reservation in networks with guest type " + GuestType.Isolated);
        }
        if (networkOfferingChanged == true) {
            throw new InvalidParameterValueException("Cannot specify this nework offering change and guestVmCidr at same time. Specify only one.");
        }
        if (!(network.getState() == Network.State.Implemented)) {
            throw new InvalidParameterValueException("The network must be in " + Network.State.Implemented + " state. IP Reservation cannot be applied in " + network.getState() + " state");
        }
        if (!NetUtils.isValidIp4Cidr(guestVmCidr)) {
            throw new InvalidParameterValueException("Invalid format of Guest VM CIDR.");
        }
        if (!NetUtils.validateGuestCidr(guestVmCidr)) {
            throw new InvalidParameterValueException("Invalid format of Guest VM CIDR. Make sure it is RFC1918 compliant. ");
        }
        // But in case networkCidr is a non null value (IP reservation already exists), it implies network cidr is networkCidr
        if (networkCidr != null) {
            if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, networkCidr)) {
                throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR  should be a subset of network CIDR : " + networkCidr);
            }
        } else {
            if (!NetUtils.isNetworkAWithinNetworkB(guestVmCidr, network.getCidr())) {
                throw new InvalidParameterValueException("Invalid value of Guest VM CIDR. For IP Reservation, Guest VM CIDR  should be a subset of network CIDR :  " + network.getCidr());
            }
        }
        // This check makes sure there are no active IPs existing outside the guestVmCidr in the network
        final String[] guestVmCidrPair = guestVmCidr.split("\\/");
        final Long size = Long.valueOf(guestVmCidrPair[1]);
        final List<NicVO> nicsPresent = _nicDao.listByNetworkId(networkId);
        final String[] cidrIpRange = NetUtils.getIpRangeFromCidr(guestVmCidrPair[0], size);
        s_logger.info("The start IP of the specified guest vm cidr is: " + cidrIpRange[0] + " and end IP is: " + cidrIpRange[1]);
        final long startIp = NetUtils.ip2Long(cidrIpRange[0]);
        final long endIp = NetUtils.ip2Long(cidrIpRange[1]);
        final long range = endIp - startIp + 1;
        s_logger.info("The specified guest vm cidr has " + range + " IPs");
        for (final NicVO nic : nicsPresent) {
            final long nicIp = NetUtils.ip2Long(nic.getIPv4Address());
            // check if nic IP is outside the guest vm cidr
            if (nicIp < startIp || nicIp > endIp) {
                if (!(nic.getState() == Nic.State.Deallocating)) {
                    throw new InvalidParameterValueException("Active IPs like " + nic.getIPv4Address() + " exist outside the Guest VM CIDR. Cannot apply reservation ");
                }
            }
        }
        // the IP ranges exactly matches, in these special cases make sure no Reservation gets applied
        if (network.getNetworkCidr() == null) {
            if (NetUtils.isSameIpRange(guestVmCidr, network.getCidr()) && !guestVmCidr.equals(network.getCidr())) {
                throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and CIDR: " + network.getCidr() + " are same, " + "even though both the cidrs appear to be different. As a precaution no IP Reservation will be applied.");
            }
        } else {
            if (NetUtils.isSameIpRange(guestVmCidr, network.getNetworkCidr()) && !guestVmCidr.equals(network.getNetworkCidr())) {
                throw new InvalidParameterValueException("The Start IP and End IP of guestvmcidr: " + guestVmCidr + " and Network CIDR: " + network.getNetworkCidr() + " are same, " + "even though both the cidrs appear to be different. As a precaution IP Reservation will not be affected. If you want to reset IP Reservation, " + "specify guestVmCidr to be: " + network.getNetworkCidr());
            }
        }
        // Populate it with the actual network cidr
        if (network.getNetworkCidr() == null) {
            network.setNetworkCidr(network.getCidr());
        }
        // Condition for IP Reservation reset : guestVmCidr and network CIDR are same
        if (network.getNetworkCidr().equals(guestVmCidr)) {
            s_logger.warn("Guest VM CIDR and Network CIDR both are same, reservation will reset.");
            network.setNetworkCidr(null);
        }
        checkIpExclusionList(ipExclusionList, guestVmCidr, null);
        // Finally update "cidr" with the guestVmCidr
        // which becomes the effective address space for CloudStack guest VMs
        network.setCidr(guestVmCidr);
        _networksDao.update(networkId, network);
        s_logger.info("IP Reservation has been applied. The new CIDR for Guests Vms is " + guestVmCidr);
    }
    final ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount);
    // 1) Shutdown all the elements and cleanup all the rules. Don't allow to shutdown network in intermediate
    // states - Shutdown and Implementing
    final boolean validStateToShutdown = network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State.Allocated;
    if (restartNetwork) {
        if (validStateToShutdown) {
            if (!changeCidr) {
                s_logger.debug("Shutting down elements and resources for network id=" + networkId + " as a part of network update");
                if (!_networkMgr.shutdownNetworkElementsAndResources(context, true, network)) {
                    s_logger.warn("Failed to shutdown the network elements and resources as a part of network restart: " + network);
                    final CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network of " + "specified id");
                    ex.addProxyObject(network.getUuid(), "networkId");
                    throw ex;
                }
            } else {
                // We need to shutdown the network, since we want to re-implement the network.
                s_logger.debug("Shutting down network id=" + networkId + " as a part of network update");
                // check if network has reservation
                if (NetUtils.isNetworkAWithinNetworkB(network.getCidr(), network.getNetworkCidr())) {
                    s_logger.warn("Existing IP reservation will become ineffective for the network with id =  " + networkId + " You need to reapply reservation after network reimplementation.");
                    // set cidr to the newtork cidr
                    network.setCidr(network.getNetworkCidr());
                    // set networkCidr to null to bring network back to no IP reservation state
                    network.setNetworkCidr(null);
                }
                if (!_networkMgr.shutdownNetwork(network.getId(), context, true)) {
                    s_logger.warn("Failed to shutdown the network as a part of update to network with specified id");
                    final CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network as a part of update of specified network id");
                    ex.addProxyObject(network.getUuid(), "networkId");
                    throw ex;
                }
            }
        } else {
            final CloudRuntimeException ex = new CloudRuntimeException("Failed to shutdown the network elements and resources as a part of update to network with specified id; network is in wrong state: " + network.getState());
            ex.addProxyObject(network.getUuid(), "networkId");
            throw ex;
        }
    }
    // 2) Only after all the elements and rules are shutdown properly, update the network VO
    // get updated network
    final Network.State networkState = _networksDao.findById(networkId).getState();
    final boolean validStateToImplement = networkState == Network.State.Implemented || networkState == Network.State.Setup || networkState == Network.State.Allocated;
    if (restartNetwork && !validStateToImplement) {
        final CloudRuntimeException ex = new CloudRuntimeException("Failed to implement the network elements and resources as a part of update to network with specified id; network is in wrong state: " + networkState);
        ex.addProxyObject(network.getUuid(), "networkId");
        throw ex;
    }
    if (networkOfferingId != null) {
        if (networkOfferingChanged) {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    network.setNetworkOfferingId(networkOfferingId);
                    _networksDao.update(networkId, network, newSvcProviders);
                    // get all nics using this network
                    // log remove usage events for old offering
                    // log assign usage events for new offering
                    final List<NicVO> nics = _nicDao.listByNetworkId(networkId);
                    for (final NicVO nic : nics) {
                        final long vmId = nic.getInstanceId();
                        final VMInstanceVO vm = _vmDao.findById(vmId);
                        if (vm == null) {
                            s_logger.error("Vm for nic " + nic.getId() + " not found with Vm Id:" + vmId);
                            continue;
                        }
                        final long isDefault = nic.isDefaultNic() ? 1 : 0;
                        final String nicIdString = Long.toString(nic.getId());
                    }
                }
            });
        } else {
            network.setNetworkOfferingId(networkOfferingId);
            _networksDao.update(networkId, network, _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()));
        }
    } else {
        _networksDao.update(networkId, network);
    }
    // 3) Implement the elements and rules again
    if (restartNetwork) {
        if (network.getState() != Network.State.Allocated) {
            final DeployDestination dest = new DeployDestination(zoneRepository.findOne(network.getDataCenterId()), null, null, null);
            s_logger.debug("Implementing the network " + network + " elements and resources as a part of network update");
            try {
                if (!changeCidr) {
                    _networkMgr.implementNetworkElementsAndResources(dest, context, network, _networkOfferingDao.findById(network.getNetworkOfferingId()));
                } else {
                    _networkMgr.implementNetwork(network.getId(), dest, context);
                }
            } catch (final Exception ex) {
                s_logger.warn("Failed to implement network " + network + " elements and resources as a part of network update due to ", ex);
                final CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of network update");
                e.addProxyObject(network.getUuid(), "networkId");
                throw e;
            }
        }
    }
    // implement the network if its not already
    if (networkOfferingChanged && !oldNtwkOff.getIsPersistent() && networkOffering.getIsPersistent()) {
        if (network.getState() == Network.State.Allocated) {
            try {
                final DeployDestination dest = new DeployDestination(zoneRepository.findOne(network.getDataCenterId()), null, null, null);
                _networkMgr.implementNetwork(network.getId(), dest, context);
            } catch (final Exception ex) {
                s_logger.warn("Failed to implement network " + network + " elements and resources as a part o" + "f network update due to ", ex);
                final CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified" + " id) elements and resources as a part of network " + "update");
                e.addProxyObject(network.getUuid(), "networkId");
                throw e;
            }
        }
    }
    return getNetwork(network.getId());
}
Also used : Vpc(com.cloud.network.vpc.Vpc) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) ReservationContext(com.cloud.vm.ReservationContext) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List) NicVO(com.cloud.vm.NicVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) Capability(com.cloud.network.Network.Capability) NetworkOffering(com.cloud.offering.NetworkOffering) VMInstanceVO(com.cloud.vm.VMInstanceVO) InvalidParameterException(java.security.InvalidParameterException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SQLException(java.sql.SQLException) UnknownHostException(java.net.UnknownHostException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) DataCenter(com.cloud.dc.DataCenter) DeployDestination(com.cloud.deploy.DeployDestination) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 67 with NetworkOfferingVO

use of com.cloud.offerings.NetworkOfferingVO in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method createGuestNetwork.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_CREATE, eventDescription = "creating network")
public Network createGuestNetwork(final CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException {
    final Long networkOfferingId = cmd.getNetworkOfferingId();
    String gateway = cmd.getGateway();
    final String startIP = cmd.getStartIp();
    String endIP = cmd.getEndIp();
    final String netmask = cmd.getNetmask();
    final String networkDomain = cmd.getNetworkDomain();
    final String vlanId = cmd.getVlan();
    final String name = cmd.getNetworkName();
    final String displayText = cmd.getDisplayText();
    final Account caller = CallContext.current().getCallingAccount();
    final Long physicalNetworkId = cmd.getPhysicalNetworkId();
    Long zoneId = cmd.getZoneId();
    final String aclTypeStr = cmd.getAclType();
    final Long domainId = cmd.getDomainId();
    boolean isDomainSpecific = false;
    final Boolean subdomainAccess = cmd.getSubdomainAccess();
    final Long vpcId = cmd.getVpcId();
    final String startIPv6 = cmd.getStartIpv6();
    String endIPv6 = cmd.getEndIpv6();
    String ip6Gateway = cmd.getIp6Gateway();
    final String ip6Cidr = cmd.getIp6Cidr();
    Boolean displayNetwork = cmd.getDisplayNetwork();
    final Long aclId = cmd.getAclId();
    final String isolatedPvlan = cmd.getIsolatedPvlan();
    final String dns1 = cmd.getDns1();
    final String dns2 = cmd.getDns2();
    final String ipExclusionList = cmd.getIpExclusionList();
    // Validate network offering
    final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
    if (ntwkOff == null || ntwkOff.isSystemOnly()) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering by specified id");
        if (ntwkOff != null) {
            ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
        }
        throw ex;
    }
    if (!GuestType.Private.equals(ntwkOff.getGuestType()) && vpcId == null) {
        throw new InvalidParameterValueException("VPC ID is required");
    }
    if (GuestType.Private.equals(ntwkOff.getGuestType()) && (startIP != null || endIP != null || vpcId != null || gateway != null || netmask != null)) {
        throw new InvalidParameterValueException("StartIp/endIp/vpcId/gateway/netmask can't be specified for guest type " + GuestType.Private);
    }
    // validate physical network and zone
    // Check if physical network exists
    PhysicalNetwork pNtwk = null;
    if (physicalNetworkId != null) {
        pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
        if (pNtwk == null) {
            throw new InvalidParameterValueException("Unable to find a physical network having the specified physical network id");
        }
    }
    if (zoneId == null) {
        zoneId = pNtwk.getDataCenterId();
    }
    if (displayNetwork == null) {
        displayNetwork = true;
    }
    final Zone zone = zoneRepository.findOne(zoneId);
    if (zone == null) {
        throw new InvalidParameterValueException("Specified zone id was not found");
    }
    if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
        // See DataCenterVO.java
        final PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation since specified Zone is currently disabled");
        ex.addProxyObject(zone.getUuid(), "zoneId");
        throw ex;
    }
    // Only domain and account ACL types are supported in Acton.
    ACLType aclType = null;
    if (aclTypeStr != null) {
        if (aclTypeStr.equalsIgnoreCase(ACLType.Account.toString())) {
            aclType = ACLType.Account;
        } else if (aclTypeStr.equalsIgnoreCase(ACLType.Domain.toString())) {
            aclType = ACLType.Domain;
        } else {
            throw new InvalidParameterValueException("Incorrect aclType specified. Check the API documentation for supported types");
        }
        // In 3.0 all Shared networks should have aclType == Domain, all Isolated networks aclType==Account
        if (ntwkOff.getGuestType() != GuestType.Shared) {
            if (aclType != ACLType.Account) {
                throw new InvalidParameterValueException("AclType should be " + ACLType.Account + " for network of type " + ntwkOff.getGuestType());
            }
        } else if (ntwkOff.getGuestType() == GuestType.Shared) {
            if (!(aclType == ACLType.Domain || aclType == ACLType.Account)) {
                throw new InvalidParameterValueException("AclType should be " + ACLType.Domain + " or " + ACLType.Account + " for network of type " + Network.GuestType.Shared);
            }
        }
    } else {
        aclType = (ntwkOff.getGuestType() == GuestType.Shared) ? ACLType.Domain : ACLType.Account;
    }
    // Only Admin can create Shared networks
    if (ntwkOff.getGuestType() == GuestType.Shared && !_accountMgr.isAdmin(caller.getId())) {
        throw new InvalidParameterValueException("Only Admins can create network with guest type " + GuestType.Shared);
    }
    // Check if the network is domain specific
    if (aclType == ACLType.Domain) {
        // only Admin can create domain with aclType=Domain
        if (!_accountMgr.isAdmin(caller.getId())) {
            throw new PermissionDeniedException("Only admin can create networks with aclType=Domain");
        }
        // only shared networks can be Domain specific
        if (ntwkOff.getGuestType() != GuestType.Shared) {
            throw new InvalidParameterValueException("Only " + GuestType.Shared + " networks can have aclType=" + ACLType.Domain);
        }
        if (domainId != null) {
            if (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Shared) {
                throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and guest type " + Network.GuestType.Shared);
            }
            final DomainVO domain = _domainDao.findById(domainId);
            if (domain == null) {
                throw new InvalidParameterValueException("Unable to find domain by specified id");
            }
            _accountMgr.checkAccess(caller, domain);
        }
        isDomainSpecific = true;
    } else if (subdomainAccess != null) {
        throw new InvalidParameterValueException("Parameter subDomainAccess can be specified only with aclType=Domain");
    }
    Account owner = null;
    if (cmd.getAccountName() != null && domainId != null || cmd.getProjectId() != null) {
        owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), domainId, cmd.getProjectId());
    } else {
        owner = caller;
    }
    boolean ipv4 = true, ipv6 = false;
    if (startIP != null) {
        ipv4 = true;
    }
    if (startIPv6 != null) {
        ipv6 = true;
    }
    if (gateway != null) {
        try {
            // getByName on a literal representation will only check validity of the address
            // http://docs.oracle.com/javase/6/docs/api/java/net/InetAddress.html#getByName(java.lang.String)
            final InetAddress gatewayAddress = InetAddress.getByName(gateway);
            if (gatewayAddress instanceof Inet6Address) {
                ipv6 = true;
            } else {
                ipv4 = true;
            }
        } catch (final UnknownHostException e) {
            s_logger.error("Unable to convert gateway IP to a InetAddress", e);
            throw new InvalidParameterValueException("Gateway parameter is invalid");
        }
    }
    String cidr = cmd.getCidr();
    if (ipv4) {
        // validate the CIDR
        if (cidr != null && !NetUtils.isValidIp4Cidr(cidr)) {
            throw new InvalidParameterValueException("Invalid format for the CIDR parameter");
        }
        // validate gateway with cidr
        if (cidr != null && gateway != null && !NetUtils.isIpWithtInCidrRange(gateway, cidr)) {
            throw new InvalidParameterValueException("The gateway ip " + gateway + " should be part of the CIDR of the network " + cidr);
        }
        // if end ip is not specified, default it to startIp
        if (startIP != null) {
            if (!NetUtils.isValidIp4(startIP)) {
                throw new InvalidParameterValueException("Invalid format for the startIp parameter");
            }
            if (endIP == null) {
                endIP = startIP;
            } else if (!NetUtils.isValidIp4(endIP)) {
                throw new InvalidParameterValueException("Invalid format for the endIp parameter");
            }
        }
        if (startIP != null && endIP != null) {
            if (!(gateway != null && netmask != null)) {
                throw new InvalidParameterValueException("gateway and netmask should be defined when startIP/endIP are passed in");
            }
        }
        if (gateway != null && netmask != null) {
            if (NetUtils.isNetworkorBroadcastIP(gateway, netmask)) {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("The gateway IP provided is " + gateway + " and netmask is " + netmask + ". The IP is either broadcast or network IP.");
                }
                throw new InvalidParameterValueException("Invalid gateway IP provided. Either the IP is broadcast or network IP.");
            }
            if (!NetUtils.isValidIp4(gateway)) {
                throw new InvalidParameterValueException("Invalid gateway");
            }
            if (!NetUtils.isValidIp4Netmask(netmask)) {
                throw new InvalidParameterValueException("Invalid netmask");
            }
            cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
        }
        checkIpExclusionList(ipExclusionList, cidr, null);
    }
    if (ipv6) {
        // validate the ipv6 CIDR
        if (ip6Cidr != null && !NetUtils.isValidIp4Cidr(ip6Cidr)) {
            throw new InvalidParameterValueException("Invalid format for the CIDR parameter");
        }
        if (endIPv6 == null) {
            endIPv6 = startIPv6;
        }
        _networkModel.checkIp6Parameters(startIPv6, endIPv6, ip6Gateway, ip6Cidr);
        if (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() != Network.GuestType.Shared) {
            throw new InvalidParameterValueException("Can only support create IPv6 network with advance shared network!");
        }
    }
    if (isolatedPvlan != null && (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() != Network.GuestType.Shared)) {
        throw new InvalidParameterValueException("Can only support create Private VLAN network with advance shared network!");
    }
    if (isolatedPvlan != null && ipv6) {
        throw new InvalidParameterValueException("Can only support create Private VLAN network with IPv4!");
    }
    // Regular user can create Guest Isolated Source Nat enabled network only
    if (_accountMgr.isNormalUser(caller.getId()) && (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Isolated && areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
        throw new InvalidParameterValueException("Regular user can create a network only from the network offering having traffic type " + TrafficType.Guest + " and network type " + Network.GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled");
    }
    // Don't allow to specify vlan if the caller is a normal user
    if (_accountMgr.isNormalUser(caller.getId()) && (ntwkOff.getSpecifyVlan() || vlanId != null)) {
        throw new InvalidParameterValueException("Only ROOT admin and domain admins are allowed to specify vlanId");
    }
    if (ipv4) {
        // For non-root admins check cidr limit - if it's allowed by global config value
        if (!_accountMgr.isRootAdmin(caller.getId()) && cidr != null) {
            final String[] cidrPair = cidr.split("\\/");
            final int cidrSize = Integer.parseInt(cidrPair[1]);
            if (cidrSize < _cidrLimit) {
                throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit);
            }
        }
    }
    // Vlan is created in 1 cases - works in Advance zone only:
    // 1) GuestType is Shared
    boolean createVlan = startIP != null && endIP != null && zone.getNetworkType() == NetworkType.Advanced && (ntwkOff.getGuestType() == Network.GuestType.Shared || !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat));
    if (!createVlan) {
        // Only support advance shared network in IPv6, which means createVlan is a must
        if (ipv6) {
            createVlan = true;
        }
    }
    // Can add vlan range only to the network which allows it
    if (createVlan && !ntwkOff.getSpecifyIpRanges()) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id doesn't support adding multiple ip ranges");
        ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
        throw ex;
    }
    if (ntwkOff.getGuestType() != GuestType.Private && gateway == null && cidr != null) {
        gateway = NetUtils.getCidrHostAddress(cidr);
    }
    if (ntwkOff.getGuestType() != GuestType.Private && ip6Gateway == null && ip6Cidr != null) {
        ip6Gateway = NetUtils.getCidrHostAddress6(ip6Cidr);
    }
    Network network = commitNetwork(networkOfferingId, gateway, startIP, endIP, netmask, networkDomain, vlanId, name, displayText, caller, physicalNetworkId, zoneId, domainId, isDomainSpecific, subdomainAccess, vpcId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, displayNetwork, aclId, isolatedPvlan, ntwkOff, pNtwk, aclType, owner, cidr, createVlan, dns1, dns2, ipExclusionList);
    // if the network offering has persistent set to true, implement the network
    if (ntwkOff.getIsPersistent()) {
        try {
            if (network.getState() == Network.State.Setup) {
                s_logger.debug("Network id=" + network.getId() + " is already provisioned");
                return network;
            }
            final DeployDestination dest = new DeployDestination(zone, null, null, null);
            final UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
            final Journal journal = new Journal.LogJournal("Implementing " + network, s_logger);
            final ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), journal, callerUser, caller);
            s_logger.debug("Implementing network " + network + " as a part of network provision for persistent network");
            final Pair<? extends NetworkGuru, ? extends Network> implementedNetwork = _networkMgr.implementNetwork(network.getId(), dest, context);
            if (implementedNetwork == null || implementedNetwork.first() == null) {
                s_logger.warn("Failed to provision the network " + network);
            }
            network = implementedNetwork.second();
        } catch (final ResourceUnavailableException ex) {
            s_logger.warn("Failed to implement persistent guest network " + network + "due to: " + ex.getMessage());
            final CloudRuntimeException e = new CloudRuntimeException("Failed to implement persistent guest network", ex);
            e.addProxyObject(network.getUuid(), "networkId");
            throw e;
        }
    }
    return network;
}
Also used : Account(com.cloud.user.Account) Journal(com.cloud.utils.Journal) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) ReservationContext(com.cloud.vm.ReservationContext) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ACLType(com.cloud.acl.ControlledEntity.ACLType) UnknownHostException(java.net.UnknownHostException) Zone(com.cloud.db.model.Zone) Inet6Address(java.net.Inet6Address) NetworkDomainVO(com.cloud.network.dao.NetworkDomainVO) DomainVO(com.cloud.domain.DomainVO) UserVO(com.cloud.user.UserVO) DeployDestination(com.cloud.deploy.DeployDestination) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) InetAddress(java.net.InetAddress) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 68 with NetworkOfferingVO

use of com.cloud.offerings.NetworkOfferingVO in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method releaseSecondaryIpFromNic.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NIC_SECONDARY_IP_UNASSIGN, eventDescription = "Removing secondary ip " + "from nic", async = true)
public boolean releaseSecondaryIpFromNic(final long ipAddressId) {
    final Account caller = CallContext.current().getCallingAccount();
    boolean success = false;
    // Verify input parameters
    final NicSecondaryIpVO secIpVO = _nicSecondaryIpDao.findById(ipAddressId);
    if (secIpVO == null) {
        throw new InvalidParameterValueException("Unable to find secondary ip address by id");
    }
    final VirtualMachine vm = _userVmDao.findById(secIpVO.getVmId());
    if (vm == null) {
        throw new InvalidParameterValueException("There is no vm with the given secondary ip");
    }
    // verify permissions
    _accountMgr.checkAccess(caller, null, true, vm);
    final Network network = _networksDao.findById(secIpVO.getNetworkId());
    if (network == null) {
        throw new InvalidParameterValueException("Invalid network id is given");
    }
    // Validate network offering
    final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(network.getNetworkOfferingId());
    final Long nicId = secIpVO.getNicId();
    s_logger.debug("ip id = " + ipAddressId + " nic id = " + nicId);
    // check is this the last secondary ip for NIC
    final List<NicSecondaryIpVO> ipList = _nicSecondaryIpDao.listByNicId(nicId);
    boolean lastIp = false;
    if (ipList.size() == 1) {
        // this is the last secondary ip to nic
        lastIp = true;
    }
    final DataCenter dc = _dcDao.findById(network.getDataCenterId());
    if (dc == null) {
        throw new InvalidParameterValueException("Invalid zone Id is given");
    }
    s_logger.debug("Calling secondary ip " + secIpVO.getIp4Address() + " release ");
    if (dc.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) {
        // check PF or static NAT is configured on this ip address
        final String secondaryIp = secIpVO.getIp4Address();
        final List<FirewallRuleVO> fwRulesList = _firewallDao.listByNetworkAndPurpose(network.getId(), Purpose.PortForwarding);
        if (fwRulesList.size() != 0) {
            for (final FirewallRuleVO rule : fwRulesList) {
                if (_portForwardingDao.findByIdAndIp(rule.getId(), secondaryIp) != null) {
                    s_logger.debug("VM nic IP " + secondaryIp + " is associated with the port forwarding rule");
                    throw new InvalidParameterValueException("Can't remove the secondary ip " + secondaryIp + " is associate with the port forwarding rule");
                }
            }
        }
        // check if the secondary ip associated with any static nat rule
        final IPAddressVO publicIpVO = _ipAddressDao.findByIpAndNetworkId(secIpVO.getNetworkId(), secondaryIp);
        if (publicIpVO != null) {
            s_logger.debug("VM nic IP " + secondaryIp + " is associated with the static NAT rule public IP address id " + publicIpVO.getId());
            throw new InvalidParameterValueException("Can' remove the ip " + secondaryIp + "is associate with static NAT rule public IP address id " + publicIpVO.getId());
        }
        if (_lbService.isLbRuleMappedToVmGuestIp(secondaryIp)) {
            s_logger.debug("VM nic IP " + secondaryIp + " is mapped to load balancing rule");
            throw new InvalidParameterValueException("Can't remove the secondary ip " + secondaryIp + " is mapped to load balancing rule");
        }
    } else if (dc.getNetworkType() == NetworkType.Basic || ntwkOff.getGuestType() == Network.GuestType.Shared) {
        final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(secIpVO.getNetworkId(), secIpVO.getIp4Address());
        if (ip != null) {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    _ipAddrMgr.markIpAsUnavailable(ip.getId());
                    _ipAddressDao.unassignIpAddress(ip.getId());
                }
            });
        }
    } else if (network.getTrafficType() == TrafficType.Public) {
        final IPAddressVO publicIpVO = _ipAddressDao.findByIpAndSourceNetworkId(secIpVO.getNetworkId(), secIpVO.getIp4Address());
        final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
        final Account callerAccount = _accountMgr.getActiveAccountById(callerUser.getAccountId());
        _ipAddrMgr.disassociatePublicIpAddress(publicIpVO.getId(), callerUser.getId(), callerAccount);
    } else {
        throw new InvalidParameterValueException("Not supported for this network now");
    }
    success = removeNicSecondaryIP(secIpVO, lastIp);
    return success;
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) NicSecondaryIpVO(com.cloud.vm.dao.NicSecondaryIpVO) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) VirtualMachine(com.cloud.vm.VirtualMachine) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 69 with NetworkOfferingVO

use of com.cloud.offerings.NetworkOfferingVO in project cosmic by MissionCriticalCloud.

the class VirtualRouterElement method prepare.

@Override
public boolean prepare(final Network network, final NicProfile nic, final VirtualMachineProfile vm, final DeployDestination dest, final ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException, IllegalVirtualMachineException {
    if (vm.getType() != VirtualMachine.Type.User) {
        throw new IllegalVirtualMachineException("Illegal VM type informed. Expected USER VM, but got: " + vm.getType());
    }
    if (!canHandle(network, null)) {
        return false;
    }
    final NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
    if (offering.isSystemOnly()) {
        return false;
    }
    if (!_networkMdl.isProviderEnabledInPhysicalNetwork(_networkMdl.getPhysicalNetworkId(network), getProvider().getName())) {
        return false;
    }
    final RouterDeploymentDefinition routerDeploymentDefinition = routerDeploymentDefinitionBuilder.create().setGuestNetwork(network).setDeployDestination(dest).setAccountOwner(_accountMgr.getAccount(network.getAccountId())).setParams(vm.getParameters()).build();
    final List<DomainRouterVO> routers = routerDeploymentDefinition.deployVirtualRouter();
    if (routers == null || routers.size() == 0) {
        throw new ResourceUnavailableException("Can't find at least one running router!", DataCenter.class, network.getDataCenterId());
    }
    return true;
}
Also used : RouterDeploymentDefinition(com.cloud.network.router.deployment.RouterDeploymentDefinition) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) IllegalVirtualMachineException(com.cloud.exception.IllegalVirtualMachineException) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 70 with NetworkOfferingVO

use of com.cloud.offerings.NetworkOfferingVO 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.user.Account) ArrayList(java.util.ArrayList) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair) NetworkOffering(com.cloud.offering.NetworkOffering) Service(com.cloud.network.Network.Service) NetworkOrchestrationService(com.cloud.engine.orchestration.service.NetworkOrchestrationService) NetworkService(com.cloud.network.NetworkService) ManagementService(com.cloud.server.ManagementService) ResourceLimitService(com.cloud.user.ResourceLimitService) AffinityGroupService(com.cloud.affinity.AffinityGroupService) DataCenter(com.cloud.dc.DataCenter) Filter(com.cloud.utils.db.Filter) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO)

Aggregations

NetworkOfferingVO (com.cloud.offerings.NetworkOfferingVO)128 NetworkVO (com.cloud.network.dao.NetworkVO)45 ArrayList (java.util.ArrayList)34 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)32 Network (com.cloud.network.Network)27 DB (com.cloud.utils.db.DB)27 Test (org.junit.Test)27 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)26 Service (com.cloud.network.Network.Service)26 Account (com.cloud.user.Account)24 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)23 Provider (com.cloud.network.Network.Provider)22 PhysicalNetwork (com.cloud.network.PhysicalNetwork)21 HashSet (java.util.HashSet)21 TransactionStatus (com.cloud.utils.db.TransactionStatus)20 HashMap (java.util.HashMap)20 Set (java.util.Set)20 DataCenterVO (com.cloud.dc.DataCenterVO)19 NetworkOffering (com.cloud.offering.NetworkOffering)19 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)18