Search in sources :

Example 51 with IpAddress

use of com.cloud.network.IpAddress in project cloudstack by apache.

the class MidoNetElement method applyPFRules.

@Override
public boolean applyPFRules(Network network, List<PortForwardingRule> rules) throws ResourceUnavailableException {
    s_logger.debug("applyPFRules called with network " + network.toString());
    if (!midoInNetwork(network)) {
        return false;
    }
    if (!canHandle(network, Service.PortForwarding)) {
        return false;
    }
    String accountIdStr = getAccountUuid(network);
    String networkUUIDStr = String.valueOf(network.getId());
    RuleChain preNat = getChain(accountIdStr, networkUUIDStr, RuleChainCode.TR_PRENAT);
    RuleChain postNat = getChain(accountIdStr, networkUUIDStr, RuleChainCode.TR_POST);
    RuleChain preFilter = getChain(accountIdStr, networkUUIDStr, RuleChainCode.TR_PREFILTER);
    Router providerRouter = api.getRouter(_providerRouterId);
    Router tenantRouter = getOrCreateGuestNetworkRouter(network);
    RouterPort[] ports = getOrCreateProviderRouterPorts(tenantRouter, providerRouter);
    RouterPort providerDownlink = ports[1];
    // Rules in the preNat table
    Map<String, Rule> existingPreNatRules = new HashMap<String, Rule>();
    for (Rule existingRule : preNat.getRules()) {
        // The "port forwarding" rules we're interested in are dnat rules where src / dst ports are specified
        if (existingRule.getType().equals(DtoRule.DNAT) && existingRule.getTpDst() != null) {
            String ruleString = new SimpleFirewallRule(existingRule).toStringArray()[0];
            existingPreNatRules.put(ruleString, existingRule);
        }
    }
    /*
         * Counts of rules associated with an IP address. Use this to check
         * how many rules we have of a given IP address. When it reaches 0,
         * we can delete the route associated with it.
         */
    Map<String, Integer> ipRuleCounts = new HashMap<String, Integer>();
    for (Rule rule : preNat.getRules()) {
        String ip = rule.getNwDstAddress();
        if (ip != null && rule.getNwDstLength() == 32) {
            if (ipRuleCounts.containsKey(ip)) {
                ipRuleCounts.put(ip, new Integer(ipRuleCounts.get(ip).intValue() + 1));
            } else {
                ipRuleCounts.put(ip, new Integer(1));
            }
        }
    }
    /*
         * Routes associated with IP. When we delete all the rules associated
         * with a given IP, we can delete the route associated with it.
         */
    Map<String, Route> routes = new HashMap<String, Route>();
    for (Route route : providerRouter.getRoutes(new MultivaluedMapImpl())) {
        String ip = route.getDstNetworkAddr();
        if (ip != null && route.getDstNetworkLength() == 32) {
            routes.put(ip, route);
        }
    }
    for (PortForwardingRule rule : rules) {
        IpAddress dstIp = _networkModel.getIp(rule.getSourceIpAddressId());
        PortForwardingRuleTO ruleTO = new PortForwardingRuleTO(rule, null, dstIp.getAddress().addr());
        SimpleFirewallRule fwRule = new SimpleFirewallRule(ruleTO);
        String[] ruleStrings = fwRule.toStringArray();
        if (rule.getState() == FirewallRule.State.Revoke) {
            /*
                 * Lookup in existingRules, delete if present
                 * We need to delete from both the preNat table and the
                 * postNat table.
                 */
            for (String revokeRuleString : ruleStrings) {
                Rule foundPreNatRule = existingPreNatRules.get(revokeRuleString);
                if (foundPreNatRule != null) {
                    String ip = foundPreNatRule.getNwDstAddress();
                    // is this the last rule associated with this IP?
                    Integer cnt = ipRuleCounts.get(ip);
                    if (cnt != null) {
                        if (cnt == 1) {
                            ipRuleCounts.remove(ip);
                            // no more rules for this IP. delete the route.
                            Route route = routes.remove(ip);
                            route.delete();
                        } else {
                            ipRuleCounts.put(ip, new Integer(ipRuleCounts.get(ip).intValue() - 1));
                        }
                    }
                    foundPreNatRule.delete();
                }
            }
        } else if (rule.getState() == FirewallRule.State.Add) {
            for (int i = 0; i < ruleStrings.length; i++) {
                String ruleString = ruleStrings[i];
                Rule foundRule = existingPreNatRules.get(ruleString);
                if (foundRule == null) {
                    String vmIp = ruleTO.getDstIp();
                    String publicIp = dstIp.getAddress().addr();
                    int privPortStart = ruleTO.getDstPortRange()[0];
                    int privPortEnd = ruleTO.getDstPortRange()[1];
                    int pubPortStart = ruleTO.getSrcPortRange()[0];
                    int pubPortEnd = ruleTO.getSrcPortRange()[1];
                    DtoRule.DtoNatTarget[] preTargets = new DtoRule.DtoNatTarget[] { new DtoRule.DtoNatTarget(vmIp, vmIp, privPortStart, privPortEnd) };
                    Rule preNatRule = preNat.addRule().type(DtoRule.DNAT).flowAction(DtoRule.Accept).nwDstAddress(publicIp).nwDstLength(32).tpDst(new DtoRange(pubPortStart, pubPortEnd)).natTargets(preTargets).nwProto(SimpleFirewallRule.stringToProtocolNumber(rule.getProtocol())).position(1);
                    Integer cnt = ipRuleCounts.get(publicIp);
                    if (cnt != null) {
                        ipRuleCounts.put(publicIp, new Integer(cnt.intValue() + 1));
                    } else {
                        ipRuleCounts.put(publicIp, new Integer(1));
                    }
                    String preNatRuleStr = new SimpleFirewallRule(preNatRule).toStringArray()[0];
                    existingPreNatRules.put(preNatRuleStr, preNatRule);
                    preNatRule.create();
                    if (routes.get(publicIp) == null) {
                        Route route = providerRouter.addRoute().type("Normal").weight(100).srcNetworkAddr("0.0.0.0").srcNetworkLength(0).dstNetworkAddr(publicIp).dstNetworkLength(32).nextHopPort(providerDownlink.getId());
                        route.create();
                        routes.put(publicIp, route);
                    }
                    // default firewall rule
                    if (canHandle(network, Service.Firewall)) {
                        boolean defaultBlock = false;
                        for (Rule filterRule : preFilter.getRules()) {
                            String pfDstIp = filterRule.getNwDstAddress();
                            if (pfDstIp != null && filterRule.getNwDstAddress().equals(publicIp)) {
                                defaultBlock = true;
                                break;
                            }
                        }
                        if (!defaultBlock) {
                            preFilter.addRule().type(DtoRule.Drop).nwDstAddress(publicIp).nwDstLength(32).create();
                        }
                    }
                }
            }
        }
    }
    return true;
}
Also used : DtoRange(org.midonet.client.dto.DtoRule.DtoRange) PortForwardingRuleTO(com.cloud.agent.api.to.PortForwardingRuleTO) HashMap(java.util.HashMap) DtoRule(org.midonet.client.dto.DtoRule) Router(org.midonet.client.resource.Router) MultivaluedMapImpl(com.sun.jersey.core.util.MultivaluedMapImpl) PortForwardingRule(com.cloud.network.rules.PortForwardingRule) RuleChain(org.midonet.client.resource.RuleChain) IpAddress(com.cloud.network.IpAddress) PublicIpAddress(com.cloud.network.PublicIpAddress) Rule(org.midonet.client.resource.Rule) PortForwardingRule(com.cloud.network.rules.PortForwardingRule) FirewallRule(com.cloud.network.rules.FirewallRule) DtoRule(org.midonet.client.dto.DtoRule) RouterPort(org.midonet.client.resource.RouterPort) Route(org.midonet.client.resource.Route)

Example 52 with IpAddress

use of com.cloud.network.IpAddress in project cloudstack by apache.

the class CreatePortForwardingRuleCmd method getNetworkId.

@Override
public long getNetworkId() {
    IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId());
    Long ntwkId = null;
    if (ip.getAssociatedWithNetworkId() != null) {
        ntwkId = ip.getAssociatedWithNetworkId();
    } else {
        ntwkId = networkId;
    }
    if (ntwkId == null) {
        throw new InvalidParameterValueException("Unable to create port forwarding rule for the ipAddress id=" + ipAddressId + " as ip is not associated with any network and no networkId is passed in");
    }
    return ntwkId;
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) IpAddress(com.cloud.network.IpAddress)

Example 53 with IpAddress

use of com.cloud.network.IpAddress 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 54 with IpAddress

use of com.cloud.network.IpAddress in project cloudstack by apache.

the class AssociateIPAddrCmdByAdmin method execute.

@Override
public void execute() throws ResourceUnavailableException, ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
    CallContext.current().setEventDetails("Ip Id: " + getEntityId());
    IpAddress result = null;
    if (getVpcId() != null) {
        result = _vpcService.associateIPToVpc(getEntityId(), getVpcId());
    } else if (getNetworkId() != null) {
        result = _networkService.associateIPToNetwork(getEntityId(), getNetworkId());
    }
    if (result != null) {
        IPAddressResponse ipResponse = _responseGenerator.createIPAddressResponse(ResponseView.Full, result);
        ipResponse.setResponseName(getCommandName());
        setResponseObject(ipResponse);
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to assign ip address");
    }
}
Also used : ServerApiException(org.apache.cloudstack.api.ServerApiException) IpAddress(com.cloud.network.IpAddress) IPAddressResponse(org.apache.cloudstack.api.response.IPAddressResponse)

Example 55 with IpAddress

use of com.cloud.network.IpAddress in project cloudstack by apache.

the class AssociateIPAddrCmd method execute.

@Override
public void execute() throws ResourceUnavailableException, ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
    CallContext.current().setEventDetails("IP ID: " + getEntityId());
    IpAddress result = null;
    if (getVpcId() != null) {
        result = _vpcService.associateIPToVpc(getEntityId(), getVpcId());
    } else if (getNetworkId() != null) {
        result = _networkService.associateIPToNetwork(getEntityId(), getNetworkId());
    }
    if (result != null) {
        IPAddressResponse ipResponse = _responseGenerator.createIPAddressResponse(ResponseView.Restricted, result);
        ipResponse.setResponseName(getCommandName());
        setResponseObject(ipResponse);
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to assign IP address");
    }
}
Also used : ServerApiException(org.apache.cloudstack.api.ServerApiException) IpAddress(com.cloud.network.IpAddress) IPAddressResponse(org.apache.cloudstack.api.response.IPAddressResponse)

Aggregations

IpAddress (com.cloud.network.IpAddress)58 ArrayList (java.util.ArrayList)26 PublicIpAddress (com.cloud.network.PublicIpAddress)20 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)16 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)16 Network (com.cloud.network.Network)14 FirewallRule (com.cloud.network.rules.FirewallRule)11 HostVO (com.cloud.host.HostVO)9 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)9 DataCenterVO (com.cloud.dc.DataCenterVO)7 CiscoVnmcControllerVO (com.cloud.network.cisco.CiscoVnmcControllerVO)7 NetworkAsa1000vMapVO (com.cloud.network.cisco.NetworkAsa1000vMapVO)7 IPAddressVO (com.cloud.network.dao.IPAddressVO)7 PrivateIpAddress (com.cloud.network.vpc.PrivateIpAddress)7 Answer (com.cloud.agent.api.Answer)6 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)6 PublicIp (com.cloud.network.addr.PublicIp)6 StaticNat (com.cloud.network.rules.StaticNat)6 Account (com.cloud.user.Account)6 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)5