Search in sources :

Example 21 with NetworkOfferingVO

use of com.cloud.offerings.NetworkOfferingVO in project cloudstack by apache.

the class NetworkServiceImpl method updateGuestNetwork.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_UPDATE, eventDescription = "updating network", async = true)
public Network updateGuestNetwork(final UpdateNetworkCmd cmd) {
    User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId());
    Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId());
    final long networkId = cmd.getId();
    String name = cmd.getNetworkName();
    String displayText = cmd.getDisplayText();
    String domainSuffix = cmd.getNetworkDomain();
    final Long networkOfferingId = cmd.getNetworkOfferingId();
    Boolean changeCidr = cmd.getChangeCidr();
    String guestVmCidr = cmd.getGuestVmCidr();
    Boolean displayNetwork = cmd.getDisplayNetwork();
    String customId = cmd.getCustomId();
    boolean updateInSequence = cmd.getUpdateInSequence();
    boolean forced = cmd.getForced();
    boolean restartNetwork = false;
    // verify input parameters
    final NetworkVO network = getNetworkVO(networkId, "Specified network id doesn't exist in the system");
    // perform below validation if the network is vpc network
    if (network.getVpcId() != null && networkOfferingId != null) {
        Vpc vpc = _entityMgr.findById(Vpc.class, network.getVpcId());
        _vpcMgr.validateNtwkOffForNtwkInVpc(networkId, networkOfferingId, null, null, vpc, null, _accountMgr.getAccount(network.getAccountId()), network.getNetworkACLId());
    }
    // 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
    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);
    _accountMgr.checkAccess(_accountMgr.getActiveAccountById(network.getAccountId()), offering, _dcDao.findById(network.getDataCenterId()));
    if (cmd instanceof UpdateNetworkCmdByAdmin) {
        final Boolean hideIpAddressUsage = ((UpdateNetworkCmdByAdmin) cmd).getHideIpAddressUsage();
        if (hideIpAddressUsage != null) {
            final NetworkDetailVO detail = _networkDetailsDao.findDetail(network.getId(), Network.hideIpAddressUsage);
            if (detail != null) {
                detail.setValue(hideIpAddressUsage.toString());
                _networkDetailsDao.update(detail.getId(), detail);
            } else {
                _networkDetailsDao.persist(new NetworkDetailVO(network.getId(), Network.hideIpAddressUsage, hideIpAddressUsage.toString(), false));
            }
        }
    }
    if (name != null) {
        network.setName(name);
    }
    if (displayText != null) {
        network.setDisplayText(displayText);
    }
    if (customId != null) {
        network.setUuid(customId);
    }
    // display flag is not null and has changed
    if (displayNetwork != null && displayNetwork != network.getDisplayNetwork()) {
        // Update resource count if it needs to be updated
        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();
    NetworkOffering oldNtwkOff = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId);
    NetworkOfferingVO networkOffering = _networkOfferingDao.findById(networkOfferingId);
    if (networkOfferingId != null) {
        if (networkOffering == null || networkOffering.isSystemOnly()) {
            throwInvalidIdException("Unable to find network offering with specified id", networkOfferingId.toString(), "networkOfferingId");
        }
        // network offering should be in Enabled state
        if (networkOffering.getState() != NetworkOffering.State.Enabled) {
            throwInvalidIdException("Network offering with specified id is not in " + NetworkOffering.State.Enabled + " state, can't upgrade to it", networkOffering.getUuid(), "networkOfferingId");
        }
        // can't update from vpc to non-vpc network offering
        boolean forVpcNew = _configMgr.isOfferingForVpc(networkOffering);
        boolean vorVpcOriginal = _configMgr.isOfferingForVpc(_entityMgr.findById(NetworkOffering.class, oldNetworkOfferingId));
        if (forVpcNew != vorVpcOriginal) {
            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) {
            Collection<String> newProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(networkOffering, network.getPhysicalNetworkId()).values();
            Collection<String> oldProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(oldNtwkOff, network.getPhysicalNetworkId()).values();
            if (providersConfiguredForExternalNetworking(newProviders) != providersConfiguredForExternalNetworking(oldProviders) && !changeCidr) {
                throw new InvalidParameterValueException("Updating network failed since guest CIDR needs to be changed!");
            }
            if (changeCidr) {
                if (!checkForNonStoppedVmInNetwork(network.getId())) {
                    throwInvalidIdException("All user vm of network of specified id should be stopped before changing CIDR!", network.getUuid(), "networkId");
                }
            }
            // 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 isReduntant to the new network offering's RedundantRouter.
            network.setRedundant(_networkOfferingDao.findById(networkOfferingId).isRedundantRouter());
        }
    }
    final Map<String, String> newSvcProviders = networkOfferingChanged ? _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()) : new HashMap<String, String>();
    // 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;
        }
        Map<Network.Capability, String> dnsCapabilities = getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, offeringId), Service.Dns);
        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
    DataCenter dc = _dcDao.findById(network.getDataCenterId());
    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) {
            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
        String[] guestVmCidrPair = guestVmCidr.split("\\/");
        Long size = Long.valueOf(guestVmCidrPair[1]);
        List<NicVO> nicsPresent = _nicDao.listByNetworkId(networkId);
        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]);
        long startIp = NetUtils.ip2Long(cidrIpRange[0]);
        long endIp = NetUtils.ip2Long(cidrIpRange[1]);
        long range = endIp - startIp + 1;
        s_logger.info("The specified guest vm cidr has " + range + " IPs");
        for (NicVO nic : nicsPresent) {
            long nicIp = NetUtils.ip2Long(nic.getIPv4Address());
            // check if nic IP is outside the guest vm cidr
            if ((nicIp < startIp || nicIp > endIp) && 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);
        }
        // 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);
    }
    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
    int resourceCount = 1;
    if (updateInSequence && restartNetwork && _networkOfferingDao.findById(network.getNetworkOfferingId()).isRedundantRouter() && (networkOfferingId == null || _networkOfferingDao.findById(networkOfferingId).isRedundantRouter()) && network.getVpcId() == null) {
        _networkMgr.canUpdateInSequence(network, forced);
        NetworkDetailVO networkDetail = new NetworkDetailVO(network.getId(), Network.updatingInSequence, "true", true);
        _networkDetailsDao.persist(networkDetail);
        _networkMgr.configureUpdateInSequence(network);
        resourceCount = _networkMgr.getResourceCount(network);
    }
    List<String> servicesNotInNewOffering = null;
    if (networkOfferingId != null) {
        servicesNotInNewOffering = _networkMgr.getServicesNotSupportedInNewOffering(network, networkOfferingId);
    }
    if (!forced && servicesNotInNewOffering != null && !servicesNotInNewOffering.isEmpty()) {
        NetworkOfferingVO newOffering = _networkOfferingDao.findById(networkOfferingId);
        throw new CloudRuntimeException("The new offering:" + newOffering.getUniqueName() + " will remove the following services " + servicesNotInNewOffering + "along with all the related configuration currently in use. will not proceed with the network update." + "set forced parameter to true for forcing an update.");
    }
    try {
        if (servicesNotInNewOffering != null && !servicesNotInNewOffering.isEmpty()) {
            _networkMgr.cleanupConfigForServicesInNetwork(servicesNotInNewOffering, network);
        }
    } catch (Throwable e) {
        s_logger.debug("failed to cleanup config related to unused services error:" + e.getMessage());
    }
    boolean validStateToShutdown = (network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup || network.getState() == Network.State.Allocated);
    try {
        do {
            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);
                            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");
                            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 {
                    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
            Network.State networkState = _networksDao.findById(networkId).getState();
            boolean validStateToImplement = (networkState == Network.State.Implemented || networkState == Network.State.Setup || networkState == Network.State.Allocated);
            if (restartNetwork && !validStateToImplement) {
                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(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
                            List<NicVO> nics = _nicDao.listByNetworkId(networkId);
                            for (NicVO nic : nics) {
                                if (nic.getReservationStrategy() == Nic.ReservationStrategy.PlaceHolder) {
                                    continue;
                                }
                                long vmId = nic.getInstanceId();
                                VMInstanceVO vm = _vmDao.findById(vmId);
                                if (vm == null) {
                                    s_logger.error("Vm for nic " + nic.getId() + " not found with Vm Id:" + vmId);
                                    continue;
                                }
                                long isDefault = (nic.isDefaultNic()) ? 1 : 0;
                                String nicIdString = Long.toString(nic.getId());
                                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), nicIdString, oldNetworkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplay());
                                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), nicIdString, networkOfferingId, null, isDefault, VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplay());
                            }
                        }
                    });
                } 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) {
                    DeployDestination dest = new DeployDestination(_dcDao.findById(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 (Exception ex) {
                        s_logger.warn("Failed to implement network " + network + " elements and resources as a part of network update due to ", ex);
                        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;
                    }
                }
                if (networkOfferingChanged) {
                    replugNicsForUpdatedNetwork(network);
                }
            }
            // implement the network if its not already
            if (networkOfferingChanged && !oldNtwkOff.isPersistent() && networkOffering.isPersistent()) {
                if (network.getState() == Network.State.Allocated) {
                    try {
                        DeployDestination dest = new DeployDestination(_dcDao.findById(network.getDataCenterId()), null, null, null);
                        _networkMgr.implementNetwork(network.getId(), dest, context);
                    } catch (Exception ex) {
                        s_logger.warn("Failed to implement network " + network + " elements and resources as a part o" + "f network update due to ", ex);
                        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;
                    }
                }
            }
            resourceCount--;
        } while (updateInSequence && resourceCount > 0);
    } catch (Exception exception) {
        if (updateInSequence) {
            _networkMgr.finalizeUpdateInSequence(network, false);
        }
        throw new CloudRuntimeException("failed to update network " + network.getUuid() + " due to " + exception.getMessage());
    } finally {
        if (updateInSequence) {
            if (_networkDetailsDao.findDetail(networkId, Network.updatingInSequence) != null) {
                _networkDetailsDao.removeDetail(networkId, Network.updatingInSequence);
            }
        }
    }
    return getNetwork(network.getId());
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) Vpc(com.cloud.network.vpc.Vpc) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) UpdateNetworkCmdByAdmin(org.apache.cloudstack.api.command.admin.network.UpdateNetworkCmdByAdmin) ReservationContext(com.cloud.vm.ReservationContext) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List) NetworkDetailVO(com.cloud.network.dao.NetworkDetailVO) 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) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) 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 22 with NetworkOfferingVO

use of com.cloud.offerings.NetworkOfferingVO in project cloudstack by apache.

the class NetworkServiceImpl method migrateVpcNetwork.

@Override
public Vpc migrateVpcNetwork(long vpcId, long vpcOfferingId, Map<String, String> networkToOffering, Account account, User callerUser, boolean resume) {
    // Check if a previous migration run failed and try to resume if resume = true
    ResourceTag relatedVpc = _resourceTagDao.findByKey(vpcId, ResourceObjectType.Vpc, NetworkMigrationManager.MIGRATION);
    long vpcCopyId = 0;
    /*
         * In the vpc migration process the newly created Vpc will be used as the new VPC (opposed to network tier migration).
         * In case the copy of the vpc was already created. The uuid where already swapped and the id we receive here is the id of the Copy!
         * The id stored in the resource tag table under the key "migration" is the id of the ORIGINAL vpc!
         */
    if (relatedVpc != null) {
        if (resume) {
            vpcCopyId = vpcId;
            vpcId = Long.parseLong(relatedVpc.getValue());
            // let's check if the user did not change the vpcoffering opposed to the last failed run.
            verifyAlreadyMigratedTiers(vpcCopyId, vpcOfferingId, networkToOffering);
        } else {
            s_logger.warn("This vpc has a migration row in the resource details table. You might want to re-run migration with resume = true command.");
            throw new CloudRuntimeException("Failed to migrate VPC as previous migration left this VPC in transient condition. Specify resume as true.");
        }
    }
    Vpc vpc = _vpcDao.findById(vpcId);
    _accountMgr.checkAccess(account, null, true, vpc);
    _accountMgr.checkAccess(account, _vpcOfferingDao.findById(vpcOfferingId), _dcDao.findById(vpc.getZoneId()));
    if (vpc.getVpcOfferingId() == vpcOfferingId) {
        return vpc;
    }
    // Try to fail fast, check networks in the VPC and if we can migrate them before proceeding.
    List<NetworkVO> tiersInVpc = _networksDao.listByVpc(vpcId);
    vpcTiersCanBeMigrated(tiersInVpc, account, networkToOffering, resume);
    // In case this is the first time we try to migrate this vpc
    if (relatedVpc == null) {
        final long vpcIdFinal = vpcId;
        vpcCopyId = Transaction.execute((TransactionCallback<Long>) (status) -> _networkMigrationManager.makeCopyOfVpc(vpcIdFinal, vpcOfferingId));
    }
    Vpc copyOfVpc = _vpcDao.findById(vpcCopyId);
    _networkMigrationManager.startVpc(copyOfVpc);
    for (Network tier : tiersInVpc) {
        String networkOfferingUuid = networkToOffering.get(tier.getUuid());
        // UUID may be swapped already with a new uuid due to previous migration failure.
        // So we check the related network also in case we don't find the network offering
        Long networkId = null;
        if (resume && networkOfferingUuid == null) {
            tier = _networksDao.findById(tier.getRelated());
            networkOfferingUuid = networkToOffering.get(tier.getUuid());
            // In this case the tier already exists so we need to get the id of the tier so we can validate correctly
            networkId = tier.getId();
        }
        NetworkOfferingVO newNtwkOff = _networkOfferingDao.findByUuid(networkOfferingUuid);
        Account networkAccount = _accountService.getActiveAccountById(tier.getAccountId());
        try {
            _vpcMgr.validateNtwkOffForNtwkInVpc(networkId, newNtwkOff.getId(), tier.getCidr(), tier.getNetworkDomain(), copyOfVpc, tier.getGateway(), networkAccount, tier.getNetworkACLId());
        } catch (InvalidParameterValueException e) {
            s_logger.error("Specified network offering can not be used in combination with specified vpc offering. Aborting migration. You can re-run with resume = true and the correct uuid.");
            throw e;
        }
        long newPhysicalNetworkId = findPhysicalNetworkId(tier.getDataCenterId(), newNtwkOff.getTags(), newNtwkOff.getTrafficType());
        final long oldNetworkOfferingId = tier.getNetworkOfferingId();
        NetworkOffering oldNtwkOff = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId);
        if (networkNeedsMigration(tier, newPhysicalNetworkId, oldNtwkOff, newNtwkOff) || (resume && tier.getRelated() != tier.getId())) {
            migrateNetworkToPhysicalNetwork(tier, oldNtwkOff, newNtwkOff, vpcId, vpcCopyId, newPhysicalNetworkId, account, callerUser);
        }
    }
    _networkMigrationManager.deleteCopyOfVpc(vpcId, vpcCopyId);
    return _vpcDao.findById(vpcCopyId);
}
Also used : Account(com.cloud.user.Account) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkOffering(com.cloud.offering.NetworkOffering) Vpc(com.cloud.network.vpc.Vpc) TransactionCallback(com.cloud.utils.db.TransactionCallback) ResourceTag(com.cloud.server.ResourceTag) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO)

Example 23 with NetworkOfferingVO

use of com.cloud.offerings.NetworkOfferingVO in project cloudstack by apache.

the class NetworkServiceImpl method createPrivateNetwork.

@Override
@DB
public Network createPrivateNetwork(final String networkName, final String displayText, long physicalNetworkId, String broadcastUriString, final String startIp, String endIp, final String gateway, String netmask, final long networkOwnerId, final Long vpcId, final Boolean sourceNat, final Long networkOfferingId, final Boolean bypassVlanOverlapCheck) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
    final Account owner = _accountMgr.getAccount(networkOwnerId);
    // Get system network offering
    NetworkOfferingVO ntwkOff = null;
    if (networkOfferingId != null) {
        ntwkOff = _networkOfferingDao.findById(networkOfferingId);
    }
    if (ntwkOff == null) {
        ntwkOff = findSystemNetworkOffering(NetworkOffering.SystemPrivateGatewayNetworkOffering);
    }
    // Validate physical network
    final PhysicalNetwork pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
    if (pNtwk == null) {
        throwInvalidIdException("Unable to find a physical network" + " having the given id", String.valueOf(physicalNetworkId), "physicalNetworkId");
    }
    // if end ip is not specified, default it to startIp
    if (!NetUtils.isValidIp4(startIp)) {
        throw new InvalidParameterValueException("Invalid format for the ip address parameter");
    }
    if (endIp == null) {
        endIp = startIp;
    } else if (!NetUtils.isValidIp4(endIp)) {
        throw new InvalidParameterValueException("Invalid format for the endIp address parameter");
    }
    if (!NetUtils.isValidIp4(gateway)) {
        throw new InvalidParameterValueException("Invalid gateway");
    }
    if (!NetUtils.isValidIp4Netmask(netmask)) {
        throw new InvalidParameterValueException("Invalid netmask");
    }
    final String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
    URI uri = BroadcastDomainType.fromString(broadcastUriString);
    final String uriString = uri.toString();
    BroadcastDomainType tiep = BroadcastDomainType.getSchemeValue(uri);
    // TODO make a test for any supported scheme
    if (!(tiep == BroadcastDomainType.Vlan || tiep == BroadcastDomainType.Lswitch)) {
        throw new InvalidParameterValueException("unsupported type of broadcastUri specified: " + broadcastUriString);
    }
    final NetworkOfferingVO ntwkOffFinal = ntwkOff;
    try {
        return Transaction.execute(new TransactionCallbackWithException<Network, Exception>() {

            @Override
            public Network doInTransaction(TransactionStatus status) throws ResourceAllocationException, InsufficientCapacityException {
                // lock datacenter as we need to get mac address seq from there
                DataCenterVO dc = _dcDao.lockRow(pNtwk.getDataCenterId(), true);
                // check if we need to create guest network
                Network privateNetwork = _networksDao.getPrivateNetwork(uriString, cidr, networkOwnerId, pNtwk.getDataCenterId(), networkOfferingId, vpcId);
                if (privateNetwork == null) {
                    // create Guest network
                    privateNetwork = _networkMgr.createPrivateNetwork(ntwkOffFinal.getId(), networkName, displayText, gateway, cidr, uriString, bypassVlanOverlapCheck, owner, pNtwk, vpcId);
                    if (privateNetwork != null) {
                        s_logger.debug("Successfully created guest network " + privateNetwork);
                    } else {
                        throw new CloudRuntimeException("Creating guest network failed");
                    }
                } else {
                    s_logger.debug("Private network already exists: " + privateNetwork);
                    // Do not allow multiple private gateways with same Vlan within a VPC
                    throw new InvalidParameterValueException("Private network for the vlan: " + uriString + " and cidr  " + cidr + "  already exists " + "for Vpc " + vpcId + " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
                }
                if (vpcId != null) {
                    // add entry to private_ip_address table
                    PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkIdAndVpcId(privateNetwork.getId(), startIp, vpcId);
                    if (privateIp != null) {
                        throw new InvalidParameterValueException("Private ip address " + startIp + " already used for private gateway" + " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
                    }
                    Long mac = dc.getMacAddress();
                    Long nextMac = mac + 1;
                    dc.setMacAddress(nextMac);
                    privateIp = new PrivateIpVO(startIp, privateNetwork.getId(), nextMac, vpcId, sourceNat);
                    _privateIpDao.persist(privateIp);
                    _dcDao.update(dc.getId(), dc);
                }
                s_logger.debug("Private network " + privateNetwork + " is created");
                return privateNetwork;
            }
        });
    } catch (Exception e) {
        ExceptionUtil.rethrowRuntime(e);
        ExceptionUtil.rethrow(e, ResourceAllocationException.class);
        ExceptionUtil.rethrow(e, InsufficientCapacityException.class);
        throw new IllegalStateException(e);
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) TransactionStatus(com.cloud.utils.db.TransactionStatus) PrivateIpVO(com.cloud.network.vpc.PrivateIpVO) URI(java.net.URI) 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) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) BroadcastDomainType(com.cloud.network.Networks.BroadcastDomainType) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) DB(com.cloud.utils.db.DB)

Example 24 with NetworkOfferingVO

use of com.cloud.offerings.NetworkOfferingVO in project cloudstack by apache.

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 {
    if (vm.getType() != VirtualMachine.Type.User || vm.getHypervisorType() == HypervisorType.BareMetal) {
        return false;
    }
    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(org.cloud.network.router.deployment.RouterDeploymentDefinition) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 25 with NetworkOfferingVO

use of com.cloud.offerings.NetworkOfferingVO in project cloudstack by apache.

the class KubernetesClusterManagerImpl method isKubernetesServiceNetworkOfferingConfigured.

private boolean isKubernetesServiceNetworkOfferingConfigured(DataCenter zone) {
    // Check network offering
    String networkOfferingName = KubernetesClusterNetworkOffering.value();
    if (networkOfferingName == null || networkOfferingName.isEmpty()) {
        LOGGER.warn(String.format("Global setting %s is empty. Admin has not yet specified the network offering to be used for provisioning isolated network for the cluster", KubernetesClusterNetworkOffering.key()));
        return false;
    }
    NetworkOfferingVO networkOffering = networkOfferingDao.findByUniqueName(networkOfferingName);
    if (networkOffering == null) {
        LOGGER.warn(String.format("Unable to find the network offering %s to be used for provisioning Kubernetes cluster", networkOfferingName));
        return false;
    }
    if (networkOffering.getState() == NetworkOffering.State.Disabled) {
        LOGGER.warn(String.format("Network offering ID: %s is not enabled", networkOffering.getUuid()));
        return false;
    }
    List<String> services = networkOfferingServiceMapDao.listServicesForNetworkOffering(networkOffering.getId());
    if (services == null || services.isEmpty() || !services.contains("SourceNat")) {
        LOGGER.warn(String.format("Network offering ID: %s does not have necessary services to provision Kubernetes cluster", networkOffering.getUuid()));
        return false;
    }
    if (!networkOffering.isEgressDefaultPolicy()) {
        LOGGER.warn(String.format("Network offering ID: %s has egress default policy turned off should be on to provision Kubernetes cluster", networkOffering.getUuid()));
        return false;
    }
    boolean offeringAvailableForZone = false;
    List<NetworkOfferingJoinVO> networkOfferingJoinVOs = networkOfferingJoinDao.findByZoneId(zone.getId(), true);
    for (NetworkOfferingJoinVO networkOfferingJoinVO : networkOfferingJoinVOs) {
        if (networkOffering.getId() == networkOfferingJoinVO.getId()) {
            offeringAvailableForZone = true;
            break;
        }
    }
    if (!offeringAvailableForZone) {
        LOGGER.warn(String.format("Network offering ID: %s is not available for zone ID: %s", networkOffering.getUuid(), zone.getUuid()));
        return false;
    }
    long physicalNetworkId = networkModel.findPhysicalNetworkId(zone.getId(), networkOffering.getTags(), networkOffering.getTrafficType());
    PhysicalNetwork physicalNetwork = physicalNetworkDao.findById(physicalNetworkId);
    if (physicalNetwork == null) {
        LOGGER.warn(String.format("Unable to find physical network with tag: %s", networkOffering.getTags()));
        return false;
    }
    return true;
}
Also used : PhysicalNetwork(com.cloud.network.PhysicalNetwork) NetworkOfferingJoinVO(com.cloud.api.query.vo.NetworkOfferingJoinVO) 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