Search in sources :

Example 21 with PublicIp

use of com.cloud.network.addr.PublicIp in project cloudstack by apache.

the class NetworkOrchestrator method shutdownNetworkResources.

private boolean shutdownNetworkResources(final long networkId, final Account caller, final long callerUserId) {
    // This method cleans up network rules on the backend w/o touching them in the DB
    boolean success = true;
    final Network network = _networksDao.findById(networkId);
    // Mark all PF rules as revoked and apply them on the backend (not in the DB)
    final List<PortForwardingRuleVO> pfRules = _portForwardingRulesDao.listByNetwork(networkId);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Releasing " + pfRules.size() + " port forwarding rules for network id=" + networkId + " as a part of shutdownNetworkRules");
    }
    for (final PortForwardingRuleVO pfRule : pfRules) {
        s_logger.trace("Marking pf rule " + pfRule + " with Revoke state");
        pfRule.setState(FirewallRule.State.Revoke);
    }
    try {
        if (!_firewallMgr.applyRules(pfRules, true, false)) {
            s_logger.warn("Failed to cleanup pf rules as a part of shutdownNetworkRules");
            success = false;
        }
    } catch (final ResourceUnavailableException ex) {
        s_logger.warn("Failed to cleanup pf rules as a part of shutdownNetworkRules due to ", ex);
        success = false;
    }
    // Mark all static rules as revoked and apply them on the backend (not in the DB)
    final List<FirewallRuleVO> firewallStaticNatRules = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.StaticNat);
    final List<StaticNatRule> staticNatRules = new ArrayList<StaticNatRule>();
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Releasing " + firewallStaticNatRules.size() + " static nat rules for network id=" + networkId + " as a part of shutdownNetworkRules");
    }
    for (final FirewallRuleVO firewallStaticNatRule : firewallStaticNatRules) {
        s_logger.trace("Marking static nat rule " + firewallStaticNatRule + " with Revoke state");
        final IpAddress ip = _ipAddressDao.findById(firewallStaticNatRule.getSourceIpAddressId());
        final FirewallRuleVO ruleVO = _firewallDao.findById(firewallStaticNatRule.getId());
        if (ip == null || !ip.isOneToOneNat() || ip.getAssociatedWithVmId() == null) {
            throw new InvalidParameterValueException("Source ip address of the rule id=" + firewallStaticNatRule.getId() + " is not static nat enabled");
        }
        //String dstIp = _networkModel.getIpInNetwork(ip.getAssociatedWithVmId(), firewallStaticNatRule.getNetworkId());
        ruleVO.setState(FirewallRule.State.Revoke);
        staticNatRules.add(new StaticNatRuleImpl(ruleVO, ip.getVmIp()));
    }
    try {
        if (!_firewallMgr.applyRules(staticNatRules, true, false)) {
            s_logger.warn("Failed to cleanup static nat rules as a part of shutdownNetworkRules");
            success = false;
        }
    } catch (final ResourceUnavailableException ex) {
        s_logger.warn("Failed to cleanup static nat rules as a part of shutdownNetworkRules due to ", ex);
        success = false;
    }
    try {
        if (!_lbMgr.revokeLoadBalancersForNetwork(networkId, Scheme.Public)) {
            s_logger.warn("Failed to cleanup public lb rules as a part of shutdownNetworkRules");
            success = false;
        }
    } catch (final ResourceUnavailableException ex) {
        s_logger.warn("Failed to cleanup public lb rules as a part of shutdownNetworkRules due to ", ex);
        success = false;
    }
    try {
        if (!_lbMgr.revokeLoadBalancersForNetwork(networkId, Scheme.Internal)) {
            s_logger.warn("Failed to cleanup internal lb rules as a part of shutdownNetworkRules");
            success = false;
        }
    } catch (final ResourceUnavailableException ex) {
        s_logger.warn("Failed to cleanup public lb rules as a part of shutdownNetworkRules due to ", ex);
        success = false;
    }
    // revoke all firewall rules for the network w/o applying them on the DB
    final List<FirewallRuleVO> firewallRules = _firewallDao.listByNetworkPurposeTrafficType(networkId, Purpose.Firewall, FirewallRule.TrafficType.Ingress);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Releasing " + firewallRules.size() + " firewall ingress rules for network id=" + networkId + " as a part of shutdownNetworkRules");
    }
    for (final FirewallRuleVO firewallRule : firewallRules) {
        s_logger.trace("Marking firewall ingress rule " + firewallRule + " with Revoke state");
        firewallRule.setState(FirewallRule.State.Revoke);
    }
    try {
        if (!_firewallMgr.applyRules(firewallRules, true, false)) {
            s_logger.warn("Failed to cleanup firewall ingress rules as a part of shutdownNetworkRules");
            success = false;
        }
    } catch (final ResourceUnavailableException ex) {
        s_logger.warn("Failed to cleanup firewall ingress rules as a part of shutdownNetworkRules due to ", ex);
        success = false;
    }
    final List<FirewallRuleVO> firewallEgressRules = _firewallDao.listByNetworkPurposeTrafficType(networkId, Purpose.Firewall, FirewallRule.TrafficType.Egress);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Releasing " + firewallEgressRules.size() + " firewall egress rules for network id=" + networkId + " as a part of shutdownNetworkRules");
    }
    try {
        // delete default egress rule
        final DataCenter zone = _dcDao.findById(network.getDataCenterId());
        if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.Firewall) && (network.getGuestType() == Network.GuestType.Isolated || network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced)) {
            // add default egress rule to accept the traffic
            _firewallMgr.applyDefaultEgressFirewallRule(network.getId(), _networkModel.getNetworkEgressDefaultPolicy(networkId), false);
        }
    } catch (final ResourceUnavailableException ex) {
        s_logger.warn("Failed to cleanup firewall default egress rule as a part of shutdownNetworkRules due to ", ex);
        success = false;
    }
    for (final FirewallRuleVO firewallRule : firewallEgressRules) {
        s_logger.trace("Marking firewall egress rule " + firewallRule + " with Revoke state");
        firewallRule.setState(FirewallRule.State.Revoke);
    }
    try {
        if (!_firewallMgr.applyRules(firewallEgressRules, true, false)) {
            s_logger.warn("Failed to cleanup firewall egress rules as a part of shutdownNetworkRules");
            success = false;
        }
    } catch (final ResourceUnavailableException ex) {
        s_logger.warn("Failed to cleanup firewall egress rules as a part of shutdownNetworkRules due to ", ex);
        success = false;
    }
    if (network.getVpcId() != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Releasing Network ACL Items for network id=" + networkId + " as a part of shutdownNetworkRules");
        }
        try {
            //revoke all Network ACLs for the network w/o applying them in the DB
            if (!_networkACLMgr.revokeACLItemsForNetwork(networkId)) {
                s_logger.warn("Failed to cleanup network ACLs as a part of shutdownNetworkRules");
                success = false;
            }
        } catch (final ResourceUnavailableException ex) {
            s_logger.warn("Failed to cleanup network ACLs as a part of shutdownNetworkRules due to ", ex);
            success = false;
        }
    }
    //release all static nats for the network
    if (!_rulesMgr.applyStaticNatForNetwork(networkId, false, caller, true)) {
        s_logger.warn("Failed to disable static nats as part of shutdownNetworkRules for network id " + networkId);
        success = false;
    }
    // Get all ip addresses, mark as releasing and release them on the backend
    final List<IPAddressVO> userIps = _ipAddressDao.listByAssociatedNetwork(networkId, null);
    final List<PublicIp> publicIpsToRelease = new ArrayList<PublicIp>();
    if (userIps != null && !userIps.isEmpty()) {
        for (final IPAddressVO userIp : userIps) {
            userIp.setState(IpAddress.State.Releasing);
            final PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
            publicIpsToRelease.add(publicIp);
        }
    }
    try {
        if (!_ipAddrMgr.applyIpAssociations(network, true, true, publicIpsToRelease)) {
            s_logger.warn("Unable to apply ip address associations for " + network + " as a part of shutdownNetworkRules");
            success = false;
        }
    } catch (final ResourceUnavailableException e) {
        throw new CloudRuntimeException("We should never get to here because we used true when applyIpAssociations", e);
    }
    return success;
}
Also used : PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) PublicIp(com.cloud.network.addr.PublicIp) ArrayList(java.util.ArrayList) StaticNatRule(com.cloud.network.rules.StaticNatRule) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) StaticNatRuleImpl(com.cloud.network.rules.StaticNatRuleImpl) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) IpAddress(com.cloud.network.IpAddress) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 22 with PublicIp

use of com.cloud.network.addr.PublicIp in project cloudstack by apache.

the class IpAddressManagerImpl method checkStaticNatIPAssocRequired.

// checks if there are any public IP assigned to network, that are marked for one-to-one NAT that
// needs to be associated/dis-associated with static-nat provider
boolean checkStaticNatIPAssocRequired(Network network, boolean postApplyRules, boolean forRevoke, List<PublicIp> publicIps) {
    for (PublicIp ip : publicIps) {
        if (ip.isOneToOneNat()) {
            Long activeFwCount = null;
            activeFwCount = _firewallDao.countRulesByIpIdAndState(ip.getId(), FirewallRule.State.Active);
            if (!postApplyRules && !forRevoke) {
                if (activeFwCount > 0) {
                    continue;
                } else {
                    return true;
                }
            } else if (postApplyRules && forRevoke) {
                return true;
            }
        } else {
            continue;
        }
    }
    return false;
}
Also used : PublicIp(com.cloud.network.addr.PublicIp)

Example 23 with PublicIp

use of com.cloud.network.addr.PublicIp in project cloudstack by apache.

the class IpAddressManagerImpl method allocateIp.

@DB
@Override
public IpAddress allocateIp(final Account ipOwner, final boolean isSystem, Account caller, long callerUserId, final DataCenter zone, final Boolean displayIp) throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException {
    final VlanType vlanType = VlanType.VirtualNetwork;
    final boolean assign = false;
    if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
        // zone is of type DataCenter. See DataCenterVO.java.
        PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, " + "Zone is currently disabled");
        ex.addProxyObject(zone.getUuid(), "zoneId");
        throw ex;
    }
    PublicIp ip = null;
    Account accountToLock = null;
    try {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId());
        }
        accountToLock = _accountDao.acquireInLockTable(ipOwner.getId());
        if (accountToLock == null) {
            s_logger.warn("Unable to lock account: " + ipOwner.getId());
            throw new ConcurrentOperationException("Unable to acquire account lock");
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Associate IP address lock acquired");
        }
        ip = Transaction.execute(new TransactionCallbackWithException<PublicIp, InsufficientAddressCapacityException>() {

            @Override
            public PublicIp doInTransaction(TransactionStatus status) throws InsufficientAddressCapacityException {
                PublicIp ip = fetchNewPublicIp(zone.getId(), null, null, ipOwner, vlanType, null, false, assign, null, isSystem, null, displayIp);
                if (ip == null) {
                    InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Unable to find available public IP addresses", DataCenter.class, zone.getId());
                    ex.addProxyObject(ApiDBUtils.findZoneById(zone.getId()).getUuid());
                    throw ex;
                }
                CallContext.current().setEventDetails("Ip Id: " + ip.getId());
                Ip ipAddress = ip.getAddress();
                s_logger.debug("Got " + ipAddress + " to assign for account " + ipOwner.getId() + " in zone " + zone.getId());
                return ip;
            }
        });
    } finally {
        if (accountToLock != null) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Releasing lock account " + ipOwner);
            }
            _accountDao.releaseFromLockTable(ipOwner.getId());
            s_logger.debug("Associate IP address lock released");
        }
    }
    return ip;
}
Also used : Account(com.cloud.user.Account) PublicIp(com.cloud.network.addr.PublicIp) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) PortableIp(org.apache.cloudstack.region.PortableIp) Ip(com.cloud.utils.net.Ip) PublicIp(com.cloud.network.addr.PublicIp) TransactionStatus(com.cloud.utils.db.TransactionStatus) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) VlanType(com.cloud.dc.Vlan.VlanType) DB(com.cloud.utils.db.DB)

Example 24 with PublicIp

use of com.cloud.network.addr.PublicIp in project cloudstack by apache.

the class IpAddressManagerImpl method applyRules.

@Override
public boolean applyRules(List<? extends FirewallRule> rules, FirewallRule.Purpose purpose, NetworkRuleApplier applier, boolean continueOnError) throws ResourceUnavailableException {
    if (rules == null || rules.size() == 0) {
        s_logger.debug("There are no rules to forward to the network elements");
        return true;
    }
    boolean success = true;
    Network network = _networksDao.findById(rules.get(0).getNetworkId());
    FirewallRuleVO.TrafficType trafficType = rules.get(0).getTrafficType();
    List<PublicIp> publicIps = new ArrayList<PublicIp>();
    if (!(rules.get(0).getPurpose() == FirewallRule.Purpose.Firewall && trafficType == FirewallRule.TrafficType.Egress)) {
        // get the list of public ip's owned by the network
        List<IPAddressVO> userIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), null);
        if (userIps != null && !userIps.isEmpty()) {
            for (IPAddressVO userIp : userIps) {
                PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
                publicIps.add(publicIp);
            }
        }
    }
    // the network so as to ensure IP is associated before applying rules (in add state)
    if (checkIfIpAssocRequired(network, false, publicIps)) {
        applyIpAssociations(network, false, continueOnError, publicIps);
    }
    try {
        applier.applyRules(network, purpose, rules);
    } catch (ResourceUnavailableException e) {
        if (!continueOnError) {
            throw e;
        }
        s_logger.warn("Problems with applying " + purpose + " rules but pushing on", e);
        success = false;
    }
    // This IPAssoc ensures, public IP is dis-associated after last active rule is revoked.
    if (checkIfIpAssocRequired(network, true, publicIps)) {
        applyIpAssociations(network, true, continueOnError, publicIps);
    }
    return success;
}
Also used : PublicIp(com.cloud.network.addr.PublicIp) ArrayList(java.util.ArrayList) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) IPAddressVO(com.cloud.network.dao.IPAddressVO) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO)

Example 25 with PublicIp

use of com.cloud.network.addr.PublicIp in project cloudstack by apache.

the class IpAddressManagerImpl method applyStaticNats.

@Override
public boolean applyStaticNats(List<? extends StaticNat> staticNats, boolean continueOnError, boolean forRevoke) throws ResourceUnavailableException {
    if (staticNats == null || staticNats.size() == 0) {
        s_logger.debug("There are no static nat rules for the network elements");
        return true;
    }
    Network network = _networksDao.findById(staticNats.get(0).getNetworkId());
    boolean success = true;
    // Check if the StaticNat service is supported
    if (!_networkModel.areServicesSupportedInNetwork(network.getId(), Service.StaticNat)) {
        s_logger.debug("StaticNat service is not supported in specified network id");
        return true;
    }
    List<IPAddressVO> userIps = getStaticNatSourceIps(staticNats);
    List<PublicIp> publicIps = new ArrayList<PublicIp>();
    if (userIps != null && !userIps.isEmpty()) {
        for (IPAddressVO userIp : userIps) {
            PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
            publicIps.add(publicIp);
        }
    }
    // association for the network so as to ensure IP is associated before applying rules
    if (checkStaticNatIPAssocRequired(network, false, forRevoke, publicIps)) {
        applyIpAssociations(network, false, continueOnError, publicIps);
    }
    // get provider
    StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network);
    try {
        success = element.applyStaticNats(network, staticNats);
    } catch (ResourceUnavailableException e) {
        if (!continueOnError) {
            throw e;
        }
        s_logger.warn("Problems with " + element.getName() + " but pushing on", e);
        success = false;
    }
    // For revoked static nat IP, set the vm_id to null, indicate it should be revoked
    for (StaticNat staticNat : staticNats) {
        if (staticNat.isForRevoke()) {
            for (PublicIp publicIp : publicIps) {
                if (publicIp.getId() == staticNat.getSourceIpAddressId()) {
                    publicIps.remove(publicIp);
                    IPAddressVO ip = _ipAddressDao.findByIdIncludingRemoved(staticNat.getSourceIpAddressId());
                    // ip can't be null, otherwise something wrong happened
                    ip.setAssociatedWithVmId(null);
                    publicIp = PublicIp.createFromAddrAndVlan(ip, _vlanDao.findById(ip.getVlanId()));
                    publicIps.add(publicIp);
                    break;
                }
            }
        }
    }
    // if the static NAT rules configured on public IP is revoked then, dis-associate IP with static NAT service provider
    if (checkStaticNatIPAssocRequired(network, true, forRevoke, publicIps)) {
        applyIpAssociations(network, true, continueOnError, publicIps);
    }
    return success;
}
Also used : PublicIp(com.cloud.network.addr.PublicIp) StaticNatServiceProvider(com.cloud.network.element.StaticNatServiceProvider) ArrayList(java.util.ArrayList) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) IPAddressVO(com.cloud.network.dao.IPAddressVO) StaticNat(com.cloud.network.rules.StaticNat)

Aggregations

PublicIp (com.cloud.network.addr.PublicIp)38 IPAddressVO (com.cloud.network.dao.IPAddressVO)20 ArrayList (java.util.ArrayList)16 Network (com.cloud.network.Network)9 Account (com.cloud.user.Account)9 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)9 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)8 DataCenter (com.cloud.dc.DataCenter)7 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)6 Test (org.junit.Test)6 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)5 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)5 Service (com.cloud.network.Network.Service)5 DB (com.cloud.utils.db.DB)5 TransactionStatus (com.cloud.utils.db.TransactionStatus)5 HashSet (java.util.HashSet)5 Set (java.util.Set)5 VlanVO (com.cloud.dc.VlanVO)4 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)4 Provider (com.cloud.network.Network.Provider)4