Search in sources :

Example 1 with NetworkRuleConflictException

use of com.cloud.legacymodel.exceptions.NetworkRuleConflictException in project cosmic by MissionCriticalCloud.

the class CreateVpnConnectionCmd method create.

@Override
public void create() {
    try {
        final Site2SiteVpnConnection conn = _s2sVpnService.createVpnConnection(this);
        if (conn != null) {
            setEntityId(conn.getId());
            setEntityUuid(conn.getUuid());
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create site to site vpn connection");
        }
    } catch (final NetworkRuleConflictException e) {
        s_logger.info("Network rule conflict: " + e.getMessage());
        s_logger.trace("Network Rule Conflict: ", e);
        throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage());
    }
}
Also used : ServerApiException(com.cloud.api.ServerApiException) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) Site2SiteVpnConnection(com.cloud.network.Site2SiteVpnConnection)

Example 2 with NetworkRuleConflictException

use of com.cloud.legacymodel.exceptions.NetworkRuleConflictException in project cosmic by MissionCriticalCloud.

the class RulesManagerImpl method enableStaticNat.

private boolean enableStaticNat(final long ipId, final long vmId, final long networkId, final boolean isSystemVm, final String vmGuestIp) throws NetworkRuleConflictException, ResourceUnavailableException {
    final CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    CallContext.current().setEventDetails("Ip Id: " + ipId);
    // Verify input parameters
    IPAddressVO ipAddress = _ipAddressDao.findById(ipId);
    if (ipAddress == null) {
        throw new InvalidParameterValueException("Unable to find ip address by id " + ipId);
    }
    // Verify input parameters
    boolean performedIpAssoc = false;
    final boolean isOneToOneNat = ipAddress.isOneToOneNat();
    final Long associatedWithVmId = ipAddress.getAssociatedWithVmId();
    final Nic guestNic;
    NicSecondaryIpVO nicSecIp = null;
    String dstIp = null;
    try {
        final Network network = _networkModel.getNetwork(networkId);
        if (network == null) {
            throw new InvalidParameterValueException("Unable to find network by id");
        }
        // Check that vm has a nic in the network
        guestNic = _networkModel.getNicInNetwork(vmId, networkId);
        if (guestNic == null) {
            throw new InvalidParameterValueException("Vm doesn't belong to the network with specified id");
        }
        dstIp = guestNic.getIPv4Address();
        if (!_networkModel.areServicesSupportedInNetwork(network.getId(), Service.StaticNat)) {
            throw new InvalidParameterValueException("Unable to create static nat rule; StaticNat service is not " + "supported in network with specified id");
        }
        if (!isSystemVm) {
            final UserVmVO vm = _vmDao.findById(vmId);
            if (vm == null) {
                throw new InvalidParameterValueException("Can't enable static nat for the address id=" + ipId + ", invalid virtual machine id specified (" + vmId + ").");
            }
            // associate ip address to network (if needed)
            if (ipAddress.getAssociatedWithNetworkId() == null) {
                final boolean assignToVpcNtwk = network.getVpcId() != null && ipAddress.getVpcId() != null && ipAddress.getVpcId().longValue() == network.getVpcId();
                if (assignToVpcNtwk) {
                    _networkModel.checkIpForService(ipAddress, Service.StaticNat, networkId);
                    s_logger.debug("The ip is not associated with the VPC network id=" + networkId + ", so assigning");
                    try {
                        ipAddress = _ipAddrMgr.associateIPToGuestNetwork(ipId, networkId, false);
                    } catch (final Exception ex) {
                        s_logger.warn("Failed to associate ip id=" + ipId + " to VPC network id=" + networkId + " as " + "a part of enable static nat");
                        return false;
                    }
                }
            } else if (ipAddress.getAssociatedWithNetworkId() != networkId) {
                throw new InvalidParameterValueException("Invalid network Id=" + networkId + ". IP is associated with" + " a different network than passed network id");
            } else {
                _networkModel.checkIpForService(ipAddress, Service.StaticNat, null);
            }
            if (ipAddress.getAssociatedWithNetworkId() == null) {
                throw new InvalidParameterValueException("Ip address " + ipAddress + " is not assigned to the network " + network);
            }
            // Check permissions
            if (ipAddress.getSystem()) {
                // when system is enabling static NAT on system IP's (for EIP) ignore VM state
                checkIpAndUserVm(ipAddress, vm, caller, true);
            } else {
                checkIpAndUserVm(ipAddress, vm, caller, false);
            }
            // dstIp = guestNic.getIp4Address();
            if (vmGuestIp != null) {
                if (!dstIp.equals(vmGuestIp)) {
                    // check whether the secondary ip set to the vm or not
                    final boolean secondaryIpSet = _networkMgr.isSecondaryIpSetForNic(guestNic.getId());
                    if (!secondaryIpSet) {
                        throw new InvalidParameterValueException("VM ip " + vmGuestIp + " address not belongs to the vm");
                    }
                    // check the ip belongs to the vm or not
                    nicSecIp = _nicSecondaryDao.findByIp4AddressAndNicId(vmGuestIp, guestNic.getId());
                    if (nicSecIp == null) {
                        throw new InvalidParameterValueException("VM ip " + vmGuestIp + " address not belongs to the vm");
                    }
                    dstIp = nicSecIp.getIp4Address();
                // Set public ip column with the vm ip
                }
            }
            // Verify ip address parameter
            // checking vm id is not sufficient, check for the vm ip
            isIpReadyForStaticNat(vmId, ipAddress, dstIp, caller, ctx.getCallingUserId());
        }
        ipAddress.setOneToOneNat(true);
        ipAddress.setAssociatedWithVmId(vmId);
        ipAddress.setVmIp(dstIp);
        if (_ipAddressDao.update(ipAddress.getId(), ipAddress)) {
            // enable static nat on the backend
            s_logger.trace("Enabling static nat for ip address " + ipAddress + " and vm id=" + vmId + " on the backend");
            if (applyStaticNatForIp(ipId, false, caller, false)) {
                // ignor unassignIPFromVpcNetwork in finally block
                performedIpAssoc = false;
                return true;
            } else {
                s_logger.warn("Failed to enable static nat rule for ip address " + ipId + " on the backend");
                ipAddress.setOneToOneNat(isOneToOneNat);
                ipAddress.setAssociatedWithVmId(associatedWithVmId);
                ipAddress.setVmIp(null);
                _ipAddressDao.update(ipAddress.getId(), ipAddress);
            }
        } else {
            s_logger.warn("Failed to update ip address " + ipAddress + " in the DB as a part of enableStaticNat");
        }
    } finally {
        if (performedIpAssoc) {
            // if the rule is the last one for the ip address assigned to VPC, unassign it from the network
            final IpAddress ip = _ipAddressDao.findById(ipAddress.getId());
            _vpcMgr.unassignIPFromVpcNetwork(ip.getId(), networkId);
        }
    }
    return false;
}
Also used : Account(com.cloud.legacymodel.user.Account) UserVmVO(com.cloud.vm.UserVmVO) Nic(com.cloud.legacymodel.network.Nic) CallContext(com.cloud.context.CallContext) 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) NicSecondaryIpVO(com.cloud.vm.dao.NicSecondaryIpVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Network(com.cloud.legacymodel.network.Network) IPAddressVO(com.cloud.network.dao.IPAddressVO) IpAddress(com.cloud.network.IpAddress)

Example 3 with NetworkRuleConflictException

use of com.cloud.legacymodel.exceptions.NetworkRuleConflictException 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 4 with NetworkRuleConflictException

use of com.cloud.legacymodel.exceptions.NetworkRuleConflictException in project cosmic by MissionCriticalCloud.

the class RulesManagerImpl method getSystemIpAndEnableStaticNatForVm.

@Override
public void getSystemIpAndEnableStaticNatForVm(final VirtualMachine vm, final boolean getNewIp) throws InsufficientAddressCapacityException {
    boolean success = true;
    // enable static nat if eIp capability is supported
    final List<? extends Nic> nics = _nicDao.listByVmId(vm.getId());
    for (final Nic nic : nics) {
        final Network guestNetwork = _networkModel.getNetwork(nic.getNetworkId());
        final NetworkOffering offering = _entityMgr.findById(NetworkOffering.class, guestNetwork.getNetworkOfferingId());
        if (offering.getElasticIp()) {
            final boolean isSystemVM = (vm.getType() == VirtualMachineType.ConsoleProxy || vm.getType() == VirtualMachineType.SecondaryStorageVm);
            // for user VM's associate public IP only if offering is marked to associate a public IP by default on start of VM
            if (!isSystemVM && !offering.getAssociatePublicIP()) {
                continue;
            }
            // check if there is already static nat enabled
            if (_ipAddressDao.findByAssociatedVmId(vm.getId()) != null && !getNewIp) {
                s_logger.debug("Vm " + vm + " already has ip associated with it in guest network " + guestNetwork);
                continue;
            }
            s_logger.debug("Allocating system ip and enabling static nat for it for the vm " + vm + " in guest network " + guestNetwork);
            final IpAddress ip = _ipAddrMgr.assignSystemIp(guestNetwork.getId(), _accountMgr.getAccount(vm.getAccountId()), false, true);
            if (ip == null) {
                throw new CloudRuntimeException("Failed to allocate system ip for vm " + vm + " in guest network " + guestNetwork);
            }
            s_logger.debug("Allocated system ip " + ip + ", now enabling static nat on it for vm " + vm);
            try {
                success = enableStaticNat(ip.getId(), vm.getId(), guestNetwork.getId(), isSystemVM, null);
            } catch (final NetworkRuleConflictException ex) {
                s_logger.warn("Failed to enable static nat as a part of enabling elasticIp and staticNat for vm " + vm + " in guest network " + guestNetwork + " due to exception ", ex);
                success = false;
            } catch (final ResourceUnavailableException ex) {
                s_logger.warn("Failed to enable static nat as a part of enabling elasticIp and staticNat for vm " + vm + " in guest network " + guestNetwork + " due to exception ", ex);
                success = false;
            }
            if (!success) {
                s_logger.warn("Failed to enable static nat on system ip " + ip + " for the vm " + vm + ", releasing the ip...");
                _ipAddrMgr.handleSystemIpRelease(ip);
                throw new CloudRuntimeException("Failed to enable static nat on system ip for the vm " + vm);
            } else {
                s_logger.warn("Succesfully enabled static nat on system ip " + ip + " for the vm " + vm);
            }
        }
    }
}
Also used : NetworkOffering(com.cloud.offering.NetworkOffering) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) Nic(com.cloud.legacymodel.network.Nic) IpAddress(com.cloud.network.IpAddress) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException)

Example 5 with NetworkRuleConflictException

use of com.cloud.legacymodel.exceptions.NetworkRuleConflictException in project cosmic by MissionCriticalCloud.

the class RulesManagerImpl method reservePorts.

@Override
@DB
public FirewallRuleVO[] reservePorts(final IpAddress ip, final String protocol, final FirewallRule.Purpose purpose, final boolean openFirewall, final Account caller, final int... ports) throws NetworkRuleConflictException {
    final FirewallRuleVO[] rules = new FirewallRuleVO[ports.length];
    Transaction.execute(new TransactionCallbackWithExceptionNoReturn<NetworkRuleConflictException>() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) throws NetworkRuleConflictException {
            for (int i = 0; i < ports.length; i++) {
                rules[i] = new FirewallRuleVO(null, ip.getId(), ports[i], protocol, ip.getAssociatedWithNetworkId(), ip.getAllocatedToAccountId(), ip.getAllocatedInDomainId(), purpose, null, null, null, null);
                rules[i] = _firewallDao.persist(rules[i]);
                if (openFirewall) {
                    _firewallMgr.createRuleForAllCidrs(ip.getId(), caller, ports[i], ports[i], protocol, null, null, rules[i].getId(), ip.getAssociatedWithNetworkId());
                }
            }
        }
    });
    boolean success = false;
    try {
        for (final FirewallRuleVO newRule : rules) {
            _firewallMgr.detectRulesConflict(newRule);
        }
        success = true;
        return rules;
    } finally {
        if (!success) {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    for (final FirewallRuleVO newRule : rules) {
                        _firewallMgr.removeRule(newRule);
                    }
                }
            });
        }
    }
}
Also used : TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) DB(com.cloud.utils.db.DB)

Aggregations

NetworkRuleConflictException (com.cloud.legacymodel.exceptions.NetworkRuleConflictException)26 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)14 ServerApiException (com.cloud.api.ServerApiException)12 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)10 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)9 Network (com.cloud.legacymodel.network.Network)8 IPAddressVO (com.cloud.network.dao.IPAddressVO)8 DB (com.cloud.utils.db.DB)7 TransactionStatus (com.cloud.utils.db.TransactionStatus)7 InsufficientAddressCapacityException (com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException)6 Account (com.cloud.legacymodel.user.Account)6 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)5 CallContext (com.cloud.context.CallContext)4 ActionEvent (com.cloud.event.ActionEvent)4 IpAddress (com.cloud.network.IpAddress)4 NetworkOffering (com.cloud.offering.NetworkOffering)4 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)3 ResourceAllocationException (com.cloud.legacymodel.exceptions.ResourceAllocationException)3 FirewallRule (com.cloud.legacymodel.network.FirewallRule)3 Ip (com.cloud.legacymodel.network.Ip)3