Search in sources :

Example 1 with StaticNatRule

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

the class RulesManagerImpl method createStaticNatRule.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "creating static nat rule", create = true)
public StaticNatRule createStaticNatRule(final StaticNatRule rule, final boolean openFirewall) throws NetworkRuleConflictException {
    final Account caller = CallContext.current().getCallingAccount();
    final Long ipAddrId = rule.getSourceIpAddressId();
    final IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
    // Validate ip address
    if (ipAddress == null) {
        throw new InvalidParameterValueException("Unable to create static nat rule; ip id=" + ipAddrId + " doesn't exist in the system");
    } else if (ipAddress.isSourceNat() || !ipAddress.isOneToOneNat() || ipAddress.getAssociatedWithVmId() == null) {
        throw new NetworkRuleConflictException("Can't do static nat on ip address: " + ipAddress.getAddress());
    }
    _firewallMgr.validateFirewallRule(caller, ipAddress, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), Purpose.StaticNat, FirewallRuleType.User, null, rule.getTrafficType());
    final Long networkId = ipAddress.getAssociatedWithNetworkId();
    final Long accountId = ipAddress.getAllocatedToAccountId();
    final Long domainId = ipAddress.getAllocatedInDomainId();
    _networkModel.checkIpForService(ipAddress, Service.StaticNat, null);
    final Network network = _networkModel.getNetwork(networkId);
    final NetworkOffering off = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
    if (off.getElasticIp()) {
        throw new InvalidParameterValueException("Can't create ip forwarding rules for the network where elasticIP service is enabled");
    }
    // String dstIp = _networkModel.getIpInNetwork(ipAddress.getAssociatedWithVmId(), networkId);
    final String dstIp = ipAddress.getVmIp();
    return Transaction.execute(new TransactionCallbackWithException<StaticNatRule, NetworkRuleConflictException>() {

        @Override
        public StaticNatRule doInTransaction(final TransactionStatus status) throws NetworkRuleConflictException {
            FirewallRuleVO newRule = new FirewallRuleVO(rule.getXid(), rule.getSourceIpAddressId(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol().toLowerCase(), networkId, accountId, domainId, rule.getPurpose(), null, null, null, null, null);
            newRule = _firewallDao.persist(newRule);
            // create firewallRule for 0.0.0.0/0 cidr
            if (openFirewall) {
                _firewallMgr.createRuleForAllCidrs(ipAddrId, caller, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), null, null, newRule.getId(), networkId);
            }
            try {
                _firewallMgr.detectRulesConflict(newRule);
                if (!_firewallDao.setStateToAdd(newRule)) {
                    throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
                }
                CallContext.current().setEventDetails("Rule Id: " + newRule.getId());
                final StaticNatRule staticNatRule = new StaticNatRuleImpl(newRule, dstIp);
                return staticNatRule;
            } catch (final Exception e) {
                if (newRule != null) {
                    // no need to apply the rule as it wasn't programmed on the backend yet
                    _firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false);
                    _firewallMgr.removeRule(newRule);
                }
                if (e instanceof NetworkRuleConflictException) {
                    throw (NetworkRuleConflictException) e;
                }
                throw new CloudRuntimeException("Unable to add static nat rule for the ip id=" + newRule.getSourceIpAddressId(), e);
            }
        }
    });
}
Also used : Account(com.cloud.legacymodel.user.Account) NetworkOffering(com.cloud.offering.NetworkOffering) TransactionStatus(com.cloud.utils.db.TransactionStatus) StaticNatRule(com.cloud.legacymodel.network.StaticNatRule) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) IPAddressVO(com.cloud.network.dao.IPAddressVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 2 with StaticNatRule

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

the class VirtualNetworkApplianceManagerImpl method finalizeNetworkRulesForNetwork.

protected void finalizeNetworkRulesForNetwork(final Commands cmds, final DomainRouterVO router, final Provider provider, final Long guestNetworkId) {
    s_logger.debug("Resending ipAssoc, port forwarding, load balancing rules as a part of Virtual router start");
    final ArrayList<? extends PublicIpAddress> publicIps = getPublicIpsToApply(router, provider, guestNetworkId);
    final List<FirewallRule> firewallRulesEgress = new ArrayList<>();
    // Fetch firewall Egress rules.
    if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Firewall, provider)) {
        firewallRulesEgress.addAll(_rulesDao.listByNetworkPurposeTrafficType(guestNetworkId, Purpose.Firewall, FirewallRule.TrafficType.Egress));
        if (firewallRulesEgress.isEmpty()) {
            // create egress default rule for VR
            createDefaultEgressFirewallRule(firewallRulesEgress, guestNetworkId);
        }
    }
    // Re-apply firewall Egress rules
    s_logger.debug("Found " + firewallRulesEgress.size() + " firewall Egress rule(s) to apply as a part of domR " + router + " start.");
    if (!firewallRulesEgress.isEmpty()) {
        _commandSetupHelper.createFirewallRulesCommands(firewallRulesEgress, router, cmds, guestNetworkId);
    }
    if (publicIps != null && !publicIps.isEmpty()) {
        final List<PortForwardingRule> pfRules = new ArrayList<>();
        final List<FirewallRule> staticNatFirewallRules = new ArrayList<>();
        final List<StaticNat> staticNats = new ArrayList<>();
        final List<FirewallRule> firewallRulesIngress = new ArrayList<>();
        // StaticNatRules; PFVPN to reapply on domR start)
        for (final PublicIpAddress ip : publicIps) {
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.PortForwarding, provider)) {
                pfRules.addAll(_pfRulesDao.listForApplication(ip.getId()));
            }
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.StaticNat, provider)) {
                staticNatFirewallRules.addAll(_rulesDao.listByIpAndPurpose(ip.getId(), Purpose.StaticNat));
            }
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Firewall, provider)) {
                firewallRulesIngress.addAll(_rulesDao.listByIpAndPurpose(ip.getId(), Purpose.Firewall));
            }
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.StaticNat, provider)) {
                if (ip.isOneToOneNat()) {
                    final StaticNatImpl staticNat = new StaticNatImpl(ip.getAccountId(), ip.getDomainId(), guestNetworkId, ip.getId(), ip.getVmIp(), false);
                    staticNats.add(staticNat);
                }
            }
        }
        // Re-apply static nats
        s_logger.debug("Found " + staticNats.size() + " static nat(s) to apply as a part of domR " + router + " start.");
        if (!staticNats.isEmpty()) {
            _commandSetupHelper.createApplyStaticNatCommands(staticNats, router, cmds);
        }
        // Re-apply firewall Ingress rules
        s_logger.debug("Found " + firewallRulesIngress.size() + " firewall Ingress rule(s) to apply as a part of domR " + router + " start.");
        if (!firewallRulesIngress.isEmpty()) {
            _commandSetupHelper.createFirewallRulesCommands(firewallRulesIngress, router, cmds, guestNetworkId);
        }
        // Re-apply port forwarding rules
        s_logger.debug("Found " + pfRules.size() + " port forwarding rule(s) to apply as a part of domR " + router + " start.");
        if (!pfRules.isEmpty()) {
            _commandSetupHelper.createApplyPortForwardingRulesCommands(pfRules, router, cmds, guestNetworkId);
        }
        // Re-apply static nat rules
        s_logger.debug("Found " + staticNatFirewallRules.size() + " static nat rule(s) to apply as a part of domR " + router + " start.");
        if (!staticNatFirewallRules.isEmpty()) {
            final List<StaticNatRule> staticNatRules = new ArrayList<>();
            for (final FirewallRule rule : staticNatFirewallRules) {
                staticNatRules.add(_rulesMgr.buildStaticNatRule(rule, false));
            }
            _commandSetupHelper.createApplyStaticNatRulesCommands(staticNatRules, router, cmds, guestNetworkId);
        }
        final List<LoadBalancerVO> lbs = _loadBalancerDao.listByNetworkIdAndScheme(guestNetworkId, Scheme.Public);
        final List<LoadBalancingRule> lbRules = new ArrayList<>();
        if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Lb, provider)) {
            // Re-apply load balancing rules
            for (final LoadBalancerVO lb : lbs) {
                final List<LbDestination> dstList = _lbMgr.getExistingDestinations(lb.getId());
                final List<LbStickinessPolicy> policyList = _lbMgr.getStickinessPolicies(lb.getId());
                final List<LbHealthCheckPolicy> hcPolicyList = _lbMgr.getHealthCheckPolicies(lb.getId());
                final Ip sourceIp = _networkModel.getPublicIpAddress(lb.getSourceIpAddressId()).getAddress();
                final LbSslCert sslCert = _lbMgr.getLbSslCert(lb.getId());
                final LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp, sslCert, lb.getLbProtocol());
                lbRules.add(loadBalancing);
            }
        }
        s_logger.debug("Found " + lbRules.size() + " load balancing rule(s) to apply as a part of domR " + router + " start.");
        if (!lbRules.isEmpty()) {
            _commandSetupHelper.createApplyLoadBalancingRulesCommands(lbRules, router, cmds, guestNetworkId);
        }
    }
}
Also used : LbSslCert(com.cloud.legacymodel.network.LoadBalancingRule.LbSslCert) LoadBalancingRule(com.cloud.legacymodel.network.LoadBalancingRule) Ip(com.cloud.legacymodel.network.Ip) PublicIp(com.cloud.network.addr.PublicIp) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LbStickinessPolicy(com.cloud.legacymodel.network.LoadBalancingRule.LbStickinessPolicy) StaticNatRule(com.cloud.legacymodel.network.StaticNatRule) PortForwardingRule(com.cloud.legacymodel.network.PortForwardingRule) StaticNat(com.cloud.network.rules.StaticNat) LbDestination(com.cloud.legacymodel.network.LoadBalancingRule.LbDestination) PublicIpAddress(com.cloud.network.PublicIpAddress) StaticNatImpl(com.cloud.network.rules.StaticNatImpl) LbHealthCheckPolicy(com.cloud.legacymodel.network.LoadBalancingRule.LbHealthCheckPolicy) FirewallRule(com.cloud.legacymodel.network.FirewallRule)

Example 3 with StaticNatRule

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

the class CommandSetupHelper method createApplyStaticNatRulesCommands.

public void createApplyStaticNatRulesCommands(final List<? extends StaticNatRule> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
    final List<StaticNatRuleTO> rulesTO = new ArrayList<>();
    if (rules != null) {
        for (final StaticNatRule rule : rules) {
            final IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
            final StaticNatRuleTO ruleTO = new StaticNatRuleTO(rule, null, sourceIp.getAddress().addr(), rule.getDestIpAddress());
            rulesTO.add(ruleTO);
        }
    }
    final SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(rulesTO, router.getVpcId());
    cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
    cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
    final Zone zone = zoneRepository.findById(router.getDataCenterId()).orElse(null);
    cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, zone.getNetworkType().toString());
    cmds.addCommand(cmd);
}
Also used : StaticNatRuleTO(com.cloud.legacymodel.to.StaticNatRuleTO) SetStaticNatRulesCommand(com.cloud.legacymodel.communication.command.SetStaticNatRulesCommand) Zone(com.cloud.db.model.Zone) ArrayList(java.util.ArrayList) IpAddress(com.cloud.network.IpAddress) PublicIpAddress(com.cloud.network.PublicIpAddress) StaticNatRule(com.cloud.legacymodel.network.StaticNatRule)

Example 4 with StaticNatRule

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

the class CreateIpForwardingRuleCmd method execute.

@Override
public void execute() throws ResourceUnavailableException {
    boolean result = true;
    FirewallRule rule = null;
    try {
        CallContext.current().setEventDetails("Rule ID: " + getEntityId());
        if (getOpenFirewall()) {
            result = result && _firewallService.applyIngressFirewallRules(ipAddressId, CallContext.current().getCallingAccount());
        }
        result = result && _rulesService.applyStaticNatRules(ipAddressId, CallContext.current().getCallingAccount());
        rule = _entityMgr.findById(FirewallRule.class, getEntityId());
        final StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false);
        final IpForwardingRuleResponse fwResponse = _responseGenerator.createIpForwardingRuleResponse(staticNatRule);
        fwResponse.setResponseName(getCommandName());
        setResponseObject(fwResponse);
    } finally {
        if (!result || rule == null) {
            if (getOpenFirewall()) {
                _firewallService.revokeRelatedFirewallRule(getEntityId(), true);
            }
            _rulesService.revokeStaticNatRule(getEntityId(), true);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Error in creating IP forwarding rule on the domr");
        }
    }
}
Also used : ServerApiException(com.cloud.api.ServerApiException) StaticNatRule(com.cloud.legacymodel.network.StaticNatRule) FirewallRule(com.cloud.legacymodel.network.FirewallRule) IpForwardingRuleResponse(com.cloud.api.response.IpForwardingRuleResponse)

Example 5 with StaticNatRule

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

the class ListIpForwardingRulesCmd method execute.

@Override
public void execute() {
    final Pair<List<? extends FirewallRule>, Integer> result = _rulesService.searchStaticNatRules(publicIpAddressId, id, vmId, this.getStartIndex(), this.getPageSizeVal(), this.getAccountName(), this.getDomainId(), this.getProjectId(), this.isRecursive(), this.listAll());
    final ListResponse<IpForwardingRuleResponse> response = new ListResponse<>();
    final List<IpForwardingRuleResponse> ipForwardingResponses = new ArrayList<>();
    for (final FirewallRule rule : result.first()) {
        final StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false);
        final IpForwardingRuleResponse resp = _responseGenerator.createIpForwardingRuleResponse(staticNatRule);
        if (resp != null) {
            ipForwardingResponses.add(resp);
        }
    }
    response.setResponses(ipForwardingResponses, result.second());
    response.setResponseName(getCommandName());
    this.setResponseObject(response);
}
Also used : ListResponse(com.cloud.api.response.ListResponse) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) StaticNatRule(com.cloud.legacymodel.network.StaticNatRule) FirewallRule(com.cloud.legacymodel.network.FirewallRule) IpForwardingRuleResponse(com.cloud.api.response.IpForwardingRuleResponse)

Aggregations

StaticNatRule (com.cloud.legacymodel.network.StaticNatRule)9 ArrayList (java.util.ArrayList)5 FirewallRule (com.cloud.legacymodel.network.FirewallRule)4 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)3 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)3 Network (com.cloud.legacymodel.network.Network)3 ServerApiException (com.cloud.api.ServerApiException)2 IpForwardingRuleResponse (com.cloud.api.response.IpForwardingRuleResponse)2 Zone (com.cloud.db.model.Zone)2 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)2 NetworkRuleConflictException (com.cloud.legacymodel.exceptions.NetworkRuleConflictException)2 LoadBalancingRule (com.cloud.legacymodel.network.LoadBalancingRule)2 PortForwardingRule (com.cloud.legacymodel.network.PortForwardingRule)2 IpAddress (com.cloud.network.IpAddress)2 PublicIpAddress (com.cloud.network.PublicIpAddress)2 PublicIp (com.cloud.network.addr.PublicIp)2 IPAddressVO (com.cloud.network.dao.IPAddressVO)2 List (java.util.List)2 Commands (com.cloud.agent.manager.Commands)1 ListResponse (com.cloud.api.response.ListResponse)1