Search in sources :

Example 21 with NetworkRuleConflictException

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

the class FirewallManagerTest method testDetectRulesConflict.

@Test
public void testDetectRulesConflict() {
    final List<FirewallRuleVO> ruleList = new ArrayList<>();
    final FirewallRuleVO rule1 = spy(new FirewallRuleVO("rule1", 3, 500, "UDP", 1, 2, 1, Purpose.Vpn, null, null, null, null));
    final FirewallRuleVO rule2 = spy(new FirewallRuleVO("rule2", 3, 1701, "UDP", 1, 2, 1, Purpose.Vpn, null, null, null, null));
    final FirewallRuleVO rule3 = spy(new FirewallRuleVO("rule3", 3, 4500, "UDP", 1, 2, 1, Purpose.Vpn, null, null, null, null));
    ruleList.add(rule1);
    ruleList.add(rule2);
    ruleList.add(rule3);
    final FirewallManagerImpl firewallMgr = (FirewallManagerImpl) _firewallMgr;
    when(firewallMgr._firewallDao.listByIpAndPurposeAndNotRevoked(3, null)).thenReturn(ruleList);
    when(rule1.getId()).thenReturn(1L);
    when(rule2.getId()).thenReturn(2L);
    when(rule3.getId()).thenReturn(3L);
    final FirewallRule newRule1 = new FirewallRuleVO("newRule1", 3, 500, "TCP", 1, 2, 1, Purpose.PortForwarding, null, null, null, null);
    final FirewallRule newRule2 = new FirewallRuleVO("newRule2", 3, 1701, "TCP", 1, 2, 1, Purpose.PortForwarding, null, null, null, null);
    final FirewallRule newRule3 = new FirewallRuleVO("newRule3", 3, 4500, "TCP", 1, 2, 1, Purpose.PortForwarding, null, null, null, null);
    try {
        firewallMgr.detectRulesConflict(newRule1);
        firewallMgr.detectRulesConflict(newRule2);
        firewallMgr.detectRulesConflict(newRule3);
    } catch (final NetworkRuleConflictException ex) {
        Assert.fail();
    }
}
Also used : ArrayList(java.util.ArrayList) FirewallRule(com.cloud.legacymodel.network.FirewallRule) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) Test(org.junit.Test)

Example 22 with NetworkRuleConflictException

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

the class ApiDispatcher method dispatch.

public void dispatch(final BaseCmd cmd, final Map<String, String> params, final boolean execute) throws CloudException {
    // Let the chain of responsibility dispatch gradually
    standardDispatchChain.dispatch(new DispatchTask(cmd, params));
    final CallContext ctx = CallContext.current();
    ctx.setEventDisplayEnabled(cmd.isDisplay());
    if (params.get(ApiConstants.PROJECT_ID) != null) {
        final Project project = _entityMgr.findByUuidIncludingRemoved(Project.class, params.get(ApiConstants.PROJECT_ID));
        ctx.setProject(project);
    }
    // TODO This if shouldn't be here. Use polymorphism and move it to validateSpecificParameters
    if (cmd instanceof BaseAsyncCmd) {
        final BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmd;
        final String startEventId = params.get(ApiConstants.CTX_START_EVENT_ID);
        ctx.setStartEventId(Long.parseLong(startEventId));
        // Synchronise job on the object if needed
        if (asyncCmd.getJob() != null && asyncCmd.getSyncObjId() != null && asyncCmd.getSyncObjType() != null) {
            final Long queueSizeLimit;
            if (asyncCmd.getSyncObjType() != null && asyncCmd.getSyncObjType().equalsIgnoreCase(BaseAsyncCmd.snapshotHostSyncObject)) {
                queueSizeLimit = _createSnapshotQueueSizeLimit;
            } else {
                queueSizeLimit = 1L;
            }
            if (queueSizeLimit != null) {
                if (!execute) {
                    // if we are not within async-execution context, enqueue the command
                    _asyncMgr.syncAsyncJobExecution((AsyncJob) asyncCmd.getJob(), asyncCmd.getSyncObjType(), asyncCmd.getSyncObjId().longValue(), queueSizeLimit);
                    return;
                }
            } else {
                s_logger.trace("The queue size is unlimited, skipping the synchronizing");
            }
        }
    }
    // TODO This if shouldn't be here. Use polymorphism and move it to validateSpecificParameters
    if (cmd instanceof BaseAsyncCustomIdCmd) {
        ((BaseAsyncCustomIdCmd) cmd).checkUuid();
    } else if (cmd instanceof BaseCustomIdCmd) {
        ((BaseCustomIdCmd) cmd).checkUuid();
    }
    try {
        cmd.execute();
    } catch (ResourceUnavailableException | InsufficientCapacityException | ResourceAllocationException | NetworkRuleConflictException e) {
        throw new CloudException("Caught exception while executing command", e);
    }
}
Also used : CloudException(com.cloud.legacymodel.exceptions.CloudException) CallContext(com.cloud.context.CallContext) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) Project(com.cloud.projects.Project) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) DispatchTask(com.cloud.api.dispatch.DispatchTask)

Example 23 with NetworkRuleConflictException

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

the class VpcManagerImpl method createStaticRoute.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_STATIC_ROUTE_CREATE, eventDescription = "creating static route", create = true)
public StaticRoute createStaticRoute(final long vpcId, final String cidr, final String gwIpAddress) throws NetworkRuleConflictException {
    final Account caller = CallContext.current().getCallingAccount();
    final Vpc vpc = getActiveVpc(vpcId);
    if (vpc == null) {
        throw new InvalidParameterValueException("Can't add static route to VPC that is being deleted");
    }
    _accountMgr.checkAccess(caller, null, false, vpc);
    if (!NetUtils.isValidIp4Cidr(cidr)) {
        throw new InvalidParameterValueException("Invalid format for cidr " + cidr);
    }
    if (!NetUtils.isValidIp4(gwIpAddress)) {
        throw new InvalidParameterValueException("Invalid format for ip address " + gwIpAddress);
    }
    // CIDR should be outside of link-local cidr
    if (NetUtils.isNetworkAWithinNetworkB(cidr, NetUtils.getLinkLocalCIDR())) {
        throw new InvalidParameterValueException("CIDR should be outside of link local cidr " + NetUtils.getLinkLocalCIDR());
    }
    // Verify against blacklisted routes
    if (isCidrBlacklisted(cidr, vpc.getZoneId())) {
        throw new InvalidParameterValueException("The static gateway cidr overlaps with one of the blacklisted routes of the zone the VPC belongs to");
    }
    return Transaction.execute(new TransactionCallbackWithException<StaticRouteVO, NetworkRuleConflictException>() {

        @Override
        public StaticRouteVO doInTransaction(final TransactionStatus status) throws NetworkRuleConflictException {
            StaticRouteVO newRoute = new StaticRouteVO(cidr, vpc.getId(), vpc.getAccountId(), vpc.getDomainId(), gwIpAddress);
            s_logger.debug("Adding static route " + newRoute);
            newRoute = _staticRouteDao.persist(newRoute);
            detectDuplicateCidr(newRoute);
            if (!_staticRouteDao.setStateToAdd(newRoute)) {
                throw new CloudRuntimeException("Unable to update the state to add for " + newRoute);
            }
            CallContext.current().setEventDetails("Static route Id: " + newRoute.getId());
            return newRoute;
        }
    });
}
Also used : Account(com.cloud.legacymodel.user.Account) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Vpc(com.cloud.legacymodel.network.vpc.Vpc) TransactionStatus(com.cloud.utils.db.TransactionStatus) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 24 with NetworkRuleConflictException

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

the class RulesManagerImpl method isIpReadyForStaticNat.

protected void isIpReadyForStaticNat(final long vmId, final IPAddressVO ipAddress, final String vmIp, final Account caller, final long callerUserId) throws NetworkRuleConflictException, ResourceUnavailableException {
    if (ipAddress.isSourceNat()) {
        throw new InvalidParameterValueException("Can't enable static, ip address " + ipAddress + " is a sourceNat ip address");
    }
    if (!ipAddress.isOneToOneNat()) {
        // Dont allow to enable static nat if PF/LB rules exist for the IP
        final List<FirewallRuleVO> portForwardingRules = _firewallDao.listByIpAndPurposeAndNotRevoked(ipAddress.getId(), Purpose.PortForwarding);
        if (portForwardingRules != null && !portForwardingRules.isEmpty()) {
            throw new NetworkRuleConflictException("Failed to enable static nat for the ip address " + ipAddress + " as it already has PortForwarding rules assigned");
        }
        final List<FirewallRuleVO> loadBalancingRules = _firewallDao.listByIpAndPurposeAndNotRevoked(ipAddress.getId(), Purpose.LoadBalancing);
        if (loadBalancingRules != null && !loadBalancingRules.isEmpty()) {
            throw new NetworkRuleConflictException("Failed to enable static nat for the ip address " + ipAddress + " as it already has LoadBalancing rules assigned");
        }
    } else if (ipAddress.getAssociatedWithVmId() != null && ipAddress.getAssociatedWithVmId().longValue() != vmId) {
        throw new NetworkRuleConflictException("Failed to enable static for the ip address " + ipAddress + " and vm id=" + vmId + " as it's already assigned to antoher vm");
    }
    // check wether the vm ip is alreday associated with any public ip address
    final IPAddressVO oldIP = _ipAddressDao.findByAssociatedVmIdAndVmIp(vmId, vmIp);
    if (oldIP != null) {
        // If elasticIP functionality is supported in the network, we always have to disable static nat on the old
        // ip in order to re-enable it on the new one
        final Long networkId = oldIP.getAssociatedWithNetworkId();
        final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
        boolean reassignStaticNat = false;
        if (networkId != null) {
            final Network guestNetwork = _networkModel.getNetwork(networkId);
            final NetworkOffering offering = _entityMgr.findById(NetworkOffering.class, guestNetwork.getNetworkOfferingId());
            if (offering.getElasticIp()) {
                reassignStaticNat = true;
            }
        }
        // If there is public ip address already associated with the vm, throw an exception
        if (!reassignStaticNat) {
            throw new InvalidParameterValueException("Failed to enable static nat on the  ip " + ipAddress.getAddress() + " with Id " + ipAddress.getUuid() + " as the vm " + vm.getInstanceName() + " with Id " + vm.getUuid() + " is already associated with another public ip " + oldIP.getAddress() + " with id " + oldIP.getUuid());
        }
        // unassign old static nat rule
        s_logger.debug("Disassociating static nat for ip " + oldIP);
        if (!disableStaticNat(oldIP.getId(), caller, callerUserId, true)) {
            throw new CloudRuntimeException("Failed to disable old static nat rule for vm " + vm.getInstanceName() + " with id " + vm.getUuid() + "  and public ip " + oldIP);
        }
    }
}
Also used : InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) NetworkOffering(com.cloud.offering.NetworkOffering) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) VMInstanceVO(com.cloud.vm.VMInstanceVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException)

Example 25 with NetworkRuleConflictException

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

the class FirewallManagerImpl method createFirewallRule.

@DB
protected FirewallRule createFirewallRule(final Long ipAddrId, final Account caller, final String xId, final Integer portStart, final Integer portEnd, final String protocol, final List<String> sourceCidrList, final Integer icmpCode, final Integer icmpType, final Long relatedRuleId, final FirewallRule.FirewallRuleType type, final Long networkId, final FirewallRule.TrafficType trafficType, final Boolean forDisplay) throws NetworkRuleConflictException {
    IPAddressVO ipAddress = null;
    if (ipAddrId != null) {
        // this for ingress firewall rule, for egress id is null
        ipAddress = _ipAddressDao.findById(ipAddrId);
        // Validate ip address
        if (ipAddress == null && type == FirewallRule.FirewallRuleType.User) {
            throw new InvalidParameterValueException("Unable to create firewall rule; " + "couldn't locate IP address by id in the system");
        }
        _networkModel.checkIpForService(ipAddress, Service.Firewall, null);
    }
    validateFirewallRule(caller, ipAddress, portStart, portEnd, protocol, Purpose.Firewall, type, networkId, trafficType);
    // icmp code and icmp type can't be passed in for any other protocol rather than icmp
    if (!protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (icmpCode != null || icmpType != null)) {
        throw new InvalidParameterValueException("Can specify icmpCode and icmpType for ICMP protocol only");
    }
    if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (portStart != null || portEnd != null)) {
        throw new InvalidParameterValueException("Can't specify start/end port when protocol is ICMP");
    }
    Long accountId = null;
    Long domainId = null;
    if (ipAddress != null) {
        // Ingress firewall rule
        accountId = ipAddress.getAllocatedToAccountId();
        domainId = ipAddress.getAllocatedInDomainId();
    } else if (networkId != null) {
        // egress firewall rule
        final Network network = _networkModel.getNetwork(networkId);
        accountId = network.getAccountId();
        domainId = network.getDomainId();
    }
    final Long accountIdFinal = accountId;
    final Long domainIdFinal = domainId;
    return Transaction.execute(new TransactionCallbackWithException<FirewallRuleVO, NetworkRuleConflictException>() {

        @Override
        public FirewallRuleVO doInTransaction(final TransactionStatus status) throws NetworkRuleConflictException {
            FirewallRuleVO newRule = new FirewallRuleVO(xId, ipAddrId, portStart, portEnd, protocol.toLowerCase(), networkId, accountIdFinal, domainIdFinal, Purpose.Firewall, sourceCidrList, icmpCode, icmpType, relatedRuleId, trafficType);
            newRule.setType(type);
            if (forDisplay != null) {
                newRule.setDisplay(forDisplay);
            }
            newRule = _firewallDao.persist(newRule);
            if (type == FirewallRuleType.User) {
                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());
            return newRule;
        }
    });
}
Also used : InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) TransactionStatus(com.cloud.utils.db.TransactionStatus) IPAddressVO(com.cloud.network.dao.IPAddressVO) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) 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