Search in sources :

Example 41 with Vpc

use of com.cloud.legacymodel.network.vpc.Vpc in project cosmic by MissionCriticalCloud.

the class AdvancedVpnRules method accept.

@Override
public boolean accept(final NetworkTopologyVisitor visitor, final VirtualRouter router) throws ResourceUnavailableException {
    _router = router;
    final VpcDao vpcDao = visitor.getVirtualNetworkApplianceFactory().getVpcDao();
    final Vpc vpc = vpcDao.findById(_remoteAccessVpn.getVpcId());
    if (_router.getState() != State.Running) {
        s_logger.warn("Failed to add/remove Remote Access VPN users: router not in running state");
        throw new ResourceUnavailableException("Failed to add/remove Remote Access VPN users: router not in running state: " + router.getState(), DataCenter.class, vpc.getZoneId());
    }
    return visitor.visit(this);
}
Also used : VpcDao(com.cloud.network.vpc.dao.VpcDao) Vpc(com.cloud.legacymodel.network.vpc.Vpc) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException)

Example 42 with Vpc

use of com.cloud.legacymodel.network.vpc.Vpc in project cosmic by MissionCriticalCloud.

the class ApiResponseHelper method createIPAddressResponse.

@Override
public IPAddressResponse createIPAddressResponse(final ResponseView view, final IpAddress ipAddr) {
    final VlanVO vlan = ApiDBUtils.findVlanById(ipAddr.getVlanId());
    final boolean forVirtualNetworks = vlan.getVlanType().equals(VlanType.VirtualNetwork);
    final long zoneId = ipAddr.getDataCenterId();
    final IPAddressResponse ipResponse = new IPAddressResponse();
    ipResponse.setId(ipAddr.getUuid());
    ipResponse.setIpAddress(ipAddr.getAddress().toString());
    if (ipAddr.getAllocatedTime() != null) {
        ipResponse.setAllocated(ipAddr.getAllocatedTime());
    }
    final DataCenter zone = ApiDBUtils.findZoneById(ipAddr.getDataCenterId());
    if (zone != null) {
        ipResponse.setZoneId(zone.getUuid());
        ipResponse.setZoneName(zone.getName());
    }
    ipResponse.setSourceNat(ipAddr.isSourceNat());
    ipResponse.setIsSystem(ipAddr.getSystem());
    // get account information
    if (ipAddr.getAllocatedToAccountId() != null) {
        populateOwner(ipResponse, ipAddr);
    }
    ipResponse.setForVirtualNetwork(forVirtualNetworks);
    ipResponse.setStaticNat(ipAddr.isOneToOneNat());
    if (ipAddr.getAssociatedWithVmId() != null) {
        final UserVm vm = ApiDBUtils.findUserVmById(ipAddr.getAssociatedWithVmId());
        if (vm != null) {
            ipResponse.setVirtualMachineId(vm.getUuid());
            ipResponse.setVirtualMachineName(vm.getHostName());
            if (vm.getDisplayName() != null) {
                ipResponse.setVirtualMachineDisplayName(vm.getDisplayName());
            } else {
                ipResponse.setVirtualMachineDisplayName(vm.getHostName());
            }
        }
    }
    if (ipAddr.getVmIp() != null) {
        ipResponse.setVirtualMachineIp(ipAddr.getVmIp());
    }
    if (ipAddr.getAssociatedWithNetworkId() != null) {
        final Network ntwk = ApiDBUtils.findNetworkById(ipAddr.getAssociatedWithNetworkId());
        if (ntwk != null) {
            ipResponse.setAssociatedNetworkId(ntwk.getUuid());
            ipResponse.setAssociatedNetworkName(ntwk.getName());
        }
    }
    if (ipAddr.getVpcId() != null) {
        final Vpc vpc = ApiDBUtils.findVpcById(ipAddr.getVpcId());
        if (vpc != null) {
            ipResponse.setVpcId(vpc.getUuid());
        }
    }
    // Network id the ip is associated with (if associated networkId is
    // null, try to get this information from vlan)
    final Long vlanNetworkId = ApiDBUtils.getVlanNetworkId(ipAddr.getVlanId());
    // Network id the ip belongs to
    final Long networkId;
    if (vlanNetworkId != null) {
        networkId = vlanNetworkId;
    } else {
        networkId = ApiDBUtils.getPublicNetworkIdByZone(zoneId);
    }
    if (networkId != null) {
        final NetworkVO nw = ApiDBUtils.findNetworkById(networkId);
        if (nw != null) {
            ipResponse.setNetworkId(nw.getUuid());
            ipResponse.setAssociatedNetworkName(nw.getName());
        }
    }
    ipResponse.setState(ipAddr.getState().toString());
    final NetworkACL acl = ApiDBUtils.findByNetworkACLId(ipAddr.getIpACLId());
    if (acl != null) {
        ipResponse.setAclId(acl.getUuid());
        ipResponse.setAclName(acl.getName());
    }
    if (ipAddr.getPhysicalNetworkId() != null) {
        final PhysicalNetworkVO pnw = ApiDBUtils.findPhysicalNetworkById(ipAddr.getPhysicalNetworkId());
        if (pnw != null) {
            ipResponse.setPhysicalNetworkId(pnw.getUuid());
        }
    }
    // show this info to full view only
    if (view == ResponseView.Full) {
        final VlanVO vl = ApiDBUtils.findVlanById(ipAddr.getVlanId());
        if (vl != null) {
            ipResponse.setVlanId(vl.getUuid());
            ipResponse.setVlanName(vl.getVlanTag());
        }
    }
    if (ipAddr.getSystem()) {
        if (ipAddr.isOneToOneNat()) {
            ipResponse.setPurpose(IpAddress.Purpose.StaticNat.toString());
        } else {
            ipResponse.setPurpose(IpAddress.Purpose.Lb.toString());
        }
    }
    ipResponse.setForDisplay(ipAddr.isDisplay());
    // set tag information
    final List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(ResourceObjectType.PublicIpAddress, ipAddr.getId());
    final List<ResourceTagResponse> tagResponses = new ArrayList<>();
    for (final ResourceTag tag : tags) {
        final ResourceTagResponse tagResponse = createResourceTagResponse(tag, true);
        if (tagResponse != null) {
            tagResponses.add(tagResponse);
        }
    }
    ipResponse.setTags(tagResponses);
    ipResponse.setObjectName("ipaddress");
    return ipResponse;
}
Also used : PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) Vpc(com.cloud.legacymodel.network.vpc.Vpc) ArrayList(java.util.ArrayList) NetworkACL(com.cloud.legacymodel.network.vpc.NetworkACL) UserVm(com.cloud.uservm.UserVm) DataCenter(com.cloud.legacymodel.dc.DataCenter) ResourceTag(com.cloud.server.ResourceTag) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.legacymodel.network.Network) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) ResourceTagResponse(com.cloud.api.response.ResourceTagResponse) VlanVO(com.cloud.dc.VlanVO) IPAddressResponse(com.cloud.api.response.IPAddressResponse)

Example 43 with Vpc

use of com.cloud.legacymodel.network.vpc.Vpc 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, final String dhcpTftpServer, final String dhcpBootfileName) {
    Boolean sendNetworkOverview = 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() != 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) {
        sendNetworkOverview = true;
        network.setDns1(dns1);
    }
    if (dns2 != null) {
        sendNetworkOverview = true;
        network.setDns2(dns2);
    }
    if (dhcpTftpServer != null) {
        sendNetworkOverview = true;
        network.setDhcpTftpServer(dhcpTftpServer);
    }
    if (dhcpBootfileName != null) {
        sendNetworkOverview = true;
        network.setDhcpBootfileName(dhcpBootfileName);
    }
    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) {
            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");
            }
            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);
    }
    // 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 network 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);
    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;
                        }
                    }
                }
            });
        } else {
            network.setNetworkOfferingId(networkOfferingId);
            _networksDao.update(networkId, network, _networkMgr.finalizeServicesAndProvidersForNetwork(_entityMgr.findById(NetworkOffering.class, networkOfferingId), network.getPhysicalNetworkId()));
        }
    } else {
        _networksDao.update(networkId, network);
    }
    // if network has been upgraded from a non persistent ntwk offering to a persistent ntwk offering, 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.findById(network.getDataCenterId()).orElse(null), 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;
            }
        }
    }
    if (sendNetworkOverview) {
        final List<DomainRouterVO> routers = _routerDao.listByVpcId(network.getVpcId());
        for (final DomainRouterVO router : routers) {
            final NetworkOverviewTO networkOverview = _commandSetupHelper.createNetworkOverviewFromRouter(router, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), null, null, null);
            try {
                s_logger.warn("Updating network_overview of network " + network + " on router " + router);
                final UpdateNetworkOverviewCommand updateNetworkOverviewCommand = _commandSetupHelper.createUpdateNetworkOverviewCommand(router, networkOverview);
                updateNetworkOverviewCommand.setPlugNics(true);
                final Commands cmds = new Commands(updateNetworkOverviewCommand);
                _networkGeneralHelper.sendCommandsToRouter(router, cmds);
            } catch (final Exception ex) {
                s_logger.warn("Failed to update network_overview of network " + network + " on router " + router + " due to ", ex);
            }
        }
    }
    return getNetwork(network.getId());
}
Also used : Vpc(com.cloud.legacymodel.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.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) NetworkOverviewTO(com.cloud.legacymodel.to.NetworkOverviewTO) Commands(com.cloud.agent.manager.Commands) 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.legacymodel.network.Network.Capability) NetworkOffering(com.cloud.offering.NetworkOffering) VMInstanceVO(com.cloud.vm.VMInstanceVO) UpdateNetworkOverviewCommand(com.cloud.legacymodel.communication.command.UpdateNetworkOverviewCommand) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) InvalidParameterException(java.security.InvalidParameterException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) SQLException(java.sql.SQLException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) UnknownHostException(java.net.UnknownHostException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) UnsupportedServiceException(com.cloud.legacymodel.exceptions.UnsupportedServiceException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) DataCenter(com.cloud.legacymodel.dc.DataCenter) DeployDestination(com.cloud.deploy.DeployDestination) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) DomainRouterVO(com.cloud.vm.DomainRouterVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 44 with Vpc

use of com.cloud.legacymodel.network.vpc.Vpc in project cosmic by MissionCriticalCloud.

the class VpcManagerImpl method createVpcPrivateGateway.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PRIVATE_GATEWAY_CREATE, eventDescription = "creating VPC private gateway", create = true)
public PrivateGateway createVpcPrivateGateway(final long vpcId, final String ipAddress, final String gateway, final String netmask, final long gatewayDomainId, final Long networkId, final Boolean isSourceNat, final Long aclId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
    // Validate parameters
    final Vpc vpc = getActiveVpc(vpcId);
    if (vpc == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC by id specified");
        ex.addProxyObject(String.valueOf(vpcId), "VPC");
        throw ex;
    }
    // permission check on the VPC
    final CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    _accountMgr.checkAccess(caller, null, false, vpc);
    if (gateway != null || netmask != null) {
        throw new InvalidParameterValueException("Gateway/netmask fields are not supported anymore");
    }
    final Network privateNtwk = _ntwkDao.findById(networkId);
    if (privateNtwk == null) {
        throw new InvalidParameterValueException("The private network specified could not be found.");
    }
    if (privateNtwk.getDomainId() != vpc.getDomainId() && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new InvalidParameterValueException("VPC '" + vpc.getName() + "' does not have permission to operate on private network '" + privateNtwk.getName() + "' as they need to belong to the same domain.");
    }
    if (NetUtils.isNetworkAWithinNetworkB(privateNtwk.getCidr(), vpc.getCidr())) {
        throw new InvalidParameterValueException("CIDR of the private network to be connected " + privateNtwk.getCidr() + " should be outside of the VPC super CIDR " + vpc.getCidr());
    }
    if (!NetUtils.isIpWithtInCidrRange(ipAddress, privateNtwk.getCidr())) {
        throw new InvalidParameterValueException("The specified ip address for the private network " + ipAddress + " should be within the CIDR of the private network " + privateNtwk.getCidr());
    }
    final SortedSet<Long> availableIps = _ntwkModel.getAvailableIps(privateNtwk, ipAddress);
    if (availableIps == null || availableIps.isEmpty()) {
        throw new InvalidParameterValueException("The requested ip address " + ipAddress + " is not available in private network " + privateNtwk.getName());
    }
    final Long privateNetworkId = privateNtwk.getId();
    final List<PrivateGateway> privateGateways = getVpcPrivateGateways(vpcId);
    for (final PrivateGateway privateGateway : privateGateways) {
        if (privateNetworkId == privateGateway.getNetworkId()) {
            throw new InvalidParameterValueException("VPC with uuid " + vpc.getUuid() + " is already connected to network '" + privateNtwk.getName() + "'");
        }
    }
    final VpcGatewayVO gatewayVO;
    try {
        gatewayVO = Transaction.execute(new TransactionCallbackWithException<VpcGatewayVO, Exception>() {

            @Override
            public VpcGatewayVO doInTransaction(final TransactionStatus status) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
                // create the nic/ip as createPrivateNetwork doesn't do that work for us now
                s_logger.info("found and using existing network for vpc " + vpc + ": " + privateNtwk.getBroadcastUri());
                final DataCenterVO dc = _dcDao.lockRow(vpc.getZoneId(), true);
                // add entry to private_ip_address table
                PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkId(privateNtwk.getId(), ipAddress);
                if (privateIp != null) {
                    throw new InvalidParameterValueException("Private IP address " + ipAddress + " already used for private gateway in zone " + _entityMgr.findById(DataCenter.class, vpc.getZoneId()).getName());
                }
                final Long mac = dc.getMacAddress();
                final Long nextMac = mac + 1;
                dc.setMacAddress(nextMac);
                s_logger.info("creating private IP address for VPC (" + ipAddress + ", " + privateNtwk.getId() + ", " + nextMac + ", " + vpcId + ", " + isSourceNat + ")");
                privateIp = new PrivateIpVO(ipAddress, privateNtwk.getId(), nextMac, vpcId, isSourceNat);
                _privateIpDao.persist(privateIp);
                _dcDao.update(dc.getId(), dc);
                long networkAclId = NetworkACL.DEFAULT_DENY;
                if (aclId != null) {
                    final NetworkACLVO aclVO = _networkAclDao.findById(aclId);
                    if (aclVO == null) {
                        throw new InvalidParameterValueException("Invalid network acl id passed ");
                    }
                    if (aclVO.getVpcId() != vpcId && !(aclId == NetworkACL.DEFAULT_DENY || aclId == NetworkACL.DEFAULT_ALLOW)) {
                        throw new InvalidParameterValueException("Private gateway and network acl are not in the same vpc");
                    }
                    networkAclId = aclId;
                }
                // 2) create gateway entry
                final VpcGatewayVO gatewayVO = new VpcGatewayVO(ipAddress, VpcGateway.Type.Private, vpcId, privateNtwk.getDataCenterId(), privateNtwk.getId(), vpc.getAccountId(), vpc.getDomainId(), isSourceNat, networkAclId);
                _vpcGatewayDao.persist(gatewayVO);
                s_logger.debug("Created vpc gateway entry " + gatewayVO);
                return gatewayVO;
            }
        });
    } catch (final Exception e) {
        ExceptionUtil.rethrowRuntime(e);
        ExceptionUtil.rethrow(e, InsufficientCapacityException.class);
        ExceptionUtil.rethrow(e, ResourceAllocationException.class);
        throw new IllegalStateException(e);
    }
    CallContext.current().setEventDetails("Private Gateway Id: " + gatewayVO.getId());
    return getVpcPrivateGateway(gatewayVO.getId());
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.legacymodel.user.Account) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) Vpc(com.cloud.legacymodel.network.vpc.Vpc) TransactionStatus(com.cloud.utils.db.TransactionStatus) CallContext(com.cloud.context.CallContext) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) ExecutionException(java.util.concurrent.ExecutionException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ServerApiException(com.cloud.api.ServerApiException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) PrivateGateway(com.cloud.legacymodel.network.vpc.PrivateGateway) DataCenter(com.cloud.legacymodel.dc.DataCenter) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.legacymodel.network.Network) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 45 with Vpc

use of com.cloud.legacymodel.network.vpc.Vpc in project cosmic by MissionCriticalCloud.

the class VpcManagerImpl method associateIPToVpc.

@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_IP_ASSIGN, eventDescription = "associating Ip", async = true)
public IpAddress associateIPToVpc(final long ipId, final long vpcId) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException {
    final Account caller = CallContext.current().getCallingAccount();
    final Account owner;
    final IpAddress ipToAssoc = _ntwkModel.getIp(ipId);
    if (ipToAssoc != null) {
        _accountMgr.checkAccess(caller, null, true, ipToAssoc);
        owner = _accountMgr.getAccount(ipToAssoc.getAllocatedToAccountId());
    } else {
        s_logger.debug("Unable to find ip address by id: " + ipId);
        return null;
    }
    final Vpc vpc = _vpcDao.findById(vpcId);
    if (vpc == null) {
        throw new InvalidParameterValueException("Invalid VPC id provided");
    }
    // check permissions
    _accountMgr.checkAccess(caller, null, true, owner, vpc);
    if (!hasSourceNatService(vpc)) {
        throw new InvalidParameterValueException("VPC does not support SourceNat service so no public ip addresses can be assigned.");
    }
    boolean isSourceNat = false;
    if (getExistingSourceNatInVpc(owner.getId(), vpcId) == null) {
        isSourceNat = true;
    }
    s_logger.debug("Associating ip " + ipToAssoc + " to vpc " + vpc);
    final boolean isSourceNatFinal = isSourceNat;
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            final IPAddressVO ip = _ipAddressDao.findById(ipId);
            // update ip address with networkId
            ip.setVpcId(vpcId);
            ip.setSourceNat(isSourceNatFinal);
            _ipAddressDao.update(ipId, ip);
            // mark ip as allocated
            _ipAddrMgr.markPublicIpAsAllocated(ip);
        }
    });
    s_logger.debug("Successfully assigned ip " + ipToAssoc + " to vpc " + vpc);
    return _ipAddressDao.findById(ipId);
}
Also used : Account(com.cloud.legacymodel.user.Account) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Vpc(com.cloud.legacymodel.network.vpc.Vpc) TransactionStatus(com.cloud.utils.db.TransactionStatus) IpAddress(com.cloud.network.IpAddress) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) IPAddressVO(com.cloud.network.dao.IPAddressVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

Vpc (com.cloud.legacymodel.network.vpc.Vpc)60 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)24 Account (com.cloud.legacymodel.user.Account)24 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)17 DomainRouterVO (com.cloud.vm.DomainRouterVO)17 Network (com.cloud.legacymodel.network.Network)15 ArrayList (java.util.ArrayList)14 NetworkACL (com.cloud.legacymodel.network.vpc.NetworkACL)11 ActionEvent (com.cloud.event.ActionEvent)9 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)9 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)8 NetworkVO (com.cloud.network.dao.NetworkVO)8 List (java.util.List)8 ServerApiException (com.cloud.api.ServerApiException)7 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)7 IPAddressVO (com.cloud.network.dao.IPAddressVO)7 DB (com.cloud.utils.db.DB)7 VpcResponse (com.cloud.api.response.VpcResponse)6 CallContext (com.cloud.context.CallContext)6 DataCenter (com.cloud.legacymodel.dc.DataCenter)6